Cannot get char user input to work [duplicate] - java

This question already has answers here:
Take a char input from the Scanner
(24 answers)
Closed 8 years ago.
This is what I have in my code
char guess = Keyboard.readChar();
but the error message comes up as "The method readChar() is undefined for the type scanner" The scanner i have is Scanner keyboard = new Scanner (System.in). Why Is this wrong?

you need to use this
char guess = keyboard.next().charAt(0);

Scanner does not have a method to read a char. Fundamentally, System.in is a buffered stream. You can read a line,
while(keyboard.hasNextLine()) {
String line = keyboard.nextLine();
char[] chars = line.toCharArray(); // <-- the chars read.
}

You can trying using nextLine() which reads in a String of text.
char code = keyboard.nextLine().charAt(0);
charAt(0) takes in the first character of the received input.
Additional Note:
If you want to convert user inputs to upper/lower case. This is especially useful.
You can chain String methods together:
char code1 = keyboard.nextLine().toUpperCase().charAt(0); //Convert input to uppercase
char code2 = keyboard.nextLine().toLowerCase().charAt(0); //Convert input to lowercase
char code3 = keyboard.nextLine().replace(" ", "").charAt(0); //Prevent reading whitespace

Related

Is there a way to accept a single character as an input?

New to programming, so my apologies if this is dumb question.
When utilizing the Scanner class, I fail to see if there is an option for obtaining a single character as input. For example,
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String a = input.nextLine();
}
}
The above code allows me to pull the next line into a string, which can then be validated by using a while or if statement using a.length() != 1 and then stored into a character if needed.
But is there a way to pull a single character instead of utilizing a string and then validating? If not, can someone explain why this is not allowed? I think it may be due to classes or objects vs primitive types, but am unsure.
You can use System.in.read() instead of Scanner
char input = (char) System.in.read();
You can also use Scanner, doing something like:
Scanner scanner = new Scanner(System.in);
char input = scanner.next().charAt(0);
For using Stringinstead of char, you can also to convert to String:
Scanner scanner = new Scanner(System.in);
String input = String.valueOf(input.next().charAt(0));
This is less fancy than other ways, but for a newbie, it'll be easier to understand. On the other hand, I think the problem proposed doesn't need amazing performance.
Set the delimiter so every character is a token:
Scanner input = new Scanner(System.in).useDelimiter("(?<=.)");
String c = input.next(); // one char
The regex (?<=.) is a look behind, which has zero width, that matches after every character.

String concat error using Scanner class? [duplicate]

This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(15 answers)
Closed 6 years ago.
I have a error when i give a input for string t= "is my favorite language";
it shows output java is . please tell what i made a mistake.
public class DataTypes {
public static void main(String[] args) {
String s = "Java ";
Scanner scan = new Scanner(System.in);
String t = scan.next();
String u = s.concat(t);
System.out.println(u);
}
}
scan.next() will get the next token from the input. The default delimiter for this is whitespace, so it will get the first word from your input.
To get all of the input up until the newline (when the user presses enter) use scan.nextLine() instead.
String s = "Java ";
Scanner scan = new Scanner(System.in);
String t = scan.nextLine();
String u = s + t;
System.out.println(u);
Use:
scanner.nextLine()
This will read a whole line till the system defined line seperator (usually \n)
scanner.next() only reads the next token till space.

What is the difference between .nextLine() and .next()? [duplicate]

This question already has answers here:
Understanding Scanner's nextLine(), next(), and nextInt() methods
(2 answers)
Closed 6 years ago.
I am making a program and am using user input. When I am getting a String I have always used .nextLine(), but I have also used .next() and it does the same thing. What is the difference?
Scanner input = new Scanner(System.in);
String h = input.nextLine();
String n = input.next();
What is the difference?
To make long story short:
nextLine - reads the whole line.
next - reads until the first space.
As an example:
// Input : Barack Obama
String st = in.next(); // st holds the String "Barack"
String st2 = in.nextLine(); //st2 holds the String "Barack Obama"

Why my method being called 3 times after System.in.read() in loop

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.

Issues with input from user [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an input from user of the following form:
1234 abc def gfh
..
8789327 kjwd jwdn
stop
now if i use Scanner and in turn use
Scanner sc=new Scanner(System.in);
String t=sc.nextLine();
while(!t.equals("stop"))
{
int i=sc.nextInt();
int str=sc.nextLine();
t=sc.nextLine();
}
Is there some way by which i may get
i=1234
str="abc def gfh"
...
and so on...and stop when the user enters a stop
I want to accept the numerical values and strings separately...without using regex.
Also I want to stop taking input with keyword "stop".
First of all, you are doing nothing with the accepted input, just ignoring it to take next input.
Second, scanner.nextLine() returns you the next line read which is String. To get the tokens separately, you would need to split the string read to get them.
Third, you should check in your while, whether you have next input or not using scanner#hasNextLine, if its equal to true, then only you should read your input in your while loop.
If you want to read each token separately, you should better use Scanner#next method, which returns the next token read.
Also, you want to read integers and strings, so you also need to test, whether you are having an integer. You would need to use Scanner#hasNextInt method for that.
Ok, since you want to read integer and string separately on each line.
Here's what you can try: -
while (scanner.hasNextLine()) { // Check whether you have nextLine to read
String str = scanner.nextLine(); // Read the nextLine
if (str.equals("stop")) { // If line is "stop" break
break;
}
String[] tokens = str.split(" ", 1); // Split your string with limit 1
// This will give you 2 length array
int firstValue = Integer.parseInt(tokens[0]); // Get 1st integer value
String secondString = tokens[1]; // Get next string after integer value
}
You never change the value of t so the while condition will be always true unless the first line of your file is stop.
your code:
Scanner sc=new Scanner(System.in);
String t=sc.nextLine();
while(!t.equals("stop"))
{
int i=sc.nextInt();
int str=sc.nextLine();
t=sc.nextLine();
}
First of all int str=sc.nextLine(); is wrong as nextLine() returns string. According to me, what you can do is:
Scanner sc=new Scanner(System.in);
String t=sc.nextLine();
int i;
String str="";
while(!t.equals("stop"))
{
int index=t.indexOf(" ");
if(index==-1)
System.out.println("error");
else{
i=Integer.parseInt(t.substring(0,index));
str=t.substring(index+1);
}
t=sc.nextLine();
}
I hope it helps.

Categories

Resources