我创建了一个基本的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/