2014-10-02 38 views
1

我试图让一个程序,允许用户输入5个不同的数字;但不是显示数字,我想向用户显示他已完成了多少错误/无效输入。问题是:我不完全知道如何做到这一点,但迄今为止我已经设法制定了一个计划,但不完全正确。检测无效输入的数量(使用parseInt)

import javax.swing.JOptionPane; 

public class TopicThirteen { 

    public static void main(String[] args) { 
     String msg = ""; 
     int num = 0; 
     int counter; 

     //for loop that gets the 5 numbers from the user 
     for(counter = 0; counter < 5; counter++) { 
      try { 
       num = Integer.parseInt(JOptionPane.showInputDialog(
         "Enter number " + (counter + 1))); 
      } catch(Exception e) { 
       JOptionPane.showMessageDialog(null, "Error " + e); 
      } 
     } 
     //sets msg to the string equivalent of input 
     switch(num) { 
     case 1: 
      msg = "one Invalid Inputs"; 
      break; 
     case 2: 
      msg = "two Invalid Inputs"; 
      break; 
     case 3: 
      msg = "three Invalid Inputs"; 
      break; 
     case 4: 
      msg = "four Invalid Inputs"; 
      break; 
     case 5: 
      msg = "five Invalid Inputs"; 
      break; 
     } 
     // displays the number in words if with in range 
     JOptionPane.showMessageDialog(null, msg); 
    } 
} 
+0

+1阅读http://stackoverflow.com/help/how-to-ask ...提出问题的好方法。 – StackFlowed 2014-10-02 12:43:43

回答

3

您需要一个更多的变量来保持每个错误输入(即在catch块内部)的计数和递增计数器。要在数字分析例外条款更加具体,你应该使用NumberFormatException

int wrongInputCounts = 0 ; 
//for loop that gets the 5 numbers from the user 
for(counter = 0; counter < 5; counter++){ 

    try{ 

     num = Integer.parseInt(JOptionPane.showInputDialog("Enter number "+(counter+1))); 

    }catch(NumberFormatException e){ 
     wrongInputCounts++; 
     JOptionPane.showMessageDialog(null,num + " is not a valid number"); 
    } 
} 

然后wrongInputCounts切换:

switch(wrongInputCounts){ 
+1

Juned他没有做任何与你可能只是删除它。 – StackFlowed 2014-10-02 12:44:44

+1

@wrongAnswer我用showMessageDialog现在;-) – 2014-10-02 12:46:22

+0

干得好;):P ... – StackFlowed 2014-10-02 12:47:45

1

什么有关此版本:

public class TopicThirteen 
{ 
    public static void main(String[] args){ 

     String msg = ""; 
     int num =0; 
     int counter; 

     //for loop that gets the 5 numbers from the user 
     for(counter = 0; counter < 5; counter++){ 

      try{ 

       Integer.parseInt(JOptionPane.showInputDialog("Enter number "+(counter+1))); 

      }catch(Exception e){ 
       num++; 
       JOptionPane.showMessageDialog(null,"Error "+e); 
      } 
     } 

     msg = num + " invalid input(s)"; 
     //displays the number in words if with in range 
     JOptionPane.showMessageDialog(null,msg); 
    } 
} 

至于你说的您不必捕捉用户输入,但用户输入错误。