gpt4 book ai didi

java - 变量 'menu' 可能尚未初始化

转载 作者:行者123 更新时间:2023-12-02 04:22:04 24 4
gpt4 key购买 nike

我尝试制作一个使用 switchdo while 的菜单,但它返回:

variable 'menu' might not have been initialized

} while (menu != 5);

有人可以帮我吗?这是我的目标:

pic

import java.util.Scanner;
class HW {
public static void main(String[] args) {
Scanner entry = new Scanner(System.in);
int A, B, X, menu; // there
do {
System.out.println("Main Menu");
System.out.println("1. Plus");
System.out.println("2. Minus");
System.out.println("3. Multiply");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Option :");
X = entry.nextInt();
switch (X) {
case 1:
System.out.println("Var A : ");
A = entry.nextInt();
System.out.println("Var B : ");
B = entry.nextInt();
System.out.println("Result : " + (A + B));
if (A > B)
System.out.println(A + ">" + B);
else if (A == B)
System.out.println(A + "=" + B);
else if (A < B)
System.out.println(A + "<" + B);
System.out.println("*press any key back to menu*");
menu = entry.nextInt(); // there
break;
case 2:
System.out.println("Var A : ");
A = entry.nextInt();
System.out.println("Var B : ");
B = entry.nextInt();
System.out.println("Result : " + (A - B));
if (A > B)
System.out.println(A + ">" + B);
else if (A == B)
System.out.println(A + "=" + B);
else if (A < B)
System.out.println(A + "<" + B);
System.out.println("*press any key back to menu*");
menu = entry.nextInt(); //there
break;
case 3:
System.out.println("Var A : ");
A = entry.nextInt();
System.out.println("Var B : ");
B = entry.nextInt();
System.out.println("Result : " + (A * B));
if (A > B)
System.out.println(A + ">" + B);
else if (A == B)
System.out.println(A + "=" + B);
else if (A < B)
System.out.println(A + "<" + B);
System.out.println("*press any key back to menu*");
menu = entry.nextInt(); //there
break;
case 4:
System.out.println("Var A : ");
A = entry.nextInt();
System.out.println("Var B : ");
B = entry.nextInt();
System.out.println("Result : " + (A / B));
if (A > B)
System.out.println(A + ">" + B);
else if (A == B)
System.out.println(A + "=" + B);
else if (A < B)
System.out.println(A + "<" + B);
System.out.println("*press any key back to menu*");
menu = entry.nextInt(); //there
break;
case 5:
break;
}
} while (menu != 5); //here it say not initialized.
System.out.println(" ");
}
}

最佳答案

您需要在最后一个case之后创建一个default语句。这是因为,如果没有一个情况属实,它仍然需要一个“后备计划”。它是 else 语句的对应部分。

case: 5 之后添加此内容:

default:
menu = desiredNumberHere;
break;

关于java - 变量 'menu' 可能尚未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32663633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com