以及我試圖創建一個Java計算器,但每當我嘗試輸入一個數字時,它會請求兩次,不僅如此,但我爲第一個數字輸入的數字不起作用,只會給我一個0+被輸入到2號)任何人都在意幫助我嗎?並解釋我需要做什麼來解決這個問題?爲什麼我必須輸入兩次數字?爲什麼第一個數字只給0?
package Calc1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Calc1 {
public static void main(String[] args) throws IOException {
// TODO code application logic here
Boolean test = true;
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
int a = 0;
int b = 0;
String sum;
System.out.println("Please enter the first number you wish to calculate.");
if(in.hasNextInt()) {
b = in.nextInt();
}
while (!in.hasNextInt()) {
System.out.println("Invalid number. Please enter digits only.");
in.next();//Go to next
}
//stops infinite loop by requesting Scanner try again
System.out.println("Please enter the second number you wish to calculate.");
if(in2.hasNextInt()) {
b = in2.nextInt();
}
while (!in2.hasNextInt()) {
System.out.println("Invalid number. Please enter digits only.");
in2.next();//Go to next
}
//stops infinite loop by requesting Scanner try again
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("please enter one of the following operators + -/*");
sum = br2.readLine();
if ("+".equals(sum))
{
int c = a + b;
System.out.println(a + "+" + b + "=" + c);
}
if ("-".equals(sum))
{
int c = a - b;
System.out.println(a + "-" + b + "=" + c);
}
if ("/".equals(sum))
{
int c = a/b;
System.out.println(a + "/" + b + "=" + c);
}
if("*".equals(sum))
{
int c = a * b;
System.out.println(a + "*" + b + "=" + c);
}
}
}
我的問題是怎麼這樣,我做錯了什麼?和你我怎麼解決它,這樣我只需要輸入每個數字一次(和兩個工作而不是給0)
不要創建兩個掃描儀,使用相同的所有操作 – SJuan76
我用了兩個,因爲我在java的新認爲我需要兩個,現在我知道,否則,感謝您的幫助。 – Doomking517