【问题标题】:How do you tie a String variable to a String variable? [closed]如何将 String 变量绑定到 String 变量? [关闭]
【发布时间】:2014-09-12 01:10:14
【问题描述】:

你好,所以我正在尝试编写一个测试运算符的代码,并且需要一些帮助来声明变量。 因此,在我的 if 语句下的代码中,我根据输入的数字将某个答案声明为真或假,并且我一直陷入“找不到符号”错误。这是我的代码

import java.util.Scanner;

public class TestOperators
{
   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in);

   //prompt the user to enter an integer
      System.out.print("Enter an integer: ");
      int num = input.nextInt();

      String t = new String("True");
      String f = new String("False");

      //calculate
      if ((num % 5 == 0) && (num % 6 == 0))
         answer = t;
      else if ((num % 5 == 0) && (num % 6 != 0) || (num % 5 != 0) && (num % 6 == 0))
         answer = t;
      else if ((num % 5 == 0) || (num % 6 == 0))
         answer = t;
      else
         answer = f;   

   //print results
      System.out.println("Is " + num + " divisible by 5 and 6? " + answer);
      System.out.println("Is " + num + " divisible by 5 or 6?" + answer);
      System.out.print("Is " + num + " divisible by 5 or 6, but not both?" + answer);

   }
}

程序告诉我不能在那个地方声明变量“answer”。我试图将字符串“f”和“t”变量与答案变量联系起来,但不知道如何。请帮忙!

【问题讨论】:

    标签: java string variables if-statement java.util.scanner


    【解决方案1】:

    你根本没有声明这个变量。你只是想分配给它。你可以添加

    String answer;
    

    在您开始尝试分配给代码之前。

    此外,您几乎不想调用new String(String),并且可以显着简化您的代码。您最好确定结果(例如,仅使用||),然后将结果转换为字符串:

    boolean result = ((num % 5 == 0) && (num % 6 == 0)) ||
                     ((num % 5 == 0) && (num % 6 != 0) || (num % 5 != 0) && (num % 6 == 0)) ||
                     ((num % 5 == 0) || (num % 6 == 0));
    String answer = result ? "True" : "False";
    

    这样看,你想要的结果其实似乎很简单:

    String answer = (num % 5 == 0 || num % 6 == 0) ? "True" : "False";
    

    您在原始代码和我的最终代码中都可以得到“False”作为答案的唯一方法是该数字不能被 5 或 6 整除。

    您的代码只是以一种非常复杂的方式表达了这一点......

    【讨论】:

    • 天才解决方案!但我认为这对初学者来说有点复杂
    • @TheQuickBrownFox:看看最终结果 - 我会说这比问题中的原始代码简单得多,不是吗?
    • 是的,正确!我的意思是 complicated 部分是让 OP 提供这个解决方案:D
    【解决方案2】:

    您从未声明过answer。尝试在方法的开头添加这一行:

    String answer;
    

    【讨论】:

    • 如果它被初始化为“False”(因为它需要被初始化),那么你不需要最后一个else
    猜你喜欢
    • 1970-01-01
    • 2013-02-10
    • 2016-01-02
    • 2013-08-13
    • 2021-08-27
    • 2014-01-16
    • 2021-09-16
    • 2012-11-14
    • 2013-07-03
    相关资源
    最近更新 更多