How do you tie a String variable to a String variable?

Hello so I am attempting to write a code that test the operators and need a little help declaring variables. So in my code under my if statement I declare a certain answer to be true or false depending on what the entered number would be and I keep getting stuck on the "cannot find symbol" error. Here is my code

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);

   }
}

The program tells me that I cannot declare the variable "answer" in that spot. I am trying to tie the string "f" and "t" variables to the answer variable and dont know how. Please help!

Jon Skeet
people
quotationmark

You're not declaring the variable at all. You're just trying to assign to it. You can just add

String answer;

to the code before you start trying to assign to it.

Additionally, you almost never want to call new String(String), and you can simplify your code significantly. You'd be better off determining the result (e.g. just with ||) and then converting the result into a 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";

Looking at that, the result you want actually seems to be as simple as:

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

The only way you can get "False" as an answer in both your original code and my final code is if the number isn't divisible by either 5 or 6.

Your code just expresses that in a really complicated way...

people

See more on this question at Stackoverflow