Sup Guys,
需要帮助,令人困惑。我有一些使用某些方法制作的计算器。我想知道我所做的是一种很好的写作方式,还是有其他更好的方法来做到这一点。第二个问题是如果你看到SWITCH CASE 5,如果提示用户输入Y / N,用户可以输入不仅仅坚持Y和N的各种字符....我怎样才能限制用户只使用Y和N.
****THIS IS MY MAINCALC JAVA FILE******
package calculator;
import java.util.Scanner;
public class MainCalc {
public static void main (String args []) {
Scanner scan = new Scanner(System.in);
Calcmethod calc = new Calcmethod();
char choice;
do {
System.out.println("<*-*-*-*-*-*>");
System.out.println("1. Add ");
System.out.println("2. Sub ");
System.out.println("3. Mul ");
System.out.println("4. Div ");
System.out.println("5. Exit");
System.out.println("<*-*-*-*-*-*>\n");
choice = scan.next().charAt(0);
switch (choice){
case '1': System.out.println("The CalcVal is: " + "" + calc.calcAdd());
break;
case '2': System.out.println("The CalcVal is: " + "" + calc.calcSub());
break;
case '3': System.out.println("The CalcVal is: " + "" + calc.calcMul());
break;
case '4': System.out.println("The CalcVal is: " + "" + calc.calcDiv());
break;
case '5': System.out.println("Are You Sure y/n??");
choice = scan.next().charAt(0);
if (choice !='n') {
System.out.println("Thanks for using Calc!!!");
System.exit(0);
}
break;
default: System.out.println("Wrong Choice of Selection - Please Select between 1-5 only");
break;
}//switch
}while (choice != '5');
scan.close();
}
}
****THIS IS MY CALCMETHOD JAVA FILE******
package calculator;
import java.util.Scanner;
public class Calcmethod {
Scanner scan = new Scanner(System.in);
public double calcAdd(){
System.out.println("Enter 1st Val: ");
double x = scan.nextDouble();
System.out.println("Enter 2nd Val: ");
double y = scan.nextDouble();
double res = (x+y);
return res;
}
public double calcSub(){
System.out.println("Enter 1st Val: ");
double x = scan.nextDouble();
System.out.println("Enter 2nd Val: ");
double y = scan.nextDouble();
double res = (x-y);
return res;
}
public double calcMul(){
System.out.println("Enter 1st Val: ");
double x = scan.nextDouble();
System.out.println("Enter 2nd Val: ");
double y = scan.nextDouble();
double res = (x*y);
return res;
}
public double calcDiv(){
System.out.println("Enter 1st Val: ");
double x = scan.nextDouble();
System.out.println("Enter 2nd Val: ");
double y = scan.nextDouble();
double res = (x/y);
return res;
}
答案 0 :(得分:-1)
您无法限制用户输入。您只能使用buffer[0]
预测并让您的程序为可能导致错误的任何输入做好准备。