Java 如何使程序在循环中获取变量?(爪哇)

Java 如何使程序在循环中获取变量?(爪哇),java,loops,java.util.scanner,Java,Loops,Java.util.scanner,我正在做一个程序,要求你的年龄,但它不工作。 首先,它通过扫描器模块询问您的年龄,并将您的年龄放入一个变量中。我想在您的年龄结束时输出,但它需要一个int,因此如果您输入字符串或其他内容,则会出现错误: Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source)

我正在做一个程序,要求你的年龄,但它不工作。 首先,它通过扫描器模块询问您的年龄,并将您的年龄放入一个变量中。我想在您的年龄结束时输出,但它需要一个int,因此如果您输入字符串或其他内容,则会出现错误:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at org.asking.age.main(asking.java:18)
我想让他说,而不是错误):请只输入一个介于1和100之间的数字,如果您输入其他数字,则输入一个介于1-100之间的数字。如果你输入了一个错误的号码,它必须“重新启动”,如果它是一个好的号码,它必须结束

我尝试了一个循环:

(i=来自扫描仪的年龄)

while(i>100 | i>0)
{
如果(a<100 | a>0){
System.out.println(“请只输入1到100之间的数字”);
System.out.println(“你多大了?”);
扫描仪s=新的扫描仪(System.in);
int a=s.nextInt();
{
System.out.println(“你是“+a+”岁”)
}}}}}
但在开始时,“如果”不能到达a变量。是否有其他/任何方法可以做到这一点

谢谢你的帮助,很抱歉我的英语不好:)

感谢@TheLostMind的帮助,现在我得到了以下代码:

但是我不知道如何使用if(>0&& 首先,首先在
扫描仪
inta
外部贴花 循环

接下来,使用
scanner\nextLine()
将整行输入读取到 绳子

然后使用
String#matches(\\d+)
Integer.parseInt(inputString)
将int解析为数字


然后使用
如果(>0&&您需要这样做:

Declare Scanner and other Variable 

do {
   System.out.println("please only enter a number between 1 and 100");
   System.out.println("how old are you?");

   read variable value from Scanner
} while(check your condition on variable);

希望这有帮助。

System.out.print和扫描仪中的问题应该在循环之外。
检查while循环,它会显示>100,而不是在while循环外定义扫描仪。while循环外既有
扫描仪
又有
int a
。您的问题是因为您从扫描仪读取整数,而您输入的不是数值。我的建议是使用line,然后检查它是有效数字还是其他数字报告错误或继续,小的旁注,
i>100 | i>0
可以重写为
x>0
public static void main(String[] args)  {
    System.out.println("how old are you?");

    Scanner h = new Scanner(System.in);
    String a= h.nextLine();

    String str = a;

    String matches=("\\d+");

    Integer.parseInt(a);



    {
do {


   System.out.println("please only enter a number between 1 and 100");
   System.out.println("how old are you?");
   h.nextLine();

} while(a>0 && a<100); }
}
}
Declare Scanner and other Variable 

do {
   System.out.println("please only enter a number between 1 and 100");
   System.out.println("how old are you?");

   read variable value from Scanner
} while(check your condition on variable);