gpt4 book ai didi

java - do...while 循环出现问题

转载 作者:行者123 更新时间:2023-12-01 19:12:35 25 4
gpt4 key购买 nike

我对这个do while循环有一点问题;当我运行该程序时,它正在工作,至少部分地工作,我的意思是首先您需要选择从 C 到 F 或从 F 到 C 的转换,在输入值后,程序停止我想要做的事情是继续询问值,直到输入 3。我尝试使用 do while 循环来完成此操作,但它不起作用,因此如果有人有任何想法,我将不胜感激。这是代码:

import java.util.Scanner;

public class DegreesInConversion2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Conversion table: ");
int choice = input.nextInt();
do {
System.out.println();
System.out.println("1 for convertion from Celsious to Fahrenhait: ");
System.out.println("2 for convertion froom Fahrenheit to Celsious: ");
System.out.println("3 for Exit: ");
System.out.println();
System.out.println("Make a choice between 1 - 3 ");
choice = input.nextInt();
System.out.println();
switch (choice) {
case 1:
System.out.println("Enter temperature in Celsious: ");
double cel = input.nextDouble();
if (cel < -273.15) {
System.out.println("Invalid values, please enter temperature greater than -273.15 in C:");
} else {
System.out.println("You enetered " + cel + "C " + "which is " + (((cel * 9) / 5) + 32) + "F");
}
break;
case 2:
System.out.println("Enter temperature in Farhneit: ");
double far = input.nextDouble();
if (far < -459.67) {
System.out.println("Invalid values, please enter temperature greater than -459.67 in F:");
} else {
System.out.println("You enetered " + far + "F " + "which is " + (((far - 32) * 5) / 9) + "C");
}
break;
case 3:
System.out.println("Goodbyu have a nice day: ");
break;
default:
System.out.println("Invalid entry: Please enter a number between 1-3:");
}
} while (choice != 3);
}
}

最佳答案

your other question 所示,您将在提示用户输入之前扫描输入。

您需要删除下面的第二行:

    System.out.println("Conversion table: ");
int choice = input.nextInt();
do

按原样使用您的代码,它会输出

Conversion table:

然后阻塞等待输入。而您希望它继续进入 while 循环并输出

1 for convertion from Celsious to Fahrenhait:
2 for convertion froom Fahrenheit to Celsious:
3 for Exit:

Make a choice between 1 - 3

在阻止扫描输入之前。

事实上,如果您在第一个 block 中输入任何数字,您的程序就会进入循环并按照您想要的方式运行。所以你就快到了!

关于java - do...while 循环出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7928875/

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