gpt4 book ai didi

Java:在 do while 循环内切换

转载 作者:行者123 更新时间:2023-12-04 07:14:25 24 4
gpt4 key购买 nike

我尝试进行多次随机选取,为每个输入数字打印消息,即数字系列 (4 2 17 0),其中 0 将停止代码。得到错误的输出


public class Main {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number=scanner.nextInt();

int x = number;
do{switch(x) {

case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check the balance");
break;

case 4:
System.out.println("Check loan balance");
break;
case 0:
System.out.println("Exit");
break;

default:
return;

}
if (x==0)
{break;}
x++;
}

while (true);

}
} ```
![enter image description here](/image/RJBYn.jpg)

![enter image description here](/image/wCm4p.jpg)

最佳答案

您可以使用 Scanner#hasNextInt当整数用完时终止循环。
演示:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

while (scanner.hasNextInt()) {
int x = scanner.nextInt();
switch (x) {
case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check the balance");
break;
case 4:
System.out.println("Check loan balance");
break;
case 0:
System.exit(0);
}
}
}
}
示例运行:
4 2 17 0
Check loan balance
Customer support
另外,请注意您需要 break以免案件不慎落案。我没有看到 default 的任何用途在这种情况下,因此,我已将其从演示代码中删除。
或者,使用 do-while 循环:
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x = 0;

do {
x = scanner.nextInt();
switch (x) {
case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check the balance");
break;
case 4:
System.out.println("Check loan balance");
break;
}
} while (x != 0);
}
}

关于Java:在 do while 循环内切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68871616/

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