2015-10-15 116 views
0

我的程序出现问题。一切都运行平稳,但是,当用户输入错误的变量时,它显示正确的反馈,但用户必须输入一个额外的变量。Java程序使用户在初始输入错误后输入两次相同的输入以运行

也许这是一个简单的错误我已经作出,但我不能看到它..

这是令人困惑的。一个例子,当我运行该程序:

How many grades would you like to average? 
3 

Please enter 3 grades: 
90 
jf //Intentional user input error 
You've entered a non-numerical variable. Please enter a number: 
95 
100 //The program should go ahead and calculate the average after this is entered 
100 //It should not expect this fourth input if the amount of grades is 3 

Your average is: 96.67 

在控制台中的第二输入100不应出现,但是当用户具有至少一个输入错误它。如果我要运行程序并输入所有正确的变量,那么程序运行平稳。

当询问用户想要平均分多少个等级时,也会发生此错误。我认为第二部分可以更容易地查看我的程序出了什么问题。

我试图让这个程序顺利运行。帮助表示赞赏!

for (gradesCount = 0; gradesCount < gradeNumber; gradesCount++) { 
      // Check if the input variables are numerical variables 
      while (!input.hasNextDouble()) { 
       input.next(); 
       System.out.println("You've entered a non-numerical variable. Please enter a number: "); 
       while (input.nextInt()<= 0){ 

       System.out.println("You've entered a negative number. Please eneter a positive number: "); 
       } 

      } 
      // Read grade input 
      gradesInput = input.nextDouble(); 

回答

0

相反的input.hasNextDouble()你可以试试下面

Scanner scan = new Scanner(System.in); 
    System.out.print("Enter total no of input "); 
    int total = Integer.parseInt(scan.nextLine()); 
    int[] input = new int[total]; 
    for (int i = 0; i < total; i++) { 
     while (true) { 
      try { 
       System.out.print("Enter number "); 
       String in = scan.nextLine(); 
       input[i] = Integer.parseInt(in); 
       break; 
      } catch (RuntimeException re) { 
       System.err.print("Invalid input. "); 
      } 
     } 

    } 
    scan.close(); 
    System.out.println(Arrays.toString(input)); 

它会强制用户输入只有数字,你可以添加边界或者如果需要更改数据类型。

+0

谢谢您的输入!然而,我的程序的目的之一是它为用户提供了有关初始输入错误原因的反馈。我只想弄清楚为什么用户输入错误后需要输入两次。 – Isabelle

+0

检查'input [i]> 0'是否打印不接受输入的原因,而不是输入无效。 ''打印'不是数字' – Saravana

+0

从扫描仪你正在采取'input.next()'和'input.nextInt()'。你可以得到'input.nextInt()'或'input.next() – Saravana