如何创建是/否?

时间:2015-03-19 00:25:40

标签: java class if-statement input

因此,此代码允许用户保存在main中创建的对象。但是我希望创建一个函数(如果我认为是if语句),它将询问用户是否希望保存它(results.txt)。如果他们那么保存,如果没有则退出程序。

    import java.io.FileOutputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;

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

            Person arthur = new Person();

            arthur.name = "Arthur Dent";
            arthur.age= 21;

            System.out.println("\nDo you wish to save these results? (Y / N)");

            String fileName = "results.txt";
            try {   

                ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName));

                os.writeObject(arthur); //write object
                os.close();

            } catch (IOException e) {
                e.printStackTrace();

            }
            System.out.println("\nYour results are saved!");
        }
    }

1 个答案:

答案 0 :(得分:1)

遵循Scanner方法。扫描仪工作原理的一个示例(应用于您的问题):

public class Test2 {
    static Boolean bool=true;
    public static void main(String[] args){
        System.out.println("Type Y or N:");
        //Initialise the scanner object for the first time
        //Save what the user inputs as s
        Scanner sc = new Scanner(System.in);
        String s=sc.next();
        //Now you enter a while loop
        //You will quit this loop if a condition is met
        //If you want to you can set the bool to false and the while loop will end
        while (bool){
            //if what the user entered is not equal to Y or N
            //then prompt him to try again
            if (!s.equals("Y") && !s.equals("N")){
                System.out.println("Please type only Y or N:");
                sc = new Scanner(System.in);
                s=sc.next();

            }
            //if the user actually entered Y
            if (s.equals("Y")){
                //Do your code logic here
                //In your case that is saving your object
                //Then you can exit the program if that's what you want
                System.exit(1);

            }
            if (s.equals("N")){
                //Add code logic if the user enters N if you need to
                //Exit the program if that's what you want
                System.exit(1);         
            }
        }                       
    }
}

如果您使用上述代码,您很快就可以将其集成到您的问题中。