首页 > 解决方案 > Java 3.6 检查输入

问题描述

要求用户“输入数字:” 4 次。如果输入不是数字,请再次询问。输出“成功”。在他们输入了 4 个数字后。请使用 while、if、if else 和 do 语句为我回答此代码。

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."); }

这是非常基本的东西,但我很挣扎。

标签: javaintegerdo-while

解决方案


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

推荐阅读