0
まずタイトルのゴアにお詫び申し上げます。ユーザーの初期入力が無効な場合に新しいユーザー入力を取得しようとしています。しかし、スキャナオブジェクトは最初の値を使用し続けます
次のコードで私がここで理解しようとしている具体的なことは、2回目に呼び出されたときにgetNumber関数が同じ初期ユーザー入力を返し続け、新しいユーザー入力を要求しない理由です。 documentationで
/*Write an application that inputs one number consisting
of five digits from the user, separates the number into its individual digits and prints the digits
separated from one another by three spaces each.
*/
public class SeparatingDigitsOfInt {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
boolean check =false;
String s=null;
while (check==false)
{
s= Integer.toString(getNumber()); //since user input was a string, getNumber returns 0 and we enter the while loop below
while (s.equals("0"))// here i am trying to get another input from user because first input was invalid
{
System.out.println("Try that again!");
s= Integer.toString(getNumber()); // why getNumber continues to return xyz here and doesn't ask for new user input
check =false;
}
check =true;
}
System.out.println(s);
while(s.length()!= 5){
System.out.println("Input number is not of 5 digits!");
System.out.println("Please enter a 5 digit number");
s = input.next();
}
String result = "";
for (int i = 0; i < s.length(); i++) {
result= result + s.charAt(i) + " ";
}
System.out.println("Result is :" + result);
}
public static int getNumber(){
try {
System.out.println("Enter a 5 digit number");
return input.nextInt(); // user inputs string xyz
}
catch (InputMismatchException e) {
System.out.println("Please enter only numbers");
return 0;// since user inputs xyz, so 0 is returned by getNumber
}
}
}
@shmoselありがとう! – Crabster