我是Java编码新手,正在通过制作计算器进行练习。我想要这样当我打字时 重新启动它执行操作选择部分。
import java.util.Objects;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean MO=true;
while(MO==true)
MO=false;
System.out.println("Please enter your operation");
System.out.println("1 - Addition");
System.out.println("2 - Subtraction");
System.out.println("3 - Multiplication");
System.out.println("4 - Division");
Scanner scanner = new Scanner(System.in);
int op = scanner.nextInt();
System.out.println(op);
scanner.reset();
// Addition
if(op == 1) {
System.out.println("Enter a starting value!");
int as = scanner.nextInt();
scanner.reset();
boolean ab = true;
while(ab) {
ab=false;
System.out.println("Please enter a number to add or type 'End' to end or 'Clear' to reset or 'Restart' to exit the mode");
String an = scanner.next();
if(Objects.equals(an, "End")) {
System.out.println("Quitting"); }
else if(Objects.equals(an,"Clear")) {
int ae = 0;
System.out.println("Cache clear!");
ab = true;} else if(Objects.equals(an,"Restart")) {
System.out.println("Restarting!");
MO=true;
break;
}else {
int ra = Integer.parseInt(an);
int ae = as+ra;
System.out.println(ae);
as = ae;
}}
}}
使用了一段时间(可能是错误的),期望成功,但失败了;(
您忘记了 while 循环的大括号
while(MO)
!这意味着它只会执行语句 while(MO==true) MO=false
之后的第一行。这是固定代码。
import java.util.Objects;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean MO=true;
while(MO==true) {
MO=false;
System.out.println("Please enter your operation");
System.out.println("1 - Addition");
System.out.println("2 - Subtraction");
System.out.println("3 - Multiplication");
System.out.println("4 - Division");
Scanner scanner = new Scanner(System.in);
int op = scanner.nextInt();
System.out.println(op);
scanner.reset();
// Addition
if(op == 1) {
System.out.println("Enter a starting value!");
int as = scanner.nextInt();
scanner.reset();
boolean ab = true;
while(ab) {
ab=false;
System.out.println("Please enter a number to add or type 'End' to end or 'Clear' to reset or 'Restart' to exit the mode");
String an = scanner.next();
if(Objects.equals(an, "End")) {
System.out.println("Quitting"); }
else if(Objects.equals(an,"Clear")) {
int ae = 0;
System.out.println("Cache clear!");
ab = true;} else if(Objects.equals(an,"Restart")) {
System.out.println("Restarting!");
MO=true;
break;
}else {
int ra = Integer.parseInt(an);
int ae = as+ra;
System.out.println(ae);
as = ae;
}}
}}
}
}