2017-01-25 1 views
1

Я пытаюсь выполнить программу: Если введенные данные не принимаются, запросите информацию повторно (обратите внимание: это нормально, чтобы запросить всю информацию снова, это не обязательно чтобы запрашивать конкретную информацию для повторного ввода, но вы можете, если хотите).Использование цикла и инкапсуляции

Для программы все, кажется, работает нормально, за исключением того, когда его разрешение, оно запрашивает другой вход, но если вход неверен, он просто принимает. Мне нужно, чтобы он продолжал работать до ввода правильного ввода.

import java.util.Scanner; 
public class encap 
{ 
    private static String userID; 
    private static String password; 
    private static String resolution; 
    private static int Ramsize; 
    private static int freespace; 
    private static int videocard; 

    //Get and Set methods 

    public static String getuserID() 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Please enter userID : "); 
     userID = input.next(); 
     return userID; 
    } 
    public static String getpassword() 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Please enter password : "); 
     password = input.next(); 
     return password; 
    } 
    public static String getresolution() 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Please enter video resolution: "); 
     resolution = input.next(); 
     if (resolution.equals("800x600") || resolution.equals("1024x768") || resolution.equals("1152x900")); 
     else 
     { 
      while(true) 
      { 
       System.out.println("Information invalid, Please fill again"); 
       String getresolution = input.next(); 
       if (resolution.equals("800x600") || resolution.equals("1024x768") || resolution.equals("1152x900")); 
       break; 
      } 
     } 
     return resolution; 
    } 

    public static int getRamsize() 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Please enter RAM size : "); 
     while(true) 
     { 
      if(input.hasNextInt()) 
      { 
       Ramsize = input.nextInt(); 
       break; 
      } 
      else 
      { 
      input.nextLine(); 
      System.out.println("Invalid Input! Integer required"); 
      System.out.print("Please enter RAM size : "); 
      } 
     } 
     return Ramsize; 
    } 
    public static int getfreespace() 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Please enter HD free space : "); 
     while(true) 
     { 
      if(input.hasNextInt()) 
      { 
       freespace = input.nextInt(); 
       break; 
      } 
      else 
      { 
       input.nextLine(); 
       System.out.println("Invalid Input! Integer required"); 
       System.out.print("Please enter HD free space : "); 

      } 
     } 
     return freespace; 
    } 

    public static int getvideocard() 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Please enter video card RAM size: "); 
     while(true) 
     { 
      if(input.hasNextInt()) 
      { 
       videocard = input.nextInt(); 
       break; 
      } 
      else 
      { 
       input.nextLine(); 
       System.out.println("Invalid Input! Integer required"); 
       System.out.print("Please enter video card RAM size: "); 
      } 
     } 
     return videocard; 
    } 

    public static void setuserID(String newuserID) 
    { 
     userID = newuserID; 
    } 
    public static void setpassword(String newpassword) 
    { 
     password = newpassword; 
    } 
    public static void setresolution(String newresolution) 
    { 
     resolution = newresolution; 
    } 

    public static void setRamsize (int newRamsize) 
    { 
     Ramsize = newRamsize; 
    } 

    public static void setfreespace (int newfreespace) 
    { 
     freespace = newfreespace; 
    } 

    public static void setvideocard (int newvideocard) 
    { 
     videocard = newvideocard; 
    } 
    public static void main(String[] args) 
    { 
    setuserID(getuserID()); 
    setpassword(getpassword()); 
    setresolution(getresolution()); 
    setRamsize(getRamsize()); 
    setfreespace(getfreespace()); 
    setvideocard(getvideocard()); 
    System.out.println("You have input the following information: " + "\nuserID: " + userID 
      + "\npassword: " + password + "\nVideo resolution: " + resolution + "\nRam Size: " 
      + Ramsize + "\nHD Free Space: " + freespace + "\nVideo Card Ram Size: " + videocard); 
    } 
} 
+1

Почему у вас, если внутри getresolution, есть точка с запятой непосредственно после нее? вы ничего не делаете, если вход действителен –

+0

теперь цикл просто продолжает работать и просит ввода, даже если я ввожу 800x600, он не сломается. – tubvajlis

+0

Не говоря уже о проблеме с точкой с запятой в состоянии 'if', но есть' while (true) 'в состоянии' else', которое вызовет бесконечный цикл;) –

ответ

0

Проблема в том, что вы никогда ничего не делать в течение Вашего действительного сценария дела, и вы используете .next() для одного символа вместо .nextLine(), который захватывает весь вход вошел после конца строки символа (возвращаемый символ)

Это будет запрашивать, пока введенный ввод не удовлетворит ваши условия if.

public static String getresolution() 
{ 
    String resolution; 
    boolean validAnswer = false; 
    Scanner input = new Scanner(System.in); 
    HashSet<String> validResolutions = new HashSet<>(); 
    validResolutions.add("800x600"); 
    validResolutions.add("1024x768"); 
    validResolutions.add("1152x900"); 
    //add more resolutions if you want without having to create a bigger if check 
    //validResolutions.add("1400x1120"); 

    do { 
     System.out.print("Please enter video resolution: "); 
     resolution = input.nextLine().replaceAll(" ", "").replaceAll("\n", ""); 
     validAnswer = validResolutions.contains(resolution) ? true : false; 
     if(!validAnswer) 
      System.out.println("Incorrect resolution please try again"); 
    } while (!validAnswer); 

    return resolution; 
} 
+0

Спасибо, что сработало. – tubvajlis

+0

это замечательно, пожалуйста, не стесняйтесь отмечать как ответ, если он работает, чтобы закрыть вопрос :) удачи с остальной частью вашего задания. –

Смежные вопросы