[英]How to make a single input satisfy 2 scanners at the same time
所以我正在制作一個計算器應用程序,我被困在這個應用程序中,我想知道是否有辦法讓用戶同時為兩個掃描儀進行單一輸入。 因為我打算創建一個Double ( scanner.nextDouble() )變量,同時還要檢查它是否包含一個數字( scanner.hasNextDouble() )是真還是假。
順便說一句,我是初學者,所以如果我的問題難以理解,我很抱歉。
import java.util.Scanner;
public class Actions {
static Scanner scanner = new Scanner(System.in);
private final double x;
private final double y;
private final int operation;
Actions() {
this.x = getDoubleX();
this.y = getDoubleY();
this.operation = getOperation();
showAnswer();
}
public static double getDoubleX() {
double temp = 0;
String temp1;
boolean temp2 = true;
System.out.println("input your first number: ");
while (temp2) {
/*
I tried a solution like this. but it didn't work out.
*/
temp1 = scanner.nextLine();
temp = Double.parseDouble(temp1);
if (Double.isNaN(temp)) {
System.out.println("try again! ");
} else {
temp2 = false;
}
}
return temp;
}
public static double getDoubleY() {
double temp = 0;
boolean temp1 = true;
boolean temp2 = false; //I'm talking about this
System.out.println("input your second number: ");
while (temp1) {
temp = scanner.nextDouble();
if (!Double.isNaN(temp)){
temp1=false;
} else {
System.out.println("try again!");
}
}
return temp;
}
public static int getOperation() {
int temp = 0;
boolean temp1 = true;
System.out.println("input your desired operation, \n" +
"1 = addition, 2 = subtraction, 3 = multiplication, 4 = division");
while (temp1) {
temp = scanner.nextInt();
if (temp >= 1 && temp <= 4) {
temp1 = false;
} else {
System.out.println("try again");
}
}
return temp;
}
public void showAnswer() {
if (x % 1 == 0 & y % 1 == 0) {
if (operation == 1) {
System.out.println("the sum is: " + Math.round(x + y));
} else if (operation == 2) {
System.out.println("the difference is: " + Math.round(x - y));
} else if (operation == 3) {
System.out.println("the product is: " + Math.round(x * y));
} else {
System.out.println("the quotient is: " + Math.round(x / y));
}
} else {
if (operation == 1) {
System.out.println("the sum is: " + (x + y));
} else if (operation == 2) {
System.out.println("the difference is: " + (x - y));
} else if (operation == 3) {
System.out.println("the product is: " + (x * y));
} else {
System.out.println("the quotient is: " + (x / y));
}
}
}
}
不要使用兩個掃描儀。 這是沒有必要的。 嘗試以下操作(您可能需要針對您的特定應用進行調整)。
Scanner scan = new Scanner(System.in);
double d = 0;
while (true) {
System.out.print("Enter a double value: ");
String possibleDouble = scan.next();
try {
d = Double.parseDouble(possibleDouble);
break;
} catch (NumberFormatException ne) {
System.out.printf("bad input (%s) - try again!%n",
possibleDouble);
}
}
System.out.println(d);
您可以將上述內容放在具有特定參數的方法中以驗證輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.