我对java编程语言很陌生。我一直在用while s练习String循环语句,似乎无法正确理解这段代码。我一直在犯错误:
变量选择可能还没有初始化。
import java.util.Scanner;
public class Test {
public static void main(String args []) {
Scanner sc=new Scanner(System.in);
int a, b,c, diff, prod, q, choice;
String name;
String choose;
System.out.print("Enter Name Please: \t");
name = sc.next();
System.out.println("WELCOME " + name);
System.out.println("");
while (choose == "Y");
{
System.out.println("1. Addition \t2. Subtraction \t3. Multiplication \t4. Division");
System.out.println("Please Choose a number: \t");
choice = sc.nextInt();
switch (choice)
{
case 1:
System.out.println("Thank You "+name+", you have chosen ADDITION");
System.out.print("\nPlease Enter the first number: \t");
a = sc.nextInt();
System.out.print("\nPlease Enter the Second number: \t");
b = sc.nextInt();
c = a + b;
System.out.println("\nYou have chosen "+a+ " as your first number, we will add it to "+b+" your second number.");
System.out.println("\nThe answer is "+c);
System.out.println("\nWould you like to choose again? Y/N: \t");
choose = sc.next();
break;发布于 2013-10-14 02:45:18
在将变量choose设置为初始值之前使用它。在choose循环中使用它之前,您从未分配过它的任何值。
在while循环之前添加此语句:
choose = sc.next();当然,您需要为最终用户提供一条合适的消息。
另外,您的比较是错误的-使用choose.equals("Y")或choose.equalsIgnoreCase("Y"),因为您==。
编辑:回顾您的代码,您的while循环无论如何都会失败。将分号从它的末尾移除。这样,当您期望它进入循环时,它就会进入循环。
发布于 2013-10-14 02:46:19
这是一个内置在编译器中的安全网,它抱怨说,在while语句中使用字符串safety之前,可能还没有声明它。把它声明为"“,你就可以走了。
String choose = "";希望这能有所帮助!欢迎来到爪哇!
发布于 2013-10-14 02:46:50
您没有为变量choose分配任何值。
https://stackoverflow.com/questions/19352741
复制相似问题