0

Ok, I'm taking a Comp. Prog. class at my high school and the teacher that "teaches" the class knows practically nothing about programming. I joined the Java UIL team and am teaching the class with curriculum from some college website. Anyways, I started writing a Body Mass Index Calculator yesterday, and have had success but my problem is that I want to have a println prompt to run the program again after the calculations have been completed. Now, I have learned the Do While loop for this occasion, but my problem is with the scanner. I want to receive input as a string but when I do

String a = sc.nextLine(); 

outside of the do, it says that y or yes, cannot be resolved to a variable. A friend suggested switch cases, what do you think? I use Eclipse BTW.

String a = sc.nextLine();
do{
    wow(); //My method name
}while(a == y); //Error is here
Wouter J
  • 41,455
  • 15
  • 107
  • 112

2 Answers2

0

To compare objects in java use .equals() method instead of "==" operator

Use while(a.equals("y")); instead of while(a == y);

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0
while(a == y);

This will never work for two reasons:

  • == compares references, not the contents of the object. So here it is only checking that a and y point to the same object, not that they contain the same thing.
  • You have not declared y anywhere. I'm assuming that you want to compare a against the literal string "y", in which case you should be using a.equals("y").

Your loop can be structured like this:

String input;
do {
    wow();
    input = scanner.nextLine();
} while(input.equalsIgnoreCase("y"));  //using equalsIgnoreCase because user
                                       //can input "y" or "Y".
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295