這是我的作業。但是,我無法得到結果工作。我想把它打印出來:計算器,不能讓它按我想要的打印出來
> 2*7*6
2
* 7
----
14
* 6
----
84
等等。無論輸入多少個數字,我都希望代碼能夠正常工作。這是我迄今的代碼;
public static int add(int a, int b) {
return a + b;
}
public static int sub(int a, int b) {
return a - b;
}
public static int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("(ex. 8*2*6): ");
String amount = in.nextLine();
if (amount.contains("+")) {
String[] parts = amount.split("\\+");
} else if (amount.contains("-")) {
String[] parts = amount.split("\\-");
} else if (amount.contains("*")) {
String[] parts = amount.split("\\*");
int[] results = new int[parts.length];
// Convert from string to integer
for (int i = 0; i < parts.length; i++) {
try {
results[i] = Integer.parseInt(parts[i]);
} catch (NumberFormatException nfe) {};
}
// Print result
int counter = 1;
for (int i = 0; i <= results.length; i++) {
if (i == 0) {
System.out.println(" " + results[i]);
System.out.println("* " + results[counter]);
System.out.println("----");
int total = multiply(results[i], results[counter]);
System.out.println(" " + total);
} else if (i > 1) {
System.out.println("* " + results[i]);
System.out.println("----");
System.out.println(" " + multiply(results[i], results[counter]));
}
}
} else {
System.out.println("Error");
}
我在做什麼錯?
當您顯示代碼時,您應該幾乎總是有一個語言標籤。它不僅可以幫助人們找到問題,還會影響代碼段的語法高亮顯示。 – crashmstr