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

Categories

0 votes
426 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...