This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have following do while code, where I am trying to end the loop when the text entered is Stop. However even though when I type Stop in the console, it doesn't work. I tried to debug it and see it tries to compare the Stop text but doesn't stops it. I don't understand what is the problem.
This is a java code running in eclipse.
import java.util.Scanner;
public class Application8_Switch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string to match the output");
String text;
do {
text = input.nextLine();
switch (text) {
case "start":
System.out.println("Machine started");
break;
case "end":
System.out.println("This Machine stopped");
break;
default:
System.out.println("Command not recognized");
break;
}
} while (text != "Stop");
}
}
Try this:
Scanner input = new Scanner(System.in);
System.out.println("Enter a string to match the output");
String text;
do {
text = input.nextLine();
switch (text) {
case "start":
System.out.println("Machine started");
break;
case "end":
System.out.println("This Machine stopped");
break;
default:
System.out.println("Command not recognized");
break;
}
} while (!text.equals("Stop"));
Modifications:
Used !text.equals("Stop") because == checks by comparing references. However You need to use equals() method to check its content.
Strings in Java aren't compared using == or != like you think they would be.
Instead of using text != "Stop", use !text.Equals("Stop").
Related
I have a basic console app where I'm just trying to use a simple Scanner in a while loop to catch user input. I've tried putting standardInput = System.in in the build.gradle, but my program doesn't block when it should to wait for input.
while (stillWriting) {
System.out.println(
"Press 1 to write something,\n" +
"Press 2 to erase something,\n" +
"Press 3 to exit."
);
//if you select 1, it goes into the case, but does not block
//then ends up here again.
int userSelection = scanner.nextInt();
switch (userSelection) {
case 1:
System.out.println("Enter text to be written: ");
//vvvvvv should block here but doesn't. vvvvvv
String textToWrite = scanner.nextLine();
paper = pencil.write(paper, textToWrite);
break;
case 2:
//some code
break;
case 3:
stillWriting = false;
break;
default:
System.out.println(userSelection + " is not valid.");
break;
}
}
Are there any alternatives or jars I can use that make it block correctly and actually wait for input?
turns out in each case that you want to take input, if you just reassign a new Scanner() to the scanner variable, it will correctly block.
Still won't pick up a newline character though.
You have to consume the <Enter> that the user inputs to make his choice, otherwise it would (instantly) be consumed by your String textToWrite = scanner.nextLine();:
[...]
int userSelection = scanner.nextInt();
scanner.nextLine(); // <-- consume the <enter>
switch (userSelection) {
[...]
First of all, thank you for reading this post.
I have this case of exception handling followed by a switch. After the exception handling ends correctly, the switch code is executed in a never-ending loop. If I comment the exception handling part and just add
"selection = scanner.nextInt()" the code works fine. But with the exception handling, never-ending loop happens again. I am quite sure it is all about the position of the curly braces but I just can't sort out which of them.
Thank you for help on this.
import java.util.Scanner;
class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main( String[] args ) {
ToString human = new ToString("John", 30, true);
int selection = 0;
boolean quit = false;
String selecta = null;
String message = "Select option";
while (!quit) {
returnMessage(message);
while (selecta == null) {
try {
selecta = scanner.nextLine();
selection = Integer.valueOf(selecta);
break;
} catch (NumberFormatException e) {
returnMessage("An integer was expected. Please try again.");
selecta = null;
returnMessage(message);
}
}
switch (selection) {
case 1:
System.out.println(human.getAge());
break;
case 2:
System.out.println(human.getName());
break;
case 3:
System.out.println(human.isMan());
break;
case 4:
quit = true;
break;
}
}
}
public static void returnMessage (String message){
System.out.println(message);
}
}
selecta variable never gets set to null after the switch statement and since your input is in a block with a condition selecta == nullit never executes and goes straight back into the switch statement, and so on, and so on...
Put selecta = null after the switch statement and that should be it.
I need help developing my text message abbreviation decoder I'm trying to put together. The first part of the program should do this: "If a user's input string matches a known text message abbreviation, output the unabbreviated form, else output: Unknown. Support two abbreviations: LOL -- laughing out loud, and IDK -- I don't know." Then: "Expand to also decode these abbreviations. BFF -- best friends forever, IMHO -- in my humble opinion and TMI -- too much information.
This is the code I have so far:
import java.util.Scanner;
public class TextMsgAbbreviation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String textMsg = "";
{
String BFF = "best friends forever";
String IMHO = "in my humble opinion";
String TMI = "too much information";
String LOL = "laughing out loud";
String IDK = "i don't care";
System.out.println("Input an abbreviation:" + " ");
textMsg = input.next();
if (textMsg.compareTo("LOL") == 0) {
System.out.println(LOL);
} else if (textMsg.compareTo("IDK") == 0) {
System.out.println(IDK);
} else if (textMsg.compareTo("BFF") == 0) {
System.out.println(BFF);
} else if (textMsg.compareTo("IMHO") == 0) {
}
}
}
}
This is the output I get:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at TextMsgAbbreviation.main(TextMsgAbbreviation.java:17)
What am I doing wrong?
According to the Java API docs, the next() method throws a NoSuchElementException when there aren't any more tokens available to be read. So, it is recommended to call the hasNext() method before calling the next() method in Scanner class to make sure that there is a token available to be read. So, try something like below :
if(input.hasNext()) {
textMsg = input.next();
}
On a side-note, from Java 7 onwards, the switch statements can take a String input, so you may try using that in your code. In my personal opinion, it will be more readable than using the multiple if-else loops.
An example :
switch(textMsg) {
case "LOL" : System.out.println(LOL);
break;
case "IDK" : System.out.println(IDK);
break;
case "BFF" : System.out.println(BFF);
break;
case "IMHO": System.out.println(IMHO);
break;
default : System.out.println("Unknown");
}
The values displayed 862 1371 17 need to be typed into the input box.Below is working code for the problem.
import java.util.Scanner;
public class TextMsgDecoder {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput;
System.out.println("Enter text:");
userInput = scnr.nextLine();
System.out.println("You entered: " + userInput);
if(userInput.indexOf("BFF") != -1) {
System.out.println("BFF: best friend forever");
}
if(userInput.indexOf("IDK") != -1) {
System.out.println("IDK: I don't know");
}
if(userInput.indexOf("JK") != -1) {
System.out.println("JK: just kidding");
}
if(userInput.indexOf("TMI") != -1) {
System.out.println("TMI: too much information");
}
if(userInput.indexOf("TTYL") != -1) {
System.out.println("TTYL: talk to you later");
}
}
}
I would love to share my code. But in my university the code gets tested for "cheating".
But here is my code in simplier form.
public static String readin() {
boolean error = false;
do {
string stringin;
stringin = JOptionPane.showInputDialog(null, "Please enter a number");
switch (stringin.length()) {
case 0:
JOptionPane.showMessageDialog(null, "Error Please repeat");
error = true;
case 1:
return stringin;
}
return null;
} while (error == true);
}
This Code is really in it's simpliest form. I know that for this case it would be smarter to set the while to JOptionPane is empty or something. Since in my code are like 12 different error cases. I want to use the boolean. Please: the return null will never occur in the real code.
But the real problem I have: It works perfectly fine besides: if he repeats the loop he doesn't give me the chance to type a new stringin in.
How can i do this?
Also I am sorry for my faults in english.
EDIT:
All your helps fixed my problems! Thank you very much! I love this forum!
Try with break before case 1 (#Tuxxy_Thang) and remove return null; before while (error); and put after.
public static String readin(){
boolean error=false;
do{
string stringin;
stringin=JOptionPane.showInputDialog(null,"Please enter a number");
switch (stringin.length()){
case 0: JOptionPane.showMessageDialog(null, "Error Please repeat");
error=true;
break;
case 1: return stringin;
}
} while (error);
return null;
}
You dont have to check for while condition as you wanted the user to repeat again.Return only if you have the right value else ask again
public static String readin() {
while (true) {
String stringin = JOptionPane.showInputDialog(null, "Please enter a number");
switch (stringin.length()) {
case 0:
JOptionPane.showMessageDialog(null, "Error Please repeat");
break;//is important in switch cases
case 1:
return stringin;
}
}
}
There are two reasons:
The return null should be moved to end.
There should be a break statement at the end of the first case
I have given the modified code and it repeats the loop if the user does not enter anything for the JOptionPane:
public static String readin() {
boolean error = false;
do {
String stringin;
stringin = JOptionPane.showInputDialog(null,
"Please enter a number");
switch (stringin.length()) {
case 0:
JOptionPane.showMessageDialog(null, "Error Please repeat");
error = true;
break; // **added**
case 1:
return stringin;
}
} while (error == true);
return null; // Moved here. It will return if user entered more than 1 letter.
}
You are making a simple job hard, use Java classes properly and you will have an easier time of things
public static String readin()
{
Boolean gettingNumber = true;
String stringin = null;
while (gettingNumber)
{
stringin = JOptionPane.showInputDialog(null, "Please enter a number");
try
{
Integer number = Integer.parseInt(stringin);
gettingNumber = false;
}
catch (NumberFormatException exception)
{
// no need to do anything
}
}
System.out.println("returning [" + stringin + "]");
return(stringin);
}
I added this because I deduced that you are asking the user to input a number but your code would only allow the user ot enter any single character regardless of whether it is a valid digit or not and that is what you would return form your original method.
I'm making a game which plays until the user enters quit in the command line.
The user can enter different commands like get and go, with the get command the user can say what to get like, get baseball bat. What I do in my code is split the command.
everything is working fine but I have found a bug which I can't solve. If I enter "get" and press space and then ctrl+z it gets in a while loop which never ends.
It only happens with ctrl+z (1 time with ctrl c but after that 1 time not anymore)
private void run()
{
while (! quitCommand)
{
String input = null;
try
{
input = null;
System.out.println("Input "+ input);
System.out.println("Give a command.");
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
input = is.readLine();
handleCommand(input);
// As long as the command isn’t to quit:
// get the next input line and handle it. (With handleCommand.)
}
catch (Exception e)
{
System.out.println("Something went wrong we are sorry try again.");
e.printStackTrace();
}
}
}
/**
* #param userInput (This is the entire input string from the user.)
*
* (Tell others to) Perform the task which belongs to the given
* command.
*/
private void handleCommand(String userInput)
{
// Split the user input string.
if (userInput != null) // user input can not be empty
{
String[] delenTekst = userInput.split(" ");
// The first word is a command. The rest is extra information
String command = delenTekst[0];
String extra = "";
for (int i = 1; i < delenTekst.length; i ++)
{
if (i == 1)
{
extra = extra + delenTekst[i];
}
else
{
extra = extra +" " + delenTekst[i];
}
}
switch (command)
{
// Check if the command is to travel between rooms. If so, handle
case "go"
:
this.checkRoomTravel(extra);
break;
// If there isn't any room travel, then check all other command
case "get"
:
System.out.println("Looking for " +extra );
this.handleGetCommand(extra);
break;
case "quit"
:
quitCommand = true;
break;
default
:
System.out.println("Command is not known try help for information");
break;
}
}
else
{
userInput = "help";
}
}
I'm new to java so it can be something really simple.
On the top of my script I have a private boolean quitCommand = false; which is to check if the user entered quit.
Ctrl+Z closes the Console and therefore your readLine() returns null as pretended to indicate that end of file was reached. So all you need to do, is to check for null returned by readLine() and handle this as you handle the "quit".
I've changed your code (just to test my thesis) and also stream lined a few things, e.g. you dont need to recreate a BufferedReader every time you read a line.
private boolean quitCommand = false;
private void runIt() {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
String input = null;
while(!quitCommand) {
try {
System.out.print("Give a command: ");
input = is.readLine();
// As long as the command isn’t to quit:
if(input == null || "quit".equals(input.trim())) quitCommand = true;
if(quitCommand) break;
// get the next input line and handle it. (With handleCommand.)
String[] words = input.trim().split("\\s+");
// ** This is the original handleCommand line **
System.out.println(input + ":" + Arrays.toString(words));
}
catch (Exception e) {
System.out.println("Something went wrong we are sorry try again.");
e.printStackTrace();
}
}
}
BTW: To split the input into words I'd use the regular expression as shown in my code. This works also if the user enters tabs or multiple spaces.
On DOS/Windows Ctrl+Z means end of input. This causes readLine() to return null no matter how many times you call it. This is likely to cause your code to fail as you don't appear to check for it. I suspect you are getting a NullPointerException which you are pretending didn't happen and trying again, endlessly.