我试图找到重复输出的故障

时间:2015-11-21 03:02:26

标签: java integer

我有一个验证整数输入的小试用版。它工作正常,除非有效但在while循环测试范围之外,输入整数(比如说-20),然后是无效的非整数条目(比如34.5或ksfe),然后是范围内的有效整数(比如25) )。发生的情况是这样的情况是最后一次'输入OK'消息重复2次或更多次,这取决于这些输入的数量,就好像某些东西被刷新到输出消息一样。 这是代码:

// Some glitch makes for this repeating the last
// output OK message if an age age<=0 or age>115 is otherwise validly entered 
// first, followed by a non-numerical entry, then an OK entry such as 44.

import javax.swing.JOptionPane;
import java.text.DecimalFormat; // concrete class of abstract class NumberFormat
import java.io.IOException;

public class Input_Graphic1{
    int times=1;
    String prompt1,prompt2a="Emter your age ";
    String prompt2b="Emter your age silly billy: ",nameStr,ageStr;
    String outMsg1, outMsg2,errmsg=" years old is crap! try again..";
    int age;


    public static void main(String args[]){

        Input_Graphic1 iG=new Input_Graphic1();
        iG.meth1(); 
    }

    public void meth1(){

        if (times==1){
            prompt1="Enter you full name: ";
            nameStr=getInput(prompt1);
            outMsg1="Name entered: " +nameStr;
            JOptionPane.showMessageDialog(null,outMsg1,"Name Entered OK",
                                    JOptionPane.INFORMATION_MESSAGE);
            times++;
        }

        ageStr=getInput(prompt2a);
        age=intInputTest(ageStr,prompt2a); // test for text or decimal input
        System.out.println("age at start/restart: "+age);
        while(age==1){
            System.out.println("in first while.");
            ageStr=getInput(prompt2a);  
            age=intInputTest(ageStr,prompt2a);          
        }
        while(age <= 0 || age > 115){
            JOptionPane.showMessageDialog(null,ageStr+errmsg,"Crap Age Entered",
                                JOptionPane.WARNING_MESSAGE);
            ageStr=getInput(prompt2b);
            age=intInputTest(ageStr,prompt2b); // test for decimal or text input
            System.out.println("age: "+age);
            if(age==1) break;
        }
        if(age==1) {
            System.out.println("age = 1");
            age=2;          
            meth1();
        }
        outMsg2="Age entered: " +ageStr; 
        JOptionPane.showMessageDialog(null,outMsg2,"Age Entered OK",
                                JOptionPane.INFORMATION_MESSAGE);       
    }

    public String getInput(String prompt){
        String var; 
            var=JOptionPane.showInputDialog(prompt);
            while(var.length()==0) var=JOptionPane.showInputDialog(prompt);
            return var;
    }

    public int intInputTest(String ageStr,String prompt2){
        int age=1;

        try{    // catch text or decimal input  
            age=Integer.parseInt(ageStr);
            return age;
        }catch(NumberFormatException e){
            JOptionPane.showMessageDialog(null,"Non-integer input!","Invalid Input",JOptionPane.ERROR_MESSAGE);             
            return age;
        }
    }
}

0 个答案:

没有答案