This question already has answers here:
Scanner only reads first word instead of line
(5 answers)
Closed 2 years ago.
The code works for the most part, but if I type "No way" it still stops the loop. Should I set it up a different way or use a length function ? Everything I've searched on breaking a loop used integers.
See the code below:
import java.util.Scanner;
public class CarryOn {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Shall we carry on?");
String answer = String.valueOf(scanner.next());
if (answer.equalsIgnoreCase("no")){
break;
}
}
}
}
Using .next in this case only stores "no" in "no way". Use .nextLine instead:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Shall we carry on?");
String answer = String.valueOf(scanner.nextLine());
if (answer.equalsIgnoreCase("no")){
break;
}
}
Output:
Shall we carry on?
no way
Shall we carry on?
no
Check this post for more information.
scanner.next()
only reads a single token. No way is two tokens: No and way.
Use scanner.nextLine() instead, if you want to read the whole line.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
boolean a = true;
do {
Scanner input = new Scanner(System.in);
System.out.println("Press any on keyboard:");
String keys = input.nextLine();
System.out.println("You pressed:");
System.out.println(keys);
System.out.println("Your hash is:");
String B = "#B";
String hash = B+keys;
System.out.println(hash);
System.out.println("To end loop press f");
//End Loop
Scanner exit = new Scanner(System.in);
String end = exit.nextLine();
if (end=="f") {
a=false;
}
}
while(a);
}
}
I've been using python and I decided to start learning java since android studio requires it. I'm learning how to do loops again. I can't get this to work. I already looked this up I couldn't find it. How would I end this by pressing 'f'? My thought process was that once it was done going though the first lines of the do loop, it would go though the if statement changing the value of a ending the loop.
use break statement under if(){} body. also your == comparison will give false, use str1.equals(str2) for comparison.
Your problem is you are comparing strings with ==.You have to use equals to write correct if statement.
if (end.equals("f")){...}
You could use the below code to check
if (end.equals("f")) { // end == "f" , it check the reference.
a = false;
}
This question already has answers here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Is it mandatory to close a Scanner?
(2 answers)
Does closing Scanner affect performance
(1 answer)
How do I close my scanner?
(4 answers)
Closed 4 years ago.
So I spent some time studying up on util.Scanner thanks to some feedback here. The statement that stuck with me the most was found in this post on How to use java.util.Scanner to correctly...
You will probably never actually see Scanner used in professional/commercial line of business apps because everything it does is done better by something else. Real world software has to be more resilient and maintainable than Scanner allows you to write code. Real world software uses standardized file format parsers and documented file formats, not the adhoc input formats that you are given in stand alone assignments.
So, I looked up some other options for getting user input and decided to use BufferedReader. What I'm trying to accomplish is to get the user to tell the program whether they would like to continue playing the game or not, to have the program repeat the question until given valid input (Y/N), and to have the program continue or terminate as a result of the answer.
Three related questions:
Is BufferedReader a better option than Scanner?
Is there an option that better addresses this task? What is it, if so?
Is it appropriate to have the method call itself to create a "loop" if the answer does not fit the criteria?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RageGame {
public static void main(String[] args) throws IOException {
char playAgain = 'Y';
// Loop game until user decides they are done.
do {
playAgain = playRage();
} while (playAgain == 'Y');
//Quit message
System.out.println("Thanks for playing Rage!");
}
public static char playRage() throws IOException {
return playAgain();
}
public static char playAgain() throws IOException{
char answer;
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
//Ask the user if they want to continue and set their response to upper case.
System.out.println("Do you wish to play again? (y/n)");
answer = (char) Character.toUpperCase(kb.read());
//Check if answer fits criteria
if (answer != 'Y' && answer != 'N') {
System.out.println("Sorry, " + answer + " is not a valid answer.");
return playAgain();
}else {
return answer;
}
}
}
The short answer is: Don't close it.
Your Scanner is using the stream System.in. System.in is not a resource acquired by your program (you didn't open the stream), so you shouldn't close it. Someone else is in charge of closing that.
If you find the warning annoying, you can probably silence it.
Let's suppose that your scanner takes input from a file and not System.in, then you need to call close after the last time you need it:
answer = Character.toUpperCase(kb.next().charAt(0));
kb.close();
If you are afraid of forgetting to call close, just use a try-with-resources block and it will close it for you!
try (Scanner kb = new Scanner(some other source)) {
System.out.println("Do you wish to play again? (y/n)");
answer = Character.toUpperCase(kb.next().charAt(0));
} // this will always close the scanner
On a alternative note, if you would like to close the scanner, you can wrap the System.in inside a CloseShieldInputStream. Your scanner would use a Proxy Stream. If you are interested take a look at http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/CloseShieldInputStream.html
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
public static char[] puzzleInput() {
printEnterPuzzleMessage();
Scanner puzzleS = new Scanner(System.in);
if(puzzleS.hasNext()) {
char[] puzzle = puzzleS.next().toCharArray();
while(!isLegalPuzzleStructure(puzzle)) {
printIllegalPuzzleMessage();
puzzleInput();
}
return puzzle;
}
puzzleS.close();
return null;
}
public static void main(String[] args) throws Exception{ //Q - 8
Scanner fileName = new Scanner(System.in);
if(!fileName.hasNext()) {
System.out.println("No argument has been received");
System.exit(0);
}
String filePath = fileName.nextLine();
fileName.close();
Scanner vocabulary = new Scanner(new File(filePath));
String[] vocabularyArr = scanVocabulary(vocabulary);
vocabulary.close();
printReadVocabulary(filePath, vocabularyArr.length);
printSettingsMessage();
printEnterPuzzleMessage();
char[] puzzle = puzzleInput();
Hi, a beginner in Java is here.
In the function puzzleInput, I open a Scanner to get an input from the user. For some reason, the program won't give me a chance to put in input, and therefor the argument (puzzle) gets a null as default, and later when puzzle is needed not as a null - throws a NullPointerException.
There are many other functions in the code, but most of them are just a print commands, and the ones who are not were being checked by me, and are OK.
The problem is just the scanner won't give me a chance to put in an input.
Some points I'd like to clarify further:
1. The first Scanner (fileName) is not being skipped by the program, and I'm able to give it an argument.
2. I made sure I closed all the other scanners i've opened before.
Can someone explain me what I'm doing wrong?
program won't give me a chance to put in input
Your problem is that you are closing your Scanner in main:
Scanner fileName = new Scanner(System.in);
...
fileName.close();
This in turn closes the System.in input-stream which then cannot be reused in your puzzleInput() method because it is already closed. The right thing to do here is to pass in the Scanner variable into your puzzleInput() method and continue to reuse it there and not try to open up a new Scanner.
public static char[] puzzleInput(Scanner scanner) {
printEnterPuzzleMessage();
if(scanner.hasNext()) {
...
// don't close it here
return null;
}
...
Scanner scanner = new Scanner(System.in);
...
puzzleInput(scanner);
Couple of other comments:
Calling a Scanner fileName is not a good pattern. Choosing good names for your variables will help make the code self-documenting. scanner would be a better name of course.
When dealing with any input/output, it is a good practice to wrap any opening method in a try/finally block so it gets close properly. See also the try-with-resources functionality added in Java 7.
If you want a chance to do something with the input with a prompt, why not assign it to a String variable? This allows you to manipulate the input however you want later on too.
String input = scannerName.nextLine();
This question already has answers here:
Endless while loop problem with try/catch
(2 answers)
Closed 7 years ago.
Below code,
import java.util.Scanner;
public class Dummy {
static Scanner sc = new Scanner(System.in);
public static int getIntegerInput(String prompt){
int choice = 0;
for(;;){
System.out.print(prompt);
try{
choice = sc.nextInt();
break;
}catch(java.util.InputMismatchException ex){
System.out.print("What??? ");
}
}
return choice;
}
public static void main(String[] args) {
int choice = getIntegerInput("Enter a number: ");
} //end main
}
does not stop for next user input, if the first user input raised an exception.
How do I understand this problem in the above code? placing sc.next() in catch resolves the problem. But I'm still not clear what is going on under the hood? What is the right approach to resolve this problem?
When nextXYZ() fails to consume a token it leaves it in the InputStream. Here, you are looping over the same input endlessly - each iteration, you attempt to consume this token, throw an exception if it isn't an integer, catch it, and try reading it again - forever.
EDIT:
In order to work around this, you could use next() to consume that token and move on to the next one:
for(;;) {
System.out.print(prompt);
try{
choice = sc.nextInt();
break;
} catch(java.util.InputMismatchException ex) {
sc.next(); // here
}
}
The problem with Scanner next() are they will not advances if the match is not found. And the character for which it failed remain in the stream. Hence its very important to advance the scanner if you found non intended character.
You can use next() method which actually consumes any character or you can use skip method passing skip pattern.
Use hasNext() to know whether a valid match is present or not. If not then consume that character using above said methods.
If it doesnt find an int on the next like, it throws an error. This error is then caught by your program, so the break is never hit because the error jumps over it whenever a non-int (including nothing) is found.
This question already has answers here:
How can I read input from the console using the Scanner class in Java?
(17 answers)
Closed 7 years ago.
I'm trying to make it so when the user writes Start the program does something, but I'm unsure of how to what the user actually wrote.
This was my first attempt at it:
import java.util.Scanner;
public class Suhwag {
public static void main (String args[]){
Scanner scanNer = new Scanner (System.in);
System.out.println("Please write \"Start\" to begin.");
String stinky = "Start";
if (stinky == scanNer);
But with this, I got the error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Incompatible operand types String and Scanner
After I saw the error, I tried to convert scanNer to a string as seen here:
import java.util.Scanner;
public class Suhwag {
public static void main (String args[]){
Scanner scanNer = new Scanner (System.in);
System.out.println("Please write \"Start\" to begin.");
String stinky = "Start";
String input = scanNer.nextLine();
if (stinky == scanNer);
But the same error message still appears. Anyone know what I could do to make it work?
You're trying to compare a Scanner object with a String object. First, you could input the string with the following line:
String myString = scanNer.next()
Then, compare it with "Start":
if ( myString.equals( "Start" ) )
{
...
}
You are comparing a String to a Scanner object.
You should use the equals method to compare String's
No need for the semi-colon after the if (see below)
In reference to your last code snippet:
if (stinky.equals(input)){
//do something
}
in the latter code area you said in your if statement:
stinky == scaNer
it should be
stinky.equals(input)
in your if statement, you compared still your scanner with ur stinky
change your if statment to this
if (input.equals(stinky)){<code here>}
your previous code didnt work because you compare a scanner with a string