gpt4 book ai didi

java - 在 while 语句内使用嵌套的 if 和 else if 语句

转载 作者:行者123 更新时间:2023-12-01 22:54:17 24 4
gpt4 key购买 nike

我在让我的程序执行我需要它执行的操作时遇到问题。代码中没有语法错误。

首先,我将程序设置为最多询问用户名字和姓氏 3 次,如果用户愿意,他们应该能够提前结束输入。

有没有办法可以将 System.out.print("Do you Want to add a new name (Y/N)");在 if 语句之外?因此,当我输入第三个名字或输入 2 个名字并输入 N 后,它就会停止。

任何帮助将不胜感激。

import java.util.Scanner;

public class SOF {


public static void main(String test[]){




@SuppressWarnings("resource")
Scanner scanner = new Scanner (System.in);

System.out.print("Do you want to add a new name (Y/N)");
String newname = scanner.next();

int AddName = 0;

while (AddName < 3) {


if (newname.equalsIgnoreCase("y"))
{


System.out.println("Enter first name: ");
String fname = scanner.next();

System.out.println("Enter last name: ");
String lname = scanner.next();

AddName = AddName + 1;

System.out.print("Do you want to add a new name (Y/N)");
String newnamee = scanner.next(); //had to add an extra e, since I had two varibles
// with the same time. This might be the issue.
//I'm unsure though



}

else if (newname.equalsIgnoreCase("n")) {

System.out.println("Goodbye");
AddName = AddName + 3;
}
}
}

}

最佳答案

您可以将 System.out.print("Do you Want to add a new name (Y/N)"); 放在 while 循环的开头,如下所示:

import java.util.Scanner;

public class SOF {
public static void main(String test[]){
@SuppressWarnings("resource")
Scanner scanner = new Scanner (System.in);
int AddName = 0;

while (AddName < 3) {
System.out.print("Do you want to add a new name (Y/N)");
String newname = scanner.next();

if (newname.equalsIgnoreCase("y"))
{
System.out.println("Enter first name: ");
String fname = scanner.next();
System.out.println("Enter last name: ");
String lname = scanner.next();
AddName = AddName + 1;

}

else if (newname.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
AddName = AddName + 3; //alternatively you can use break statement.
}
}
}
}

关于java - 在 while 语句内使用嵌套的 if 和 else if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24323516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com