sefor
sefor

Reputation: 61

Java program looping help! I need to restart the program via a y/n input

Okay so I made a program but I need to be able to restart the program by asking if the user wants to try again y/n? But I can't seem to loop it correctly. Help me! P.S sorry for formatting.

import java.util.*;
import java.util.Scanner;

class Tester
{...

    ...}
System.out.println("y/n?");
String playagain = in.nextLine();
if (playagain == "y")
play = true;
else
play = false;
}

}
}

Upvotes: 1

Views: 278

Answers (2)

Phiwa
Phiwa

Reputation: 319

Scanner in = new Scanner(System.in);
String s;
while (!(s = in.nextLine()).equalsIgnoreCase("q")) {       
    // do stuff
    System.out.println("---");      
}

Added a way to quit the game by typing "q", every other input restarts the game with the new word, but you could switch that to y/n as well. You can put all the rest of your logic inside the while loop or even call a method doing the logic inside it.

Upvotes: 0

duffymo
duffymo

Reputation: 308763

Try this:

if ("y".equalsIgnoreCase(playagain))

Don't use == to compare Strings. All that does is compare reference values. You want equals(): it compares String contents.

Upvotes: 5

Related Questions