我是Java新手,我想创建一个简单的程序,允许用户在3个选项(t、r和q)之间进行选择。Q的意思是退出。我希望程序继续提示他们选择不同的选项,直到他们选择退出。下面是我的代码,它不能工作。我得到的错误是q,r和t需要被解析为一个变量,但当我将它们设置为字符串时,它仍然不起作用。任何帮助都将不胜感激。
Scanner input3= new Scanner(System.in);
String choice;
boolean valid;
do
{
System.out.println("Please pick an option. t, r or q");
choice= input3.next();
if(choice==t)
{
System.out.println("You chose triangle");
valid=true;
}
else if(choice==r)
{
System.out.println("You chose rectangle");
valid=true;
}
else if (choice==q)
{
System.out.println("You chose to quit.");
valid=false;
}
else
{
System.out.println("You chose wrong.");
valid=true;
}
}
while( valid==true);发布于 2016-02-10 01:25:27
你应该把它们放在引号"两边,因为choice是字符串,你必须将它与字符串进行比较,例如:
do {
System.out.println("Please pick an option. t, r or q");
choice= input3.next();
if(choice=="t"){
System.out.println("You chose triangle");
valid=true;
}
else if(choice=="r"){
System.out.println("You chose rectangle");
valid=true;
}
else if (choice=="q"){
System.out.println("You chose to quit.");
valid=false;
}
else{
System.out.println("You chose wrong.");
valid=true;
}
}
while( valid==true);您可以使用而不是==来比较两个字符串:
do {
System.out.println("Please pick an option. t, r or q");
choice= input3.next();
if(choice.equals("t")){
System.out.println("You chose triangle");
valid=true;
}
else if(choice.equals("r")){
System.out.println("You chose rectangle");
valid=true;
}
else if (choice.equals("q")){
System.out.println("You chose to quit.");
valid=false;
}
else{
System.out.println("You chose wrong.");
valid=true;
}
}
while( valid==true);希望这能有所帮助。
发布于 2016-02-10 01:26:19
在网络上查看初学者教程(这个问题是:Java String.equals versus ==)
t、r和q需要先设置为字符串变量。
例如:
String choice;
String t = "t";
String r = "r";
String q = "q";您还应该使用equals方法来实现字符串相等。
例如:
choice.equals(t);发布于 2016-02-10 01:34:17
import java.util.Scanner;
public class TestClass {
public static void main(String args[] ) throws Exception {
Scanner input3= new Scanner(System.in);
String choice;
boolean valid;
do {
System.out.println("Please pick an option. t, r or q");
choice= input3.next();
if(choice.equals("t")){
System.out.println("You chose triangle");
valid=true;
}
else if(choice.equals("r")){
System.out.println("You chose rectangle");
valid=true;
}
else if (choice.equals("q")){
System.out.println("You chose to quit.");
valid=false;
}
else{
System.out.println("You chose wrong.");
valid=true;
}
}
while( valid==true);
}
}尽情享受!
https://stackoverflow.com/questions/35298265
复制相似问题