gpt4 book ai didi

java - 如何让我的程序在收到指示之前不关闭[距离转换]

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

我似乎不知道在 while 循环中输入什么或输入什么内容。一切正常,但是当我输入转换后,如何让它询问我是否要输入另一个问题。

import java.util.Scanner; 

public class DistanceConversion
{
public static void showKilometers(double meters)
{
double kilometers = meters * 0.001;
System.out.println(meters +" meters is " + kilometers + " kilometers.");
}

public static void showInches(double meters)
{
double inches = meters * 39.37;
System.out.println(meters +" meters is " + inches + " inches.");
}

public static void showFeet(double meters)
{
double feet = meters * 3.281;
System.out.println(meters +" meters is " + feet + " feet.");
}

public static void quitProgram()
{
System.out.println("Goodbye!");
System.out.println(0);
}
public static void showMenu()
{
System.out.println(" 1. Convert to kilometers ");
System.out.println(" 2. Convert to inches ");
System.out.println(" 3. Convert to feet ");
System.out.println(" 4. Quit the program ");
System.out.println(" ");
}

public static void main (String [] args)
{
double meters;
int choice;
Scanner scan = new Scanner (System.in);

System.out.print("Enter a distance in meters: ");
meters = scan.nextDouble();
showMenu();
choice = scan.nextInt();

switch(choice)
{
case 1:showKilometers(meters);
break;
case 2:showInches(meters);
break;
case 3:showFeet(meters);
break;
case 4:quitProgram();
}
}
}

最佳答案

你想重复什么?整个计划?然后附上“整个程序”又名。主逻辑带有 while 循环,检查输入是否等于 4 或其他任意退出 int。

在顶部声明“int choice”,然后将其余部分括起来。

while(choice >= 1 && choice <=3)
{
//main-method code here
}

编辑(为了清晰起见):

int choice = 0; 
while(choice != 4)
{
double meters;
Scanner scan = new Scanner (System.in);

System.out.print("Enter a distance in meters: ");
meters = scan.nextDouble();
showMenu();
choice = scan.nextInt();

switch(choice)
{
case 1:showKilometers(meters);
break;
case 2:showInches(meters);
break;
case 3:showFeet(meters);
break;
case 4:quitProgram();
}
}

关于java - 如何让我的程序在收到指示之前不关闭[距离转换],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21294372/

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