Reputation: 33
I have been working on a simple robot that responds only to certain things, but if it doesn't understand, tell the user that. I have two questions. I am using the switch function for this, and wanted to set the default to the robot not understanding. When I try to launch the program, I notice that the robot says that it doesn't understand immediately, before I even enter anything. How would I do this in a way that the default case happens only after the user has entered something. I tried using
if(!userInput=null) {
then the switch statement follows, but that gives me an error because it says it is not a boolean.
One more question. There is also an problem with the variable, userInput. Eclipse says "Resource Leak: userInput is never closed" Does anyone know how to fix this? Here is my current code:
package com.robot;
import java.util.Scanner;
public class Robot {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
switch(userInput.toString()) {
case "hello":
robotSay("hello");
break;
case "hi":
robotSay("hi");
break;
case "hey":
robotSay("hello");
break;
default:
robotSay("I do not understand");
break;
}
}
public static void robotSay(String string)
{
System.out.println(string);
}
}
Upvotes: 1
Views: 82
Reputation: 656
You need to use String input = userInput.next(); before switch statement and use switch (input) so that the scanner will wait for user input and read it before executing switch.
After the switch you need to use userInput.close() in order to close the scanner that will make the error go away.
Upvotes: 0
Reputation: 1924
You should use
switch(userInput.nextLine()) {
.nextLine()
returns the first unread line in System.in
(and waits for input if necessary).
.toString()
returns a String representation of the object, in you case it would lock something like this:
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\.][decimal separator=\,][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
the ResourceLeak is created, because you never close the InputStream (inside the Scanner), so that resource will be unavailable to other programs until your program finishes.
Just do
userInput.close();
in the end.
Upvotes: 3