我是java的新手,我无法理解为什么我的代码不起作用。我认为语法有问题,但我不确定它是什么。下面是我的代码的一个非常简短的手。
另外,如果用户的答案都不符合我的预测值,我该如何得到一般回复?
public class {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Hello! My name is Computer. What's your name?");
String name;
name = sc.next();
System.out.println("Hi," + name + "nice to meet you! What is your favorite color?");
String color;
color = sc.next();
if (color.equalsIgnoreCase('blue')) {System.out.println("That's my favorite color too!");
}
} // main method
答案 0 :(得分:3)
String#equalsIgnoreCase
需要String
。单引号表示一个字符,该字符应为单个字符长。话虽如此,这... ...
color.equalsIgnoreCase('blue')
无效。它应该更像......
color.equalsIgnoreCase("blue")
如果我被挑剔......
"blue".equalsIgnoreCase(color)
但是现在这可能有点过分了......
当你试着问下一个问题时......
}
return 0;
}
System.out.println ("What's your favorite sport?");
您已开始在main
方法的上下文之外添加内容。通常,代码应包含在方法和静态块中。在}
和System.out.println ("What's your favorite sport?");
声明
return 0;
基本上,这会重复第三和第四个问题。
这可能意味着您还需要在文件末尾添加}
...
答案 1 :(得分:0)
你的代码中间有一个return语句
else if (color.equalsIgnoreCase('yellow')) {
System.out.println("That's my favorite color too! Like the warm, shining sun!");
}return 0;
}
删除return 0
部分和}
。你有一半的程序在main()
块之外
另外,在单引号'blue'
之间更改所有字符串。您应该将所有这些更改为双引号"blue"
修改强>
即使你编辑了代码,你仍然没有对齐所有花括号。
更改:
return 0; // YOU DONT NEED THIS PART
} // YOU MAIN ENDS HERE
System.out.println("Well," + name + "I have to run. You sound like a great person. We'd get along very well! Take care.");
sc.close();
} // main method
要:
System.out.println("Well," + name + "I have to run. You sound like a great person. We'd get along very well! Take care.");
sc.close();
} // YOU MAIN ENDS HERE