gpt4 book ai didi

java - 我将如何创建输入命令来执行代码的不同部分? - java

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

我创建了一个基本的java程序来确定三角形的斜边。最初,程序会要求 A 边,然后是 B 边,并自动计算斜边。

我想创建一个输入命令列表,允许用户在给出 A 侧值时键入“a”,在给出 B 侧值时键入“b”,然后键入“c”来计算斜边,或“q”退出程序。

我希望他们能够随意放入任意一侧,而不是强制用户先放入 A 面。但是,如果用户键入“c”并且 A 或 B 值缺失(或两者都缺失),我想要一条错误消息并让用户更正它。

到目前为止我已经

import java.util.InputMismatchException;
import java.util.Scanner;


public class handleExceptions1 {
public static void main(String[] args) {

Scanner initial = new Scanner(System.in);
System.out.println(" Type 'a' to enter the value for side A.\n Type 'b' to enter the value for side B.\n Type 'c' to calculate the hypotenuse.\n Or type 'q' to exit");
String inputselected = initial.next();

boolean repeat = true;
double _sideA = 0;
while (repeat) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Please enter side A, this may not be 0: ");
_sideA = input.nextDouble();
if (_sideA > 0){
repeat = false;
}
} catch (InputMismatchException e) {
System.out.print("Error! Please enter a valid number!");
}
}
boolean repeat2= true;
double _sideB = 0;
while (repeat2){
try {
Scanner input = new Scanner(System.in);
System.out.print("Please enter side B, this may not be 0: ");
_sideB = input.nextDouble();
if (_sideB > 0){
repeat2= false;
}
} catch (InputMismatchException e) {
System.out.print("Error! Please enter a valid number!");
}
}
double hypotenuse = Math.sqrt((_sideA*_sideA) + (_sideB*_sideB));
System.out.print("Side C(the hypotenuse) is: "+ hypotenuse);

}



}

我的逻辑是在“String inputselected = ...”之后放置一些内容,但我不确定是什么。如果有人可以帮助我,我将不胜感激!

最佳答案

sideA = -1;
sideB = -1;
Scanner input = new Scanner(System.in);
do
{
System.out.println("Enter your choice ( a/b/c/q ) : ");
char ch = in.nextChar();
switch(ch)
{
case 'a': sideA = in.nextDouble();
if(sideA<0)
System.out.println("Error! Please enter a valid number!");
break;
case 'b': sideB = in.nextDouble();
if(sideB<0)
System.out.println("Error! Please enter a valid number!");
break;
case 'c': if(sideA<0 || sideB<0)
System.out.println("Other two sides not yet given! please provide a and b first. ");
else
System.out.print("Side C(the hypotenuse) is: "+ Math.sqrt((_sideA*_sideA) + (_sideB*_sideB)););

break;
case 'q': break;
default : System.out.println(" Enter a valid choice! ");
}
}while(ch!='q');

关于java - 我将如何创建输入命令来执行代码的不同部分? - java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38106443/

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