java - 我很难让我的循环工作
问题描述
我很难让循环工作。如果用户在开始时键入“退出”或“退出”,则循环应该有一个输出,但如果没有输入退出,则继续处理。
但是,我尝试了一个 do 循环,因为一旦它不适用于给定的参数,它将运行循环。我也根本无法使用 if/else 语句。我正在使用 Eclipse 按照教授的指示进行编码/编译。
这是我目前的片段:
public static void main(String[] args) {
Scanner scan= new Scanner (System.in);
String fullName;
int total= 0;
System.out.print("Please enter your full name: ");
fullName= scan.nextLine(); //Scans user input for name
int count= fullName.length()-1;//Evaluates the length of the user's name
while (fullName.equalsIgnoreCase("Quit || quit"))
{
System.out.println("Thank you for using the system. Come back soon.");
}
{
System.out.println("Please enter "+count+" numbers and the total will be calculated\n");
for (int i=0; i<count; i++) {
int userEnteredNum= scan.nextInt();
total += userEnteredNum;
}
System.out.println("Good day, "+ fullName+ "! You have entered "+
count+ " numbers.\nThe total of all the numbers is "+ total);
}
while (fullName.equalsIgnoreCase("Quit || quit"));
}
}
如果用户键入退出,它应该显示一条感谢消息而不是继续。如果用户没有键入quit,程序应该继续并要求用户根据姓名的字符长度输入数字,并将它们相加,然后重复直到用户键入quit。
使用我拥有的当前版本,会发生以下情况:
“请输入您的全名:退出请输入3个数字,然后计算总数”
或“请输入您的全名:Jane Lane 请输入8个数字,将计算总数
1 2 3 4 5 6 7 8 美好的一天,简·莱恩!您输入了 8 个数字。所有数字的总和是 36"
解决方案
public static void main(String[] args) {
while (true) {
Scanner scan = new Scanner(System.in);
String fullName;
int total = 0;
System.out.print("Please enter your full name: ");
fullName = scan.nextLine(); //Scans user input for name
int count = fullName.length() - 1;//Evaluates the length of the user's name
if (fullName.equalsIgnoreCase("Quit")) {
System.out.println("Thank you for using the system. Come back soon.");
return;
}
System.out.println("Please enter " + count + " numbers and the total will be calculated\n");
for (int i = 0; i < count; i++) {
int userEnteredNum = scan.nextInt();
total += userEnteredNum;
}
System.out.println("Good day, " + fullName + "! You have entered " +
count + " numbers.\nThe total of all the numbers is " + total);
}
}
推荐阅读
- c# - 如何在asp.net mvc 3.1 c#中按Id获取列行
- unity3d - 如何使用代码引用弓的“电枢动作”?
- list - 尝试打印类的对象时出现名称错误
- javascript - 如果我将网站置于在线(主机)但如果它是本地的一切顺利,为什么图像没有保存?
- django - pytest-django:使用 create_user 创建的用户始终经过身份验证
- javascript - 将文本置于图像顶部居中
- python - 为什么删除分配给另一个变量的变量不会影响新变量?
- flutter - Flutter - 如何创建来电通知?
- java - 找到离给定点最近的折线
- php - cURL 不发送 postfields