Im looking for a form to make Scanner to stop reading when you push the first time (so, if I press the key K automatically the program considerer that I press the Intro key, so it stop to recognise inputs, save the K and keep going with the program).
Im using char key= sc.next().charAt(0); in a beginning, but dont know how to make it stop without pushing Intro
Thanks in advance!
If you want to stop accepting after a single particular character you should read the user's input character by character. Try scanning based on a Pattern of one single character or using the Console class.
Scanner scanner = new Scanner(System.in);
Pattern oneChar = new Pattern(".{1}");
// make sure DOTALL is true so you capture the Enter key
String input = scanner.next(oneChar);
StringBuilder allChars = new StringBuilder();
// while input is not the Enter key {
if (input.equals("K")) {
// break out of here
} else {
// add the char to allChars and wait for the next char
}
input = scanner.next(oneChar);
}
// the Enter key or "K" was pressed - process 'allChars'
Unfortunately, Java doesn't support non blocking console and hence, you can't read user's input character by character (read this SO answer for more details).
However, what you can do is, you can ask the user to enter the whole line and process each character of it until Intro is encountered, below is an example:
System.out.println("Enter the input");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
StringBuilder processedChars = new StringBuilder();
for(int i=0 ; i<input.length() ; i++){
char c = input.charAt(i);
if(c == 'K' || c == 'k'){
break;
}else{
processedChars.append(c);
}
}
System.out.println(processedChars.toString());
Related
I want to build a program that only stops scanning for strings until after I input "0" in the console, how do I do that?
I assume I can use do while loop, but I don't know what to put in the while() condition.
Scanner scan = new Scanner(System.in);
do {
String line = scan.nextLine();
//do stuff
} while(); //what do i put in here to stop scanning after i input "0"
Thanks in advance, I'm new to Java and OOP in general.
You can use a while loop instead of a do-while loop. Define a String that will be initialized inside the while loop. On each iteration we assign the String to Scanner#nextLine and check if that line is not equal to 0. If it is, the while-loop prevents iteration.
Scanner scan = new Scanner(System.in);
String line;
while (!(line = scan.nextLine()).equals("0")) {
System.out.println("line: " + line);
}
You don't have to use any loop , as you said you want to stop input when 0 is pressed by default for nextLine() the input stops when user press the enter key because it is the delimiter , so just change the delimiter
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("0"); //regex
String s = scanner.next(); // no matter what user enters the s will contain the input before 0
I am making a program that will read user input and determine with an if/else condition what to do. If the user hits just enter and doesn't type anything else in, I want to loop something through the if. If anything else is typed as an input, the program should exit back to a different menu.
Here is what I have so far:
Scanner scnr = new Scanner(System.in);
String choice = scnr.next();
if (choice.equals("")) {
...
}
else {
...
}
When I run through it, just pressing enter does not affect anything, it just makes the cursor advance to the next line in the console. However, when I type something in, the error part that sends it to the menu when anything else is typed in works just fine. I'm thinking I have to use something besides scnr.next(); but I don't know what that would be.
This is for an entry level class, and it requires that we use the scanner utility and not something more advanced. Thanks in advance.
do
{
//string variable used to take scanner input when
//looping generations
String choice = "";
printWorld( patternName, world, generationCounter);
System.out.println("Options");
System.out.println("(Enter): show next generation");
System.out.println("end(Enter): end this simulation");
System.out.print("Choice:");
choice = scnr.nextLine();
if (choice.length() == 0) {
//used as a filler array when the method
//next generation is called
boolean newWorld[][] = new boolean [world.length][world[0].length];
nextGeneration(world, newWorld);
for (int i=0; i<newWorld.length;i++){
for (int j = 0; j<newWorld[0].length; j++){
world [i][j] = newWorld[i][j];
}
}
generationCounter++;
System.out.println("went through");
} else {
generationKill = 1;
generationCounter = 1;
}
} while (generationKill !=1);
Try using scnr.nextLine(); instead of scnr.next();
The reason for this is because of tokens. next()'s documentation says:
public String next()
Finds and returns the next complete token from this scanner.
Token generally is separated by whitespaces ("\n", "\t", " ") and therefore will not recognize your "enter" or "\n" character as a token. Which is why it'll keep reading, thinking that you haven't entered any tokens.
nextLine() on the other hand will read until it finds a "\n" character. That means when you enter, it's reading in a "\n" character, thereby setting your choice to be "".
I am having a little problem with my code. Compiling and running works well, however, when I attempt to break out of the inner loop,
System.out.println("Type which category you want to add to.");
System.out.println("Homework, Classwork, Labs, Test, Quizzes, Midterm, Final");
The code above is printing twice to the terminal when I only want it to print once.
I have a feeling that is a simple mistake with the way my brackets are aligned but I am having difficulty with figuring out how to do it. Any help would be greatly appreciated!
import java.util.Scanner;
public class GetGrade {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX = 15;
int[] homework = new int[MAX];
int[] classwork = new int[MAX];
int[] lab = new int[MAX];
int[] test = new int[MAX];
int[] quizzes = new int[MAX];
int[] midterm = new int[MAX];
int[] fin = new int[MAX];
int hwCount, clCount, labCount, testCount, quizCount, midCount, finCount;
double hwTotal, clTotal, labTotal, testTotal, quizTotal, midTotal, finTotal;
double grade = 0;
String selection = "";
System.out.println();
System.out.println("Welcome to GetGrade!");
System.out.println();
while (true) {
System.out.println("Type which category you want to add to.");
System.out.println("Homework, Classwork, Labs, Test, Quizzes, Midterm, Final");
selection = input.nextLine();
if (selection.equals("homework")) {
System.out.print("What percentange of your grade is homework? > ");
double hwPercent = input.nextDouble();
System.out.println("Now begin typing your grades. When you are finished, type -1.");
for (int i = 0; i < homework.length; i++) {
homework[i] = input.nextInt();
hwTotal = homework[i] * hwPercent;
grade += hwTotal;
if (homework[i] == -1) break;
}
}
}
}
}
It's just as trivial as it seems:
The call to input.nextInt(); in your inner loop does not include the newline.
So you are breaking of the innerloop, receiving the next line which only contains the newline - character in input.nextLine(); which is the remaining input of your "-1\n" line and proceed with the main loop again as it does not match "homework".
Try setting the conditional variable in your while loop to an actual boolean rather than true.
Also, when you invoke "break", you are only breaking out of the for loop. If you reassign a boolean variable to false at this point, you would exit the while loop completely.
Just before while loop ends, add a "Do you want to continue? (Y/N)" functionality.
If user enters "N" or anything else, execute another break. And that break will make you get out of the while loop.
The simple way to get your code working is to change
selection = input.nextLine();
to
selection = input.next();
next() only reads in a string value (which is what you are actually doing in your code) instead of the newline character as Peter has suggested.
So the an extra iteration of the while does not take place when you read the newline character.
When you use a scanner to read a line from the keyboard, it reads everything up to and including the newline character the user types to submit their input. So for example:
Type which category you want to add to.
Homework, Classwork, Labs, Test, Quizzes, Midterm, Final
>
If you type "homework" and then ENTER, the actual input becomes "homework\n". input.nextLine() will scan the input until it encounters the first newline character, '\n', which it will consume and then it returns everything up to that point (i.e. "homework").
Your problem here is that input.nextInt() does NOT consume a newline character, and so there is still a newline character in the input buffer by the time your while loop starts another round.
Now begin typing your grades. When you are finished, type -1.
> ...
> -1
=> User input is "-1\n"
-------------------------------
// Meanwhile, back in the code...
for (int i=0;i<homework.length;i++) {
homework[i] = input.nextInt(); // <--- This call consumes "-1" but leaves '\n'
hwTotal = homework[i] * hwPercent;
grade += hwTotal;
if (homework[i] == -1) break;
}
That newline is consumed by the next call to input.nextLine(), leaving the input buffer empty.
while (true) {
System.out.println("Type which category you want to add to.");
System.out.println("Homework, Classwork, Labs, Test, Quizzes, Midterm, Final");
selection = input.nextLine(); // <--- This call consumes the leftover '\n' and returns the empty string
...
And because "" is not equal to "homework", the while loop goes around one more time, but this time the input buffer is empty, and so the call to input.nextLine() behaves as you would expect.
// selection is empty, so this condition fails and the program loops back around
if (selection.equals("homework")) {
...
There are two easy solutions to this problem. You can
Use Integer.parseInt(input.nextLine()) instead of input.nextInt()
Add an extra call to input.nextLine() at the end of your while loop to consume the final newline character
The first option is probably the most robust, and you get the added benefit of a run-time error being thrown if they do not give you a valid integer as input.
I have started to learn Java, wrote couple of very easy things, but there is a thing that I don't understand:
public static void main(String[] args) throws java.io.IOException
{
char ch;
do
{
System.out.println("Quess the letter");
ch = (char) System.in.read();
}
while (ch != 'q');
}
Why does the System.out.println prints "Quess the letter" three times after giving a wrong answer. Before giving any answer string is printed only once.
Thanks in advance
Because when you print char and press Enter you produce 3 symbols (on Windows): character, carriage return and line feed:
q\r\n
You can find more details here: http://en.wikipedia.org/wiki/Newline
For your task you may want to use higher level API, e.g. Scanner:
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Guess the letter");
ch = scanner.nextLine().charAt(0);
} while (ch != 'q');
Using System.in directly is probably the wrong thing to do. You'll see that if your character is changed from q to something in Russian, Arabic or Chinese. Reading just one byte is never going to match it. You are just lucky that the bytes read from console in UTF-8 match the character codes for the plain English characters.
The way you are doing it, you are looking at the input as a stream of bytes. And then, as #Sergey Grinev said, you get three characters - the actual character you entered, and the carriage return and line feed that were produce by pressing Enter.
If you want to treat your input as characters, rather than bytes, you should create a BufferedReader or a Scanner backed by System.in. Then you can read a whole line, and it will dispose of the carriage return and linefeed characters for you.
To use a BufferedReader you do something like:
BufferedReader reader = new BufferedReader( InputStreamReader( System.in ) );
And then you can use:
String userInput = reader.readLine();
To use a Scanner, you do something like:
Scanner scanner = new Scanner( System.in );
And then you can use:
String userInput = scanner.nextLine();
In both cases, the result is a String, not a char, so you should be careful - don't compare it using == but using equals(). Or make sure its length is greater than 1 and take its first character using charAt(0).
As has been mentioned, the initial read command takes in 3 characters and holds them in the buffer.
The next time a read command comes around, it first checks the buffer before waiting for a keyboard input. Try entering more than one letter before hitting enter- your method should get called however many characters you entered + 2.
For an even simpler fix:
//add char 'ignore' variable to the char declaration
char ch ignore;
//add this do while loop after the "ch = (char) System.in.read();" line
do{
ignore = (char) System.in.read();
} while (ignore != '\n');
this way 'ignore' will cycle through the buffer until it hits the newline character in the buffer (the last one entered via pressing enter in Windows) leaving you with an fresh buffer when the method is called again.
sry about my english :)
Im new to Java programming and i have a problem with Scanner. I need to read an Int, show some stuff and then read a string so i use sc.nextInt(); show my stuff showMenu(); and then try to read a string palabra=sc.nextLine();
Some one told me i need to use a sc.nextLine(); after sc.nextInt(); but i dont understand why do you have to do it :(
Here is my code:
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int respuesta = 1;
showMenu();
respuesta = sc.nextInt();
sc.nextLine(); //Why is this line necessary for second scan to work?
switch (respuesta){
case 1:
System.out.println("=== Palindromo ===");
String palabra = sc.nextLine();
if (esPalindromo(palabra) == true)
System.out.println("Es Palindromo");
else
System.out.println("No es Palindromo");
break;
}
}
Ty so much for your time and Help :D
nextInt() only reads in until it's found the int and then stops.
You have to do nextLine() because the input stream still has a newline character and possibly other non-int data on the line. Calling nextLine() reads in whatever data is left, including the enter the user pressed between entering an int and entering a String.
When you input a value (whether String, int, double, etc...) and hit 'enter,' a new-line character (aka '\n') will be appended to the end of your input. So, if you're entering an int, sc.nextInt() will only read the integer entered and leave the '\n' behind in the buffer. So, the way to fix this is to add a sc.nextLine() that will read the leftover and throw it away. This is why you need to have that one line of code in your program.