2016-06-28 50 views
1

我正在做一个程序,要求你的年龄,但它不工作。 首先它会询问扫描仪模块的年龄,并将您的年龄放入变量中。我想在结束你的年龄输出,但它需要一个整型,所以如果你把一个字符串或其他什么东西它给出了一个错误:我该如何让一个程序在循环中获得一个变量? (java)

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) 
     { 
      if (a < 100 || a > 0) { 

       System.out.println("please only enter a number between 1 and 100"); 
       System.out.println("how old are you?"); 
       Scanner s = new Scanner(System.in); 
       int a = s.nextInt(); 

     { 
System.out.println("you are " + a + "years old") 
    }}}}} 

,但在开始时的 '如果' 斜面到达的变量。是否存在其他/任何方式来做到这一点?

感谢您的帮助,而我的英语不好:)

感谢对不起@TheLostMind现在帮助我得到这个代码:

,但我不知道如何使用if(> 0 & & < 100,比赛不工作

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); } 
} 
} 
+0

在while循环外定义您的扫描仪 –

+3

对循环外的'Scanner'和'int a'进行Decalre。 – TheLostMind

+0

您的问题是由于您从扫描仪读取整数而创建的,而您输入的不是数字值。我的建议是使用行,然后检查它是一个有效的数字或别的东西报告错误或继续进行,小方评论,'i> 100 || i> 0'可以被重写为'x> 0', – user902383

回答

1

First of all, start by decalring both Scanner and int a outside the loop.

Next, use scanner#nextLine() to read an entire line of input into a String.

Then use String#matches("\\d+") and Integer.parseInt(inputString) to parse the int as a number.

Then use if(>0 && <100) check.

里有方法类(hasNextInt())等待int,但这不是你正在寻找。

1

你需要做这样的事情:

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); 

希望这有助于。

1

是System.out.print中和扫描仪的问题,应该是外循环。 检查while循环,它表示> 100而不是< 100.

相关问题