Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

integer - Java 3.6 Checking inputs

Ask the user to "Input a number: " 4 times. If the input is not a number, ask again. Output "success." after they have entered 4 numbers. Please answer this code for me using while, if, if else and do statements.

int counter; System.out.print("Input a number: "); 
while(!(scan.hasNextInt()));{ 
  for (int i = 0; i < 3; i++){ 
    scan.next(); 
    System.out.print("Input a number: "); 
    if (!(pass.equals(pass2))) { 
      counter++; 
    } else if (!(scan.hasNextInt())) {

    }
  } 
  if (counter >= 2) { 
    System.out.println("Input a number: "); 
  }
} else if (!(scan.hasNextInt())) { System.out.println("success."); }

This is very basic stuff but I am struggling.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
int[] inputIntegers = new int[4]; // Array to save input
Scanner scan = new Scanner(System.in); 
int counter = 0;
while(counter < 4) {
    System.out.println("Input a number: ");
    String input = scan.next();
    if(input.matches("[-]?[0-9]*")){  // Checking, if input is an integer
        inputIntegers[counter]=Integer.parseInt(input); // Persing string to integer
        counter++;
    } else {
        System.out.println("Input is not an integer");
    }
}
System.out.println("Success");
scan.close(); //Do not forget do close scanner

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...