Take a char input from the Scanner - java

I am trying to find a way to take a char input from the keyboard.
I tried using:
Scanner reader = new Scanner(System.in);
char c = reader.nextChar();
This method doesn't exist.
I tried taking c as a String. Yet, it would not always work in every case, since the other method I am calling from my method requires a char as an input. Therefore I have to find a way to explicitly take a char as an input.
Any help?

You could take the first character from Scanner.next:
char c = reader.next().charAt(0);
To consume exactly one character you could use:
char c = reader.findInLine(".").charAt(0);
To consume strictly one character you could use:
char c = reader.next(".").charAt(0);

Setup scanner:
reader.useDelimiter("");
After this reader.next() will return a single-character string.

There is no API method to get a character from the Scanner. You should get the String using scanner.next() and invoke String.charAt(0) method on the returned String.
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
Just to be safe with whitespaces you could also first call trim() on the string to remove any whitespaces.
Scanner reader = new Scanner(System.in);
char c = reader.next().trim().charAt(0);

There are three ways to approach this problem:
Call next() on the Scanner, and extract the first character of the String (e.g. charAt(0)) If you want to read the rest of the line as characters, iterate over the remaining characters in the String. Other answers have this code.
Use setDelimiter("") to set the delimiter to an empty string. This will cause next() to tokenize into strings that are exactly one character long. So then you can repeatedly call next().charAt(0) to iterate the characters. You can then set the delimiter to its original value and resume scanning in the normal way!
Use the Reader API instead of the Scanner API. The Reader.read() method delivers a single character read from the input stream. For example:
Reader reader = new InputStreamReader(System.in);
int ch = reader.read();
if (ch != -1) { // check for EOF
// we have a character ...
}
When you read from the console via System.in, the input is typically buffered by the operating system, and only "released" to the application when the user types ENTER. So if you intend your application to respond to individual keyboard strokes, this is not going to work. You would need to do some OS-specific native code stuff to turn off or work around line-buffering for console at the OS level.
Reference:
How to read a single char from the console in Java (as the user types it)?

You can solve this problem, of "grabbing keyboard input one char at a time" very simply. Without having to use a Scanner all and also not clearing the input buffer as a side effect, by using this.
char c = (char)System.in.read();
If all you need is the same functionality as the C language "getChar()" function then this will work great. The Big advantage of the "System.in.read()" is the buffer is not cleared out after each char your grab. So if you still need all the users input you can still get the rest of it from the input buffer. The "char c = scanner.next().charAt(0);" way does grab the char but will clear the buffer.
// Java program to read character without using Scanner
public class Main
{
public static void main(String[] args)
{
try {
String input = "";
// Grab the First char, also wait for user input if the buffer is empty.
// Think of it as working just like getChar() does in C.
char c = (char)System.in.read();
while(c != '\n') {
//<do your magic you need to do with the char here>
input += c; // <my simple magic>
//then grab the next char
c = (char)System.in.read();
}
//print back out all the users input
System.out.println(input);
} catch (Exception e){
System.out.println(e);
}
}
}
Hope this helpful, and good luck! P.S. Sorry i know this is an older post, but i hope that my answer bring new insight and could might help other people who also have this problem.

This actually doesn't work:
char c = reader.next().charAt(0);
There are some good explanations and references in this question:
Why doesn't the Scanner class have a nextChar method?
"A Scanner breaks its input into tokens using a delimiter pattern", which is pretty open ended. For example when using this
c = lineScanner.next().charAt(0);
for this line of input
"(1 + 9) / (3 - 1) + 6 - 2"
the call to next returns "(1", c will be set to '(', and you'll end up losing the '1' on the next call to next()
Typically when you want to get a character you would like to ignore whitespace. This worked for me:
c = lineScanner.findInLine("[^\\s]").charAt(0);
Reference:
regex to match a single character that is anything but a space

The best way to take input of a character in Scanner class is:
Scanner sca=new Scanner(System.in);
System.out.println("enter a character");
char ch=sca.next().charAt(0);

You should use your custom input reader for faster results instead of extracting first character from reading String.
Link for Custom ScanReader and explanation: https://gist.github.com/nik1010/5a90fa43399c539bb817069a14c3c5a8
Code for scanning Char :
BufferedInputStream br=new BufferedInputStream(System.in);
char a= (char)br.read();

There are two approaches, you can either take exactly one character or strictly one character.
When you use exactly, the reader will take only the first character, irrespective of how many characters you input.
For example:
import java.util.Scanner;
public class ReaderExample {
public static void main(String[] args) {
try {
Scanner reader = new Scanner(System.in);
char c = reader.findInLine(".").charAt(0);
reader.close();
System.out.print(c);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
When you give a set of characters as input, say "abcd", the reader will consider only the first character i.e., the letter 'a'
But when you use strictly, the input should be just one character. If the input is more than one character, then the reader will not take the input
import java.util.Scanner;
public class ReaderExample {
public static void main(String[] args) {
try {
Scanner reader = new Scanner(System.in);
char c = reader.next(".").charAt(0);
reader.close();
System.out.print(c);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Suppose you give input "abcd", no input is taken, and the variable c will have Null value.

import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
char c = reader.next(".").charAt(0);
}
}
To get only one character char c = reader.next(".").charAt(0);

import java.util.Scanner;
public class userInput{
public static void main(String[] args){
// Creating your scanner with name kb as for keyBoard
Scanner kb = new Scanner(System.in);
String name;
int age;
char bloodGroup;
float height;
// Accepting Inputs from user
System.out.println("Enter Your Name");
name = kb.nextLine(); // for entire line of String including spaces
System.out.println("Enter Your Age");
age = kb.nextInt(); // for taking Int
System.out.println("Enter Your BloodGroup : A/B/O only");
bloodGroup = kb.next().charAt(0); // For character at position 0
System.out.println("Enter Your Height in Meters");
height = kb.nextFloat(); // for taking Float value
// closing your scanner object
kb.close();
// Outputting All
System.out.println("Name : " +name);
System.out.println("Age : " +age);
System.out.println("BloodGroup : " +bloodGroup);
System.out.println("Height : " +height+" m");
}
}

Try this:
char c=S.nextLine().charAt(0);

// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}

You should get the String using scanner.next() and invoke String.charAt(0) method on the returned String.
Exmple :
import java.util.Scanner;
public class InputC{
public static void main(String[] args) {
// TODO Auto-generated method stub
// Declare the object and initialize with
// predefined standard input object
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a character: ");
// Character input
char c = scanner.next().charAt(0);
// Print the read value
System.out.println("You have entered: "+c);
}
}
output
Enter a character:
a
You have entered: a

you just need to write this for getting value in char type.
char c = reader.next().charAt(0);

try followings.
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
this will get a character from the keyboard.

import java.io.*;
class abc // enter class name (here abc is class name)
{
public static void main(String arg[])
throws IOException // can also use Exception
{
BufferedReader z =
new BufferedReader(new InputStreamReader(System.in));
char ch = (char) z.read();
} // PSVM
} // class

Try this
Scanner scanner=new Scanner(System.in);
String s=scanner.next();
char c=s.charAt(0);

Scanner key = new Scanner(System.in);
//shortcut way
char firstChar=key.next().charAt(0);
//how it works;
/*key.next() takes a String as input then,
charAt method is applied on that input (String)
with a parameter of type int (position) that you give to get
that char at that position.
You can simply read it out as:
the char at position/index 0 from the input String
(through the Scanner object key) is stored in var. firstChar (type char) */
//you can also do it in a bit elabortive manner to understand how it exactly works
String input=key.next(); // you can also write key.nextLine to take a String with spaces also
char firstChar=input.charAt(0);
char charAtAnyPos= input.charAt(pos); // in pos you enter that index from where you want to get the char from
By the way, you can't take a char directly as an input. As you can see above, a String is first taken then the charAt(0); is found and stored

Simple solution to read a charachter from user input.
Read a String. Then use charAt(0) over String
Scanner reader = new Scanner(System.in);
String str = reader.next();
char c = str.charAt(0);
That's it.

You could use typecasting:
Scanner sc= new Scanner(System.in);
char a=(char) sc.next();
This way you will take input in String due to the function 'next()' but then it will be converted into character due to the 'char' mentioned in the brackets.
This method of conversion of data type by mentioning the destination data type in brackets is called typecating. It works for me, I hope it works for u :)

Just use...
Scanner keyboard = new Scanner(System.in);
char c = keyboard.next().charAt(0);
This gets the first character of the next input.

To find the index of a character in a given sting, you can use this code:
package stringmethodindexof;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
* #author ASUS//VERY VERY IMPORTANT
*/
public class StringMethodIndexOf {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String email;
String any;
//char any;
//any=JOptionPane.showInputDialog(null,"Enter any character or string to find out its INDEX NUMBER").charAt(0);
//THE AVOBE LINE IS FOR CHARACTER INPUT LOL
//System.out.println("Enter any character or string to find out its INDEX NUMBER");
//Scanner r=new Scanner(System.in);
// any=r.nextChar();
email = JOptionPane.showInputDialog(null,"Enter any string or anything you want:");
any=JOptionPane.showInputDialog(null,"Enter any character or string to find out its INDEX NUMBER");
int result;
result=email.indexOf(any);
JOptionPane.showMessageDialog(null, result);
}
}

The easiest way is, first change the variable to a String and accept the input as a string. Then you can control based on the input variable with an if-else or switch statement as follows.
Scanner reader = new Scanner(System.in);
String c = reader.nextLine();
switch (c) {
case "a":
<your code here>
break;
case "b":
<your code here>
break;
default:
<your code here>
}

Related

Char variable comparison issue in java [duplicate]

I am trying to find a way to take a char input from the keyboard.
I tried using:
Scanner reader = new Scanner(System.in);
char c = reader.nextChar();
This method doesn't exist.
I tried taking c as a String. Yet, it would not always work in every case, since the other method I am calling from my method requires a char as an input. Therefore I have to find a way to explicitly take a char as an input.
Any help?
You could take the first character from Scanner.next:
char c = reader.next().charAt(0);
To consume exactly one character you could use:
char c = reader.findInLine(".").charAt(0);
To consume strictly one character you could use:
char c = reader.next(".").charAt(0);
Setup scanner:
reader.useDelimiter("");
After this reader.next() will return a single-character string.
There is no API method to get a character from the Scanner. You should get the String using scanner.next() and invoke String.charAt(0) method on the returned String.
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
Just to be safe with whitespaces you could also first call trim() on the string to remove any whitespaces.
Scanner reader = new Scanner(System.in);
char c = reader.next().trim().charAt(0);
There are three ways to approach this problem:
Call next() on the Scanner, and extract the first character of the String (e.g. charAt(0)) If you want to read the rest of the line as characters, iterate over the remaining characters in the String. Other answers have this code.
Use setDelimiter("") to set the delimiter to an empty string. This will cause next() to tokenize into strings that are exactly one character long. So then you can repeatedly call next().charAt(0) to iterate the characters. You can then set the delimiter to its original value and resume scanning in the normal way!
Use the Reader API instead of the Scanner API. The Reader.read() method delivers a single character read from the input stream. For example:
Reader reader = new InputStreamReader(System.in);
int ch = reader.read();
if (ch != -1) { // check for EOF
// we have a character ...
}
When you read from the console via System.in, the input is typically buffered by the operating system, and only "released" to the application when the user types ENTER. So if you intend your application to respond to individual keyboard strokes, this is not going to work. You would need to do some OS-specific native code stuff to turn off or work around line-buffering for console at the OS level.
Reference:
How to read a single char from the console in Java (as the user types it)?
You can solve this problem, of "grabbing keyboard input one char at a time" very simply. Without having to use a Scanner all and also not clearing the input buffer as a side effect, by using this.
char c = (char)System.in.read();
If all you need is the same functionality as the C language "getChar()" function then this will work great. The Big advantage of the "System.in.read()" is the buffer is not cleared out after each char your grab. So if you still need all the users input you can still get the rest of it from the input buffer. The "char c = scanner.next().charAt(0);" way does grab the char but will clear the buffer.
// Java program to read character without using Scanner
public class Main
{
public static void main(String[] args)
{
try {
String input = "";
// Grab the First char, also wait for user input if the buffer is empty.
// Think of it as working just like getChar() does in C.
char c = (char)System.in.read();
while(c != '\n') {
//<do your magic you need to do with the char here>
input += c; // <my simple magic>
//then grab the next char
c = (char)System.in.read();
}
//print back out all the users input
System.out.println(input);
} catch (Exception e){
System.out.println(e);
}
}
}
Hope this helpful, and good luck! P.S. Sorry i know this is an older post, but i hope that my answer bring new insight and could might help other people who also have this problem.
This actually doesn't work:
char c = reader.next().charAt(0);
There are some good explanations and references in this question:
Why doesn't the Scanner class have a nextChar method?
"A Scanner breaks its input into tokens using a delimiter pattern", which is pretty open ended. For example when using this
c = lineScanner.next().charAt(0);
for this line of input
"(1 + 9) / (3 - 1) + 6 - 2"
the call to next returns "(1", c will be set to '(', and you'll end up losing the '1' on the next call to next()
Typically when you want to get a character you would like to ignore whitespace. This worked for me:
c = lineScanner.findInLine("[^\\s]").charAt(0);
Reference:
regex to match a single character that is anything but a space
The best way to take input of a character in Scanner class is:
Scanner sca=new Scanner(System.in);
System.out.println("enter a character");
char ch=sca.next().charAt(0);
You should use your custom input reader for faster results instead of extracting first character from reading String.
Link for Custom ScanReader and explanation: https://gist.github.com/nik1010/5a90fa43399c539bb817069a14c3c5a8
Code for scanning Char :
BufferedInputStream br=new BufferedInputStream(System.in);
char a= (char)br.read();
There are two approaches, you can either take exactly one character or strictly one character.
When you use exactly, the reader will take only the first character, irrespective of how many characters you input.
For example:
import java.util.Scanner;
public class ReaderExample {
public static void main(String[] args) {
try {
Scanner reader = new Scanner(System.in);
char c = reader.findInLine(".").charAt(0);
reader.close();
System.out.print(c);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
When you give a set of characters as input, say "abcd", the reader will consider only the first character i.e., the letter 'a'
But when you use strictly, the input should be just one character. If the input is more than one character, then the reader will not take the input
import java.util.Scanner;
public class ReaderExample {
public static void main(String[] args) {
try {
Scanner reader = new Scanner(System.in);
char c = reader.next(".").charAt(0);
reader.close();
System.out.print(c);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Suppose you give input "abcd", no input is taken, and the variable c will have Null value.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
char c = reader.next(".").charAt(0);
}
}
To get only one character char c = reader.next(".").charAt(0);
import java.util.Scanner;
public class userInput{
public static void main(String[] args){
// Creating your scanner with name kb as for keyBoard
Scanner kb = new Scanner(System.in);
String name;
int age;
char bloodGroup;
float height;
// Accepting Inputs from user
System.out.println("Enter Your Name");
name = kb.nextLine(); // for entire line of String including spaces
System.out.println("Enter Your Age");
age = kb.nextInt(); // for taking Int
System.out.println("Enter Your BloodGroup : A/B/O only");
bloodGroup = kb.next().charAt(0); // For character at position 0
System.out.println("Enter Your Height in Meters");
height = kb.nextFloat(); // for taking Float value
// closing your scanner object
kb.close();
// Outputting All
System.out.println("Name : " +name);
System.out.println("Age : " +age);
System.out.println("BloodGroup : " +bloodGroup);
System.out.println("Height : " +height+" m");
}
}
Try this:
char c=S.nextLine().charAt(0);
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
You should get the String using scanner.next() and invoke String.charAt(0) method on the returned String.
Exmple :
import java.util.Scanner;
public class InputC{
public static void main(String[] args) {
// TODO Auto-generated method stub
// Declare the object and initialize with
// predefined standard input object
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a character: ");
// Character input
char c = scanner.next().charAt(0);
// Print the read value
System.out.println("You have entered: "+c);
}
}
output
Enter a character:
a
You have entered: a
you just need to write this for getting value in char type.
char c = reader.next().charAt(0);
try followings.
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
this will get a character from the keyboard.
import java.io.*;
class abc // enter class name (here abc is class name)
{
public static void main(String arg[])
throws IOException // can also use Exception
{
BufferedReader z =
new BufferedReader(new InputStreamReader(System.in));
char ch = (char) z.read();
} // PSVM
} // class
Try this
Scanner scanner=new Scanner(System.in);
String s=scanner.next();
char c=s.charAt(0);
Scanner key = new Scanner(System.in);
//shortcut way
char firstChar=key.next().charAt(0);
//how it works;
/*key.next() takes a String as input then,
charAt method is applied on that input (String)
with a parameter of type int (position) that you give to get
that char at that position.
You can simply read it out as:
the char at position/index 0 from the input String
(through the Scanner object key) is stored in var. firstChar (type char) */
//you can also do it in a bit elabortive manner to understand how it exactly works
String input=key.next(); // you can also write key.nextLine to take a String with spaces also
char firstChar=input.charAt(0);
char charAtAnyPos= input.charAt(pos); // in pos you enter that index from where you want to get the char from
By the way, you can't take a char directly as an input. As you can see above, a String is first taken then the charAt(0); is found and stored
Simple solution to read a charachter from user input.
Read a String. Then use charAt(0) over String
Scanner reader = new Scanner(System.in);
String str = reader.next();
char c = str.charAt(0);
That's it.
You could use typecasting:
Scanner sc= new Scanner(System.in);
char a=(char) sc.next();
This way you will take input in String due to the function 'next()' but then it will be converted into character due to the 'char' mentioned in the brackets.
This method of conversion of data type by mentioning the destination data type in brackets is called typecating. It works for me, I hope it works for u :)
Just use...
Scanner keyboard = new Scanner(System.in);
char c = keyboard.next().charAt(0);
This gets the first character of the next input.
To find the index of a character in a given sting, you can use this code:
package stringmethodindexof;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
* #author ASUS//VERY VERY IMPORTANT
*/
public class StringMethodIndexOf {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String email;
String any;
//char any;
//any=JOptionPane.showInputDialog(null,"Enter any character or string to find out its INDEX NUMBER").charAt(0);
//THE AVOBE LINE IS FOR CHARACTER INPUT LOL
//System.out.println("Enter any character or string to find out its INDEX NUMBER");
//Scanner r=new Scanner(System.in);
// any=r.nextChar();
email = JOptionPane.showInputDialog(null,"Enter any string or anything you want:");
any=JOptionPane.showInputDialog(null,"Enter any character or string to find out its INDEX NUMBER");
int result;
result=email.indexOf(any);
JOptionPane.showMessageDialog(null, result);
}
}
The easiest way is, first change the variable to a String and accept the input as a string. Then you can control based on the input variable with an if-else or switch statement as follows.
Scanner reader = new Scanner(System.in);
String c = reader.nextLine();
switch (c) {
case "a":
<your code here>
break;
case "b":
<your code here>
break;
default:
<your code here>
}

Is there an equivalent of while(scanf()==1) in java?

I have been using the following code in c and c++ for looping till user feeds the correct value till the program comes out of it:
while((scanf("%d",&num)==1)//same way in for loop
{
//some code
}
Can i some how use the same way to accept and loop the program till i keep entering let's say an integer and floating or a char or a special character breaks it.
Use :
Scanner sc = new Scanner(System.in); // OR replace System.in with file to read
while(sc.hasNext()){
//code here
int x = sc.nextInt();
//...
}
There are different variants of hasNext() for specific expected input types: hasNextFloat(), hasNextInt()..
Same goes for next() method so you can find nextInt(), nextFloat() or even nextLine()
You can go to Java doc for more info.
As proposed in comments, you can use the Scanner class.
Note you need to read the in buffer with a nextLine() when it is not an int.
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Enter an int: ");
while (!in.hasNextInt()) {
System.out.println("That's not an int! try again...");
in.nextLine();
}
int myInt = in.nextInt();
System.out.println("You entered "+myInt);
}
}

How can I have a user search a character array for a letter?

gets a single letter from the user. This method validates that it’s either a valid letter or the quit character, ‘!’. It'll eventually keep asking for characters, then once the user is done, they'll type ‘!’ to make the loop end and move on to printing their list of chars
public static String isValidLetter(){
char[] charArray;
charArray = new char[11];
charArray[0] ='C';
charArray[1] ='E';
charArray[2] ='F';
charArray[3] ='H';
charArray[4] ='I';
charArray[5] ='J';
charArray[6] ='L';
charArray[7] ='O';
charArray[8] ='P';
charArray[9] ='S';
charArray[10] ='T';
charArray[11] ='U';
String input;
char letter;
Scanner kb = new Scanner(System.in);
System.out.println("Enter a single character: ");
input=kb.nextLine();
letter = input.charAt(0);
Reading the strings from console.. type "a", enter, "b", enter, "!", enter
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scann = new Scanner(System.in);
List<String> letterWords = new LinkedList<String>();
String str = null;
while (!"!".equals(str)) {
str = scann.next();
letterWords.add(str);
}
for (String word : letterWords) {
System.out.println(word);
}
scann.close();
}
}
If you just want to have a "collection" of valid characters, then you also could use a String instead of an array. It would be much easier to search in it and it avoids errors like in your example (you've initialized your array with size of 11, but you're inserting 12 elements):
public static boolean isValidLetter(final char character) {
final String validCharacters = "CEFHIJLOPSTU";
return validCharacters.contains(String.valueOf(character));
}
This method expects a single char and returns true if it is valid, false otherwise. Please mind, that this check is case sensitive.
You could use that method like this:
final Scanner scan = new Scanner(System.in);
String input;
while (!(input = scan.nextLine()).equals("!")) {
if (!input.isEmpty() && isValidLetter(input.charAt(0))) {
// ... store valid input
System.out.println("valid");
}
}
This loop requests user input until he enters !. I've omitted the storing part. It is up to you to do this last part.
Modify your isValidLetter method to return boolean.
Modify your isValidLetter method to get a char as a parameter.
In isValidLetter, try to find a letter by using a helper function, something like:
static boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
Somewhere in your code where you need the input (or in main for testing), ask for user input (as you already did in isValidLetter). Perform a loop, asking for input, until it is right, or until it is your ending character.
I am not posting the complete solution code on purpose, as it is better for you to play with the code and learn. I only gave directions on how to try; of course it is not the only way, but it fits with what you've already started.

Counting carriage return, Java

I am trying to count carriage return occurrences within string input. I tried both Scanner and BufferedReader. With Scanner, nextLine() does not pick up Carriage Returns. next() with Scanner looks for tokens, such as a space in input, and token splits up the input. I want the entire input to be read as single input. This probably means I cannot use Scanner.
With BufferedReader, readLine() reads up to a Carriage Return, but does not return a Carriage Return in input. If I use "reader.read();" then it tells me that the variable user_input HAS to be int. user_input is supposed to be a string input that MAY have an integer, but it also may not. The only thing is that program would continue until input contains "/done". I would appreciate it if somebody would simply point me in the right direction!
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String user_input = "";
System.out.println("Enter a string: ");
while (!user_input.contains("/done")) {
user_input = reader.readLine(); //cannot be readLine because it only reads up to a carriage return; it does NOT return carriage return
//*Sadly, if I use "reader.read();" then it tells me that user_input HAS to be int. user_input is a string input
String input = user_input;
char[] c = input.toCharArray();
int[] f = new int[114];
System.out.println("Rest of program, I convert input to ascii decimal and report the occurences of each char that was used");
}
catch (IOException e) {
e.printStackTrace();
}
}
Is this what you're looking for?
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\\z"); //"\\z" means end of input
String input = scanner.next();
EDIT: If you want the "\n" to show as "CR", just do this:
input.replaceAll("\\n", "CR");
There's a library called StringUtils that can do this very easily. It has a method named countMatches. Here's how you can use it. But first, you should combine your input into one string:
package com.sandbox;
import org.apache.commons.lang.StringUtils;
public class Sandbox2 {
public static void main(String[] args) {
String allInput = "this\nis\na\n\nfew\nlines\nasdf";
System.out.println(StringUtils.countMatches(allInput, "\n"));
}
}
This outputs "6".
Read characters one by one until EOF is encountered using read() method.
JAVA DOCS
read() in java reads any character(even \n, \r or \r\n). Thus read character one by one and check whether the character read in "Carriage return" or not.
If yes, then increase the counter.

Reading a single char in Java

How can a char be entered in Java from keyboard?
You can either scan an entire line:
Scanner s = new Scanner(System.in);
String str = s.nextLine();
Or you can read a single char, given you know what encoding you're dealing with:
char c = (char) System.in.read();
You can use Scanner like so:
Scanner s= new Scanner(System.in);
char x = s.next().charAt(0);
By using the charAt function you are able to get the value of the first char without using external casting.
Using nextline and System.in.read as often proposed requires the user to hit enter after typing a character. However, people searching for an answer to this question, may also be interested in directly respond to a key press in a console!
I found a solution to do so using jline3, wherein we first change the terminal into rawmode to directly respond to keys, and then wait for the next entered character:
var terminal = TerminalBuilder.terminal()
terminal.enterRawMode()
var reader = terminal.reader()
var c = reader.read()
<dependency>
<groupId>org.jline</groupId>
<artifactId>jline</artifactId>
<version>3.12.3</version>
</dependency>
You can use a Scanner for this. It's not clear what your exact requirements are, but here's an example that should be illustrative:
Scanner sc = new Scanner(System.in).useDelimiter("\\s*");
while (!sc.hasNext("z")) {
char ch = sc.next().charAt(0);
System.out.print("[" + ch + "] ");
}
If you give this input:
123 a b c x y z
The output is:
[1] [2] [3] [a] [b] [c] [x] [y]
So what happens here is that the Scanner uses \s* as delimiter, which is the regex for "zero or more whitespace characters". This skips spaces etc in the input, so you only get non-whitespace characters, one at a time.
i found this way worked nice:
{
char [] a;
String temp;
Scanner keyboard = new Scanner(System.in);
System.out.println("please give the first integer :");
temp=keyboard.next();
a=temp.toCharArray();
}
you can also get individual one with String.charAt()
Here is a class 'getJ' with a static function 'chr()'. This function reads one char.
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class getJ {
static char chr()throws IOException{
BufferedReader bufferReader =new BufferedReader(new InputStreamReader(System.in));
return bufferReader.readLine().charAt(0);
}
}
In order to read a char use this:
anyFunc()throws IOException{
...
...
char c=getJ.chr();
}
Because of 'chr()' is static, you don't have to create 'getJ' by 'new' ; I mean
you don't need to do:
getJ ob = new getJ;
c=ob.chr();
You should remember to add 'throws IOException' to the function's head. If it's impossible, use try / catch as follows:
anyFunc(){// if it's impossible to add 'throws IOException' here
...
try
{
char c=getJ.chr(); //reads a char into c
}
catch(IOException e)
{
System.out.println("IOException has been caught");
}
Credit to:
tutorialspoint.com
See also: geeksforgeeks.
java bufferedreader input getchar char
....
char ch;
...
ch=scan.next().charAt(0);
.
.
It's the easy way to get character.
Maybe you could try this code:
import java.io.*;
public class Test
{
public static void main(String[] args)
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String userInput = in.readLine();
System.out.println("\n\nUser entered -> " + userInput);
}
catch(IOException e)
{
System.out.println("IOException has been caught");
}
}
}

Categories