Check input using Java Scanner while typing [duplicate] - java

This question already has answers here:
How to read a single char from the console in Java (as the user types it)?
(7 answers)
Closed 2 years ago.
I was Trying to find a way to check the user input while typing so if they typed a special character ("#") the execution will terminate immediately without pressing Enter (using Java Scanner) , I tried this code but it needs to press enter each time .I couldn't find a way to do that
I'd appreciate any help.
import java.util.Scanner;
public class test{
public static void main(String[] args) {
Scanner scan =new Scanner(System.in);
while (true) {
String input =scan.next();
if (input.equals("#")) {
break;
}
System.out.println("yes");
}
}
}

you may read byte by byte and stop read when entering the special character.
For example:
char key;
do{
key = scanner.nextByte() // be careful with encoding. utf-8 may use 2 bytes per symbol
//do stuff
}while(key != '#')

Try reading the input char by char. Something like this:
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
if(c == '#')
{
// terminate execution
}

you can try this. System.in.read() will read the entered character. If the entered character is # you can terminate the execution. If the user has entered the enter key you can use the whitespace() method to break out of the loop.
char arr[] = new char[100];
for(int i=0;i<100;i++) {
arr[i] = (char)System.in.read();
if (arr[i].equals("#")) {
System.exit(1);
}
if(arr[i].isWhitespace()){
break;
}
}

Related

Why does the string inside println method show twice?

In the following code why does the string inside println method shows twice.What should I do to show the message once per iteration
package practicejava;
public class Query {
public static void main(String[] args) throws java.io.IOException {
System.out.println("Guess a capital letter Character");
while ((char) System.in.read() != 'S') {
System.out.println("wrong.guess again to finish the program");
}
}
}
When a user writes in console characters, to confirm fact that his input is ready to be passed to application he presses enter key. But console doesn't pass only provided characters, it also adds to input stream (System.in) OS dependent line separator character(s) after it. Some OS use \r or \n (those are single characters, \x is just notation to represent them) others like Windows use \r\n (two characters) sequence as line separator.
Now those additional characters are also read by System.in.read() and since they are not equal to S System.out.println("wrong.guess again to finish the program"); is executed additional time.
To avoid such problems instead of working with raw data via System.in.read() consider using classes meant to make our life easier like java.util.Scanner
Scanner sc = new Scanner(System.in);
System.out.println("Guess a capital letter Character");
String response = sc.nextLine();
while(!response.equals("S")){
System.out.print("incorrect data, please try again: ");
response = sc.nextLine();
}
Its because the first char that you read is the letter you typed, and then there is a second loop where the character is the line return.
For example on my linux machine, if I input "E" and then press enter, the first loop processes the char 69 'E', and then there is a second loop to process the carriage return (char 10).
What you can do is use a Scanner to get the user's input:
package practicejava;
import java.util.Scanner;
public class Query {
public static void main(String[] args) throws java.io.IOException {
Scanner s = new Scanner(System.in);
char c;
do {
System.out.println("Guess a capital letter Character");
c = s.next().charAt(0);
if (c != 's') {
System.out.println("Wrong! Guess again to finish the program.");
}
} while(c != 's');
}
}
s.next() will get the input from the user as a string and s.next().charAt(0) will return the first character in that string.

Java Scanner: stop reading after the first entry

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());

Printing a message if a char has more than one symbol(using char, not String)

Basically I need to write this message:
System.out.println("Invalid grade - must enter exactly one letter");
And I don't know how to write an (if,for,while loop) which will find if letterGrade is bigger than one character, it has to be only one character if > 1 character it should follow this message.
And problem is that I know how to do it with string.length() but this is char and it doesn't work.
I tried this:
while(String.valueOf(letterGrade).length() > 1)
{
System.out.println("Invalid grade - must enter exactly one letter");
System.out.print("Enter grade (one character): ");
letterGrade = in.next().charAt(0);
}
But it doesn't print me message that I want, is there some method that finds char greater than one character? Can charAt() help me ?
I would propose to use regular expression since you might want to only allow letters a-f/A-F.
The expression to use would be
[a-fA-F]
The Java code used to check this would be:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Type");
Scanner reader = null;
try {
// Read from System.in
reader = new Scanner(System.in);
// Only work with first character
char c = reader.findInLine(".").charAt(0);
// ""+c creates a string since RegEx only works on strings
String testString = ""+c;
// Test string
if(!(""+c).matches("[a-fA-F]")) {
System.out.println("Invalid input");
return;
}
// c has a valid grade
System.out.println("Valid input");
}
catch(Exception ex) {
if(reader != null)
reader.close();
}
}
}
Test results:
a > Valid input
z > Invalid input
az > Valid input
za > Invalid input
You may use System.in.read(); if you want to read only one charactor.
So you should probably be a little more clear with your question and not in a paragraph form with the entire block of code including variable declaration and user inputlines.
In java, a char can only be one character (i am sure you know this) and so having multiple would mean that it is a string.
Assuming that you are working with letterGrade as an input from the user using Scanner, the way to check if the input is one character or not and do something in response will be
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(input.length==1)
{sysout("There is only 1 character in the input");
char value = input.indexOf(0);
}else
{sysout("Invalid grade");
}

Program goes in an infinite loop

This program goes in an infinite loop in while cycle. Please, can someone tell me why?
import java.util.Scanner;
public class program {
public static void main(String[] pars) {
System.out.println("Insert something.");
Scanner read = new Scanner(System.in);
String s = "";
while(read.hasNext()) {
System.out.println(read.next());
}
System.out.println("End of program");
}
}
Read the Javadoc of Scanner#hasNext():
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
Hence the while loop will always be executed in your case, each time waiting for input from the user. Since the Scanner is linked to System.in, the input stream will always block until the user inputs a string and hasNext() will always return true, unless the user signals the end of file (e.g. through the Ctrl+z combination on Windows). Scanner#hasNext() is more convenient when reading from files where the input size is known and the end of the file marks the end of the stream.
One way to end the loop here is to add a condition on the input:
while (read.hasNext()) {
s = read.next();
if(s.equals("quit")) {
break;
}
System.out.println(s);
}
P.S.: It is more conventional to name classes starting with an uppercase letter.
The problem is this line:
while(read.hasNext()) {
If you use System.in as a stream provided by the user, it will - if no such input is available - as #manouti says, block and wait for input. But even if you provide input, it will keep waiting. The system has no means to detect whether the user wants to provide additional input in the future.
It will only stop, if the Stream ends. This can be under two conditions:
The end of the file (in case of I/O redirection like java -jar program.jar < input.dat; or
The user marks the end of a stream, in most shells with Ctrl+D. This marks the end-of-stream.
An alternative is to provide some kind of stop directive. Something like "END". Thus:
while(read.hasNext()) {
String nx = read.next();
if(nx.equals("END")) {
break;
}
System.out.println(nx);
}
Just remove while loop
public static void main(String[] pars) {
System.out.println("Insert something.");
Scanner read = new Scanner(System.in);
String s = "";
System.out.println(read.next());
System.out.println("End of program");
}
Or if u want display certain no.of string then mention condition properly.
public static void main(String[] pars) {
System.out.println("Insert something.");
Scanner read = new Scanner(System.in);
String s = "";
int i=0;
while(i<5) {
System.out.println(read.next());
i++;
}
System.out.println("End of program");
}

How to convert user inputted char to its numerical position in Java? [duplicate]

This question already has answers here:
How to map character to numeric position in java?
(7 answers)
Closed 5 years ago.
So I'm stuck on this problem in my Java intro class. I'm a complete newbie at this stuff, so any help is appreciated. I have to design and create a program that accepts a user inputted letter (which should be either a-z or A-Z) and determine what position it holds in the alphabet. (so a would equal 0) I keep having issues with string to char and char to int conversions. Any tips or leads on how to design this program would be much appreciated. I've been working on this program literally all day and haven't had made any discernible progress.
Just subtract the char constant 'a' from your input char.
Try the following code:
char c = 'b';
System.out.println(c - 'a' + 1);
The output will be 2.
In order to get a user inputted anything use a Scanner. In this case the following code will prompt the user for a character then assign that to a variable called 'c'.
import java.util.*;
// assuming that the rest of this code is inside of the main method or wherever
// you want to put it.
System.out.print("Enter the letter: ");
Scanner input = new Scanner(System.in);
char c = Character.valueOf(input.next());
Then using this code use whatever method you like to convert to alphabetical position. Hope that helps!
I think it was answered already but putting it all together:
/**
* Gets the numerical position of the given character.
*/
private static final int convertToPosition(final char c) {
return c - 'A' + 1;
}
public static void main(String[] args) throws Exception {
System.out.print("Enter the letter: ");
Scanner input = new Scanner(System.in);
if (input.hasNext()) { // if there is an input
String inStr = input.next().toUpperCase();
if (inStr.length() != 1) {
System.out.println("Unknown letter");
return;
}
char c = inStr.charAt(0);
int pos = convertToPosition(c);
System.out.println("Position: " + pos);
} else {
System.out.println("no input");
}
}

Categories

Resources