Java 如何创建是/否?

Java 如何创建是/否?,java,class,if-statement,input,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 s

因此,这段代码允许用户保存在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!");
        }
    }
遵循这个方法。扫描仪工作原理示例(适用于您的问题):


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

您想知道如何提示用户或创建
If
语句吗?请在此处发布代码之前正确设置代码格式。您可以使用这个在线工具来实现这一点:查看Scanner类
newscanner(System.in)类似并且可能有帮助您也可以使用System.console()。再见,非常感谢。你能为这门课评论几句话吗,这样我就能更好地理解了。再次感谢。你说的//你在这里保存了什么意思?我在那里放了什么?我已经为你添加了一些评论。
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);         
            }
        }                       
    }
}