how to ask user to input again and again after every invalid input

匿名 (未验证) 提交于 2019-12-03 02:41:02

问题:

so my own valid dates only are from 1520 to 3999 and im new to this site and im new to java please help i want to know what did i do wrong or what to do in this code.

    int x;     Scanner in = new Scanner (System.in);     do     {         System.out.print ("Enter a date ");         x = in.nextInt();     }     while (x<1520&&x>3999);     {         System.out.println ("Invalid Gregorian Calendar date.");         System.out.print ("Please Input a valid Gregorian Calendar date: ");     } }} 

回答1:

In the while loop, get another integer whenever the input was invalid. Also, you need to change && to || in your while condition, as no number is both less than 1520 and greater than 3999. You also do not need the do section, and you need to remove the semicolon after your while loop - it was preventing the loop from doing anything productive for you.

int x; Scanner in = new Scanner (System.in); System.out.print ("Enter a date "); x = in.nextInt();  while (x<1520 || x>3999) // change this to "or", i.e. && --> ||      {         System.out.println ("Invalid Gregorian Calendar date.");         System.out.print ("Please Input a valid Gregorian Calendar date: ");         x = in.nextInt(); // get another number before checking conditions again     } 


回答2:

&& operator is logical AND

Input value cannot be less than 1520 AND greater than 3999. I think you want to check if x is less than 1520 OR greater than 3999.

To achive this you should use proper logical operator, in this case it is OR

x<1520 || x>3999



回答3:

You can change your code as follows (note, I changed the && to an ||, because there is no number that is both greater than 3999 AND less than 1520.)

    int x;      Scanner in = new Scanner (System.in);     System.out.print("Enter a date ");     x = in.nextInt();       while (x < 1520 || x > 3999)     {         System.out.println ("Invalid Gregorian Calendar date.");         System.out.print ("Please Input a valid Gregorian Calendar date: ");         x = in.nextInt();     } } 


回答4:

You need to ask the user in a while loop until he enters the correct date.

int x;     Scanner in = new Scanner (System.in); System.out.print ("Enter a date ");         x = in.nextInt();      while (x<1520||x>3999)     {         System.out.println ("Invalid Gregorian Calendar date.");         System.out.print ("Please Input a valid Gregorian Calendar date: "); x = in.nextInt();     } }} 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!