我正在尝试为明信片制作一个类和一个单独的打印机类。我们的想法是制作一张明信片,可以为发件人,收件人和场合提供用户输入。然后添加一些允许我们将同一张明信片发送给另一位朋友的东西。这是我的明信片类
public class Postcard
{
private String message;
//define other variables that you need in this class
private String sender;
private String recipiant;
private String occasion;
private String print;
// Methods go here
public Postcard()
{
String message = "Happy holidays too ";
String sender = "Michael";
String recipiant = "";
String occasion = "";
}
public void setmessage(String m)
{
this.message = m;
}
public void setSender(String s)
{
this.sender = s;
}
public void setRecipiant(String r)
{
this.recipiant = r;
}
public void setOccasion(String o)
{
this.occasion = o;
}
public String print()
{
print = message + sender + recipiant + occasion;
return print;
}
}
这是明信片印刷类
import java.util.Scanner;
public class PostcardPrinter
{
public static void main(String[] args)
{
String text = "Happy Holiday to ";//write your msg here
Postcard myPostcard = new Postcard(); // use the constructor method
//use the mutator method to set the name of the recipient
Scanner op = new Scanner(System.in);
String recipant = op.nextLine();
String sender = op.nextLine();
String occassion = op.nextLine();
myPostcard.print();
//write the code to send the same msg to another friend
System.out.println("Do you want to send another? Type 'yes' or 'no' ");
String choice = op.nextLine();
while (choice != no)
{
String text = "Happy Holiday to ";
Postcard myPostcard = new Postcard();
Scanner op = new Scanner(System.in);
String recipant = op.nextLine();
String sender = op.nextLine();
String occassion = op.nextLine();
}
}
}
错误出现在while循环中,表示varriable no不存在,当注释掉时,没有任何反应。虚拟机正在运行,但没有任何反应。任何帮助将不胜感激
答案 0 :(得分:3)
该行:
while (choice != no)
正在寻找名为no
的变量,而不是字符串常量。你想要:
while (!choice.equals("no"))
或者,不区分大小写的方法:
while (!choice.equalsIgnoreCase("no"))
有一点需要指出 - 因为choice
的值在循环内部永远不会改变,所以你基本上会永远循环。在循环的每次迭代之后,您可能希望再次询问。您可以将 choice 的初始值设置为空字符串,然后在程序开始时立即启动循环。这将允许您删除循环上方的冗余代码。