I'm trying to read the input which is in the following format.
2
asdf
asdf
3
asd
df
2
Following is the code:
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
System.out.println(t);
while(t>0){
String a = scanner.next();
String b = scanner.next();
int K = scanner.nextInt();
}
But when I'm scanning, I'm getting empty t=2 , a="" , b=asdf, K=asdf
Can't figure out the issue. There is no space/new line between 2 and asdf.
I have tried using scanner.nextLine() instead of scanner.next() but no change
nextInt() doesn't cosume the newline token, so the following read will get it. You could introduce a nextLine after the nextInt to skip it:
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
scanner.nextLine(); // Skip the newline character
System.out.println(t);
while(t > 0) {
String a = scanner.next();
String b = scanner.next();
int K = scanner.nextInt();
scanner.nextLine(); // Skip the newline character
}
Another approach I prefer:
Scanner scanner = new Scanner(System.in);
int t = Integer.parseInt(scanner.nextLine());
System.out.println(t);
while(t>0){
String a = scanner.nextLine();
String b = scanner.nextLine();
int K = Integer.parseInt(scanner.nextLine());
}
But note it will throw NumberFormatException when input is incorrect.
Related
I want to understand why using Scanner.nextInt() to read a number and then using Scanner.nextLine() to read a sentence does not work as expected. I have the following code where I input a number but it skips listening to the sentence and my program terminates. Could someone explain why this is and what are alternate solutions?
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanner.nextInt();
System.out.println("Enter a sentence");
System.out.println(x);
String line = scanner.nextLine();
System.out.println(line);
In your code, you have to write scanner.nextLine() after int x = scanner.nextInt();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter a sentence");
System.out.println(x);/*be careful,
here you write the result of x and below you are going to write the sentence.
I think you better write
System.out.println(x);
above
System.out.println("Enter a sentence");*/
String line = scanner.nextLine();
System.out.println(line);
You need a different Scanner instance for String receiving and another for Integer
Scanner scanNumbers = new Scanner(System.in);
Scanner scanString = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanNumbers.nextInt();
System.out.println(x);
System.out.println("Enter a sentence");
String line = scanString.nextLine();
System.out.println(line);
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanner.nextInt();
System.out.println(x);
scanner.nextLine(); // skip the newline character
System.out.println("Enter name");
String name1 = scanner.nextLine();
System.out.println(name1);
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
When I execute the following:
static void Append() {
StringBuilder sb = new StringBuilder();
System.out.print("How many words do you want to append? ");
int n = input.nextInt();
System.out.println("Please type the words you want to append: ");
for (int c = 1; c <= n; c++) {
String str = input.nextLine();
sb.append(str);
System.out.print(" ");
}
System.out.print(sb);
}
Let's say if I put 3, then the computer lets me type only 2 words..
This is the output:
How many words do you want to append? 3
Please type the words you want to append:
I
am
Iam
Also, why is there a space before the words? the print function is after the input function. So shouldn't it be the opposite?
You should replace nextLine() by next().
import java.util.Scanner;
public class Main
{
static void Append() {
Scanner input = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.print("How many words do you want to append? ");
int n = input.nextInt();
System.out.println("Please type the words you want to append: ");
String str = null;
for (int c = 0; c < n; c++) {
str = input.next();
sb.append(str +" " );
}
System.out.print(sb);
}
public static void main(String[] args) {
System.out.println("Hello World");
Append();
}
}
If you debug that program, you can find that the first time of loop will get input.nextLine() with an empty string. This is when the problem occurs.
When you input a 3 and a \n for int n = input.nextInt();, the input buffer contains "3\n", and input.nextInt(); will just take that "3", like the image below:
where the position of input is 1, remaining the "\n" in the buffer. Then when the program required for nextLine(), it will read the buffer until a "\n", which results in reading an empty string.
So a possible workaround is to add a String empty = input.nextLine(); before the loop, or use input.next(); instead of input.nextLine();, since in the document says, input.next(); will return the next token.
Update: Notice that no one answers your second question in the bottom...
You should modify the line System.out.println(" "); in the loop into sb.append(" ");.
I think it is because it read a line changing char into the string
so it consider the changing line as the first and the first string is taken.
you could only have two string to input
If you put code printing line which was read from input as follows:
static void append() {
Scanner input = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.print("How many words do you want to append? ");
int n = input.nextInt();
System.out.println("Please type the words you want to append: ");
for (int c = 1; c <= n; c++) {
String str = input.nextLine();
System.out.println("input str=" + str); //pay attention to this line
sb.append(str);
System.out.print(" ");
}
System.out.print(sb);
}
you will see that first iteration does not read from input. Because there is already \n in buffer which was read with nextInt.
To solve that you can skip line after nextInt as in code bellow (I am not sure that it is best solution):
static void append() {
Scanner input = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.print("How many words do you want to append? ");
int n = input.nextInt();
System.out.println("Please type the words you want to append: ");
if (input.hasNextLine()) input.nextLine();
for (int c = 1; c <= n; c++) {
String str = input.nextLine();
System.out.println("input str=" + str);
sb.append(str);
System.out.print(" ");
}
System.out.print(sb);
}
Using next() is not solution, if you want read sentences as single string.
So I was using this code in my program and whenever I give input consisting of multiple words, the compiler executes the catch block that many times. I've also tried it with different methods & till now all efforts went to vain.
Method 1:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
try
{
size = scanner.nextInt();
break;
}
catch (InputMismatchException e)
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
}
Method 2:
Scanner scanner = new Scanner(System.in);
int size = 0;
boolean bError = true;
while (bError)
{
if (scanner.hasNextInt())
size = scanner.nextInt();
else
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
bError = false;
}
Method 3:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
if (scanner.hasNextInt())
size = scanner.nextInt();
else
{
scanner.next();
System.out.println("Enter valid input (Digit Only)");
continue;
}
String sizeStr = Integer.toString(size);
Pattern pattern = Pattern.compile(new String ("^[0-9]*$"));
Matcher matcher = pattern.matcher(sizeStr);
if(matcher.matches())
{
break;
}
else
{
System.out.println("Enter valid input (Digit Only)");
continue;
}
}
Method 4:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (scanner.hasNext())
{
if (scanner.hasNextInt())
{
size = scanner.nextInt();
System.out.println(size);
break;
}
else
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
}
}
I'm now able to do the task via taking a String input and then parsing it to int. But the initial doubt still remains that why that was not working properly. The code below is working fine.
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
try
{
String sizeStr = scanner.nextLine();
size = Integer.parseInt(sizeStr);
break;
}
catch (NumberFormatException e)
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
}
According to the official Java Doc (https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html):
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next
methods.
The scanner can also use delimiters other than whitespace.
By default, all the next*() functions of scanner class other than nextLine() read the next token, not the next line. This means it reads until it finds a whitespace. If you want to read all the tokens in a line, you need to use nextLine() and then format the input explicitly as you want.
Consider this input:
abcd xyz
When you do scanner.nextInt() or any of scanner.next*() functions other than scanner.nextLine(), only "abcd" is read because it is the next token. When you do scanner.nextLine(), the complete string in the current line "abcd xyz" is read and the scanner advances to the next line.
However, if you want the nextInt() function to read the whole line, then you can set the delimiter to be new line '\n'.
Scanner scan = new Scanner(System.in).useDelimiter("\n");
Using this, you can get the behaviour that you want.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 6 years ago.
In this snippet what I am doing taking three different types of variables and adding them and then printing then down.
public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = "HackerRank ";
Scanner scan = new Scanner(System.in);
int firstVariable = 0;
double secondVariable = 0.0;
String theString = "";
firstVariable = scan.nextInt();
secondVariable = scan.nextDouble();
theString = scan.nextLine();
System.out.println(firstVariable+i);
System.out.println(secondVariable+d);
System.out.println(s+""+theString);
}
I am providing input for firstVariable hitting enter and then providing the input for secondVariable and now as soon as I hit enter theString is capturing that value(I know it should capture it).
EDIT: in this case how should I provide the input to theString without as well as with space ?
I did try something like this,
while(scan.hasNext())
theString = scan.nextLine();
But it didn't work either.
Simply check scan.nextLine() is empty if so call scan.nextLine() again as next:
secondVariable = scan.nextDouble();
theString = scan.nextLine().trim();
if (theString.isEmpty()) {
theString = scan.nextLine();
}
Another approach with a pattern:
firstVariable = scan.nextInt();
secondVariable = scan.nextDouble();
theString = scan.next("\\w+");
There are two ways to solve your problem:
The first one is to use
nextLine()
each time you read from the user like this:
int firstVariable = scan.nextInt();
scan.nextLine();
double secondVariable = scan.nextDouble();
scan.nextLine();
String theString = scan.nextLine();
The second one is to parse the integer and double value from nextLine() like this:
int firstVariable = Integer.parseInt(scan.nextLine());
Double secondVariable = Double.parseDouble(scan.nextLine());
String theString = scan.nextLine();
You need to add an extra scan.nextLine(); before your String theString, to capture the Enter after the double. Like this:
firstVariable = scan.nextInt();
secondVariable = scan.nextDouble();
scan.nextLine();
theString = scan.nextLine();
Just as an advice to reduce your code, there's no need to add these:
int firstVariable = 0;
double secondVariable = 0.0;
String theString = "";
Just add the type to the variables to capture the scan:
int firstVariable = scan.nextInt();
double secondVariable = scan.nextDouble();
scan.nextLine();
String theString = scan.nextLine();
How can I get 2 or more integer values of user with Scanner class then check them; if they all are integer, run some statements and if aren't just show a warning not crash!
I wrote this code but it can't be ok with Java! Of course I know where is the problem from. I only want something like this :
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first value: ");
String v1 = sc.nextLine() ;
System.out.println("Enter the second value: ") ;
String v2 = sc.nextLine() ;
if(v1.hasNextInt() && v2.hasNextInt()){ }
Change your code to:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first value: ");
int v1 = sc.nextInt() ; // could also use hasNextInt() before this line
System.out.println("Enter the second value: ") ;
int v2 = sc.nextInt() ;// could also use hasNextInt() before this line
// you have 2 int values..
org.apache.commons.lang3.StringUtils has some great utility methods for checking strings. In this scenario I would do:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first value: ");
String v1 = sc.nextLine() ;
System.out.println("Enter the second value: ") ;
String v2 = sc.nextLine() ;
if(StringUtils.isNumeric(v1) && StringUtils.isNumeric(v2)){ }
You can use sc.nextInt() for taking input as an integer
However if you want to take input as a string then
just use Integer.parseInt(String value);
This method will take String value as an argument and convert it to Integer.However If the String value can be converted to integer then fine,else this method throws NumberFormatException which you can catch by implementing Exception Handling and avoid your program from crashing.
See various ,methods of Scanner class for taking different type of
input
Scanner in=new Scanner(System.in);
integer = in.nextInt();
longInteger = in.nextLong();
realNumber = in.nextFloat();
doubleReal = in.nextDouble();
string1 = in.nextLine();
You can use .matches("-?\\d+") expression on a String to check whether it's an Integer.
{
int number;
if (v1.matches("-?\\d+"))
number = Integer.parseInt(v1);
else
System.out.println("It's not a number!")
}