我正在尝试为明信片制作一个类和一个单独的打印机类。想法是制作一张明信片,可以接受用户对发件人,收件人和场合的输入。然后添加一些内容,使我们可以将同一张明信片发送给另一个朋友。这是我的明信片课

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循环中出现,表示不存在变量variable,注释掉后,什么也没有发生。虚拟机正在运行,但没有任何反应。任何帮助将不胜感激

最佳答案

该行:

while (choice != no)


正在寻找名为no的变量,而不是字符串常量。你要:

while (!choice.equals("no"))


或者,区分大小写的方法:

while (!choice.equalsIgnoreCase("no"))


需要指出的一件事-由于choice的值在循环内永远不会改变,因此您基本上将永远循环。您可能需要在每次循环迭代后再次询问。您可能只是将选择的初始值设置为空字符串,然后在程序开始时立即启动循环。这将允许您删除循环上方的冗余代码。

10-06 05:57