This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
The question is that write a class named Seyyed includes a method named seyyed. I should save the name of some people in a String array in main method and calculate how many names begin with "Seyyed". I wrote the following code. But the output is unexpected. The problem is at line 10 where the sentence "Enter a name : " is printed two times at the first time.
import java.util.Scanner;
public class Seyyed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
}
for example When I enter 3 to add 3 names the program 2 times repeats the sentence "Enter a name : " and the output is something like this:
Enter the number of names :3
Enter a name :
Enter a name :
Seyyed Saber
Enter a name :
Ahmad Ali
There are 1 Seyyed
I can enter 2 names while I expect to enter 3 names.
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Right after in.nextInt(); just add in.nextLine(); to consume the extra \n from your input. This should work.
Original answer: https://stackoverflow.com/a/14452649/7621786
When you enter the number, you also press the Enter key, which does an "\n" input value, which is captured by your first nextLine() method.
To prevent that, you should insert an nextLine() in your code to consume the "\n" character after you read the int value.
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
Good answer for the same issue: https://stackoverflow.com/a/7056782/4983264
nextInt() will consume all the characters of the integer but will not touch the end of line character. So when you say nextLine() for the first time in the loop it will read the eol left from the previous scanInt(), so basically reading an empty string. To fix that use a nextLine() before the loop to clear the scanner or use a different scanner for Strings and int.
Try this one:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
Related
How do I print the selected name in the array? I want to print the names i entered in the array and print it alone but when I try to run the code it says:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
here is my code:
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
//Getting the names using for loop.
for(int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
for(int i = 0; i <numOfLoop; i++) {
if(name[i] == name[num]) {
System.out.println(name[i]);
}
}
Input:
6 //How many loop and size of array I want.
john
mark
kevin
tesia
arthur
cody
5 //what ever is in array[5] will be printed.
Expected output: cody
I also encountered this problem before, it seems that when you change from nextInt() the scanner instance did not read the \n character before it goes forward to nextLine().
Just adding in.nextLine(); before the For-loop should fix the problem.
Your error comes from the fact that the first entry in the array gets set as an empty string and the last name you put in gets read where you normally would put the second number, thus the nextInt() throws an error since it gets a String and not an int.
There are several typical flaws in the code snippet to be addressed:
InputMismatchException - because not all new lines are consumed properly after calling to nextInt
name[i] == name[num] -- invalid String comparison, should be name[i].equals(name[num])
Missing check num < numOfLoop -- without that, ArrayOutOfBoundsException is possible
The fixed code would look as follows:
Scanner in = new Scanner(System.in);
System.out.println("Input the number of names: ");
int numOfLoop = in.nextInt(); //number of loops I want.
in.nextLine(); // skip remaining line
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
System.out.println("Input the names, one per line: ");
//Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
System.out.println("Input the index of the name to print: ");
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
if (num >= 0 && num < numOfLoop) {
System.out.println("Looking for name: " + name[num]);
for (int i = 0; i <numOfLoop; i++) {
if(name[i].equals(name[num])) {
System.out.println(name[i] + " at index=" + i);
}
}
} else {
System.out.println("Invalid index, cannot be greater or equal to " + numOfLoop);
}
Sample output:
Input the number of names:
5
Input the names, one per line:
john
jeff
joan
john
jake
Input the index of the name to print:
0
Looking for name: john
john at index=0
john at index=3
You do not need the second loop.
All you need to do is to check if (num >= 0 && num < numOfLoop) and display the value of name[num] or an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numOfLoop = Integer.parseInt(in.nextLine()); // number of loops I want.
String[] name = new String[numOfLoop]; // size of the array is depend on how many loop I want.
// Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = Integer.parseInt(in.nextLine()); // The name I want to print depend on what number I enter here.
if (num >= 0 && num < numOfLoop) {
System.out.println(name[num]);
} else {
System.out.println("Invalid index.");
}
}
}
Also, use Integer.parseInt(in.nextLine()) instead of in.nextInt() for the reason mentioned at Scanner is skipping nextLine() after using next() or nextFoo()?
A sample run:
5
Johny
Arvind
Kumar
Avinash
Stackoverflow
3
Avinash
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
for (int i=0; i<name.length; i++){
String names = in.next();
name[i] = names;
}
System.out.println("The names array: " + Arrays.toString(name));
for(int index=0;index<name.length;index++) {
System.out.print("Enter an index you want to print: ");
index = in.nextInt();
System.out.println("index " + index + " is: " + name[index-1]);
}
I am a beginner to java. I try to write a program to read a series of words from the command-line arguments, and find the index of the first match of a given word. Like user can enter "I love apple", and the given word is "apple". The program will display "The index of the first match of ‘apple’ is 2".
What I did so far does not work. Is it my way of storing the input into the string array not correct?
import java.util.Scanner;
public class test {
public static void main(String [] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int num=1;
String sentence[]=new String[num];
for(int i=0; i< num; i++) {
sentence[i] = input; // store the user input into the array.
num = num+1;
}
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for(int j=0; j<num; j++) {
while (sentence[j].equals(key)) {
System.out.println("The index of the first match of "+key+" is "+j);
}
}
}
}
String array is not required in your solution.
Try this :-
System.out.println("enter sentence ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("enter the given word to fin the index ");
sc = new Scanner(System.in);
String toBeMatched = sc.nextLine();
if (input.contains(toBeMatched)) {
System.out.println("index is " + input.indexOf(toBeMatched));
} else {
System.out.println("doesn't contain string");
}
I have made the following changes to make your code work. Note you were storing the input string incorrectly. In your code, the entire code was being stored as the first index in the array. You don't need the first for-loop as we can use the function .split() to distinguish each word into a different index in the array. Rest of the code stays as it is.
public class ConfigTest {
public static void main(String[] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// Use this to split the input into different indexes of the array
String[] sentence = input.split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].equals(key)) {
System.out.println("The index of the first match of " + key + " is " + i);
}
}
}
}
I think you have a scope problem. sentence[] is declared and instantiated in your first forloop. Try moving the declaration outside of the loop and you should do away with the error.
I also noticed a couple of errors. You could try this
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Enter Sentence");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String sentence[] = input.split("\\s");
System.out.println("Enter Word");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
int index = 0;
for(String word : sentence)
{
if(word.equals(key))
{
System.out.println("The index of the first match of " + key + " is " + index);
break;
}
index++;
}
}
Turtle
sentence variable is only defined inside the for loop, it needs to be declared outside it
You can use the first Scanner (sc) declared variable again instead of declaring another one (sc2)
sentence[i] = input -- will mean -- sentence[0] = "I love apple"
Scanner variable can do all the work for you for the input into the array instead of a for loop
String[] a = sc. nextLine(). split(" ");
This will scan an input of new line and separate each string separated by a space into each array.
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String[] sentence = sc. nextLine(). split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
String key = sc.nextLine();
for(int j=0; j<num; j++) {
if (sentence[j].matches(key)) {
System.out.println("The index of the first match of "+ key +" is "+ j);
}
}
Declare the String [] sentence outside the for loop. It is not visible outside the first for block.
The sentence array is created over and over again during the iteration of the for loop. The loop is not required to get the String from the command line.
Edited my answer and removed the use of any for loops, Arrays.asList() will take the words array and fetch the index of the word from the resulting List.
public static void main(String[] args) throws IOException {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("Enter the given word to find the index of its first match: ");
Scanner wordInput = new Scanner(System.in);
String key = wordInput.next();
String[] words = input.split(" ");
int occurence = Arrays.asList(words).indexOf(key);
if(occurence != -1){
System.out.println(String.format("Index of first occurence of the word is %d", occurence));
}
}
You just need to declare sentence array outside the for loop, as for now, the issue is of scope.For more on the scope of a variable in java . Also, this is not you intend to do, you intended to take input as a command line.
So, the input which you will get will come in String[] args. For more on command line arguments check here.
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.
I want to read multiple words into a string called input. The words can be casted into numeric values like "1 14 5 9 13". After the user input, the string will be converted into a string array separated by spaces.
public class ArraySum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.next());
System.out.println("Please enter "+n+" numbers");
String input = scanner.next(); // ERROR: only the first word is read
String[] inputs = input.split("\\s+");
int sum=0;
for (int i =0; i<inputs.length; i++){
if (!inputs[i].equals(""))
sum+= Long.parseLong(inputs[i]);
}
System.out.print(sum);
}
}
However only the first word is read into the string.
This answer suggests using nextLine() to read a multi-word string, but if I change it, an error was thrown.
java.lang.NumberFormatException: null
Apparently an empty/null string was inputted before I entered any word.
You have to use nextLine after nextInt to clear your Scanner like this :
int n = scanner.nextInt();//read your int
scanner.nextLine();//clear your Scanner
System.out.println("Please enter " + n + " numbers");
String input = scanner.nextLine();//read your String example 12 55 66
I need to solve a problem when take an input of integer which are the number of lines the user wants to input just next to this input(some sentences) as understandable from text as follows:
The first line of input contains a single integer N, indicating the
number of lines in the input. This is followed by N lines of input
text.
I wrote the following code:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String lines[] = new String[n];
for(int i = 0; i < n; i++){
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
}
And an interaction with the program:
5(The user inputted 5)
Enter 0th line(Program outputted this)
Enter 1th line(Doesn't gave time to input and instantly printed this message)
Hello(Gave time to write some input)
Enter 2th line(Program outputted this)
How(User input)
Enter 3th line(Program outputted this)
Are(User input)
Enter 4th line(Program outputted this)
You(User input)
What's the problem? I can't input 0th line.
Suggest a better method to input n numbers of lines where n is user provided to a string array.
The call to nextInt() is leaving the newline for the 0th call to nextLine() to consume.
Another way to do it would be to consistently use nextLine() and parse the number of lines out of the input string.
Start paying attention to style and code formatting. It promotes readability and understanding.
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
String lines[] = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
I don't know what you would consider better:
Try changing
System.out.println("Enter " + i + "th line");
to
System.out.print("Enter " + i + "th line:");
Makes it look better.
A better way of inputting lines would be to keep reading input lines until you see a special termination char.
Use an ArrayList to store the lines then you don't need to declare the size beforehand