This question already has answers here:
Using scanner.nextLine() [duplicate]
(5 answers)
Closed 8 years ago.
My program is supposed to count the number of occurrences a user inputted character appears in a string. For some reason, my program does not execute the for loop. Right after it prints out "Enter the string to search: ", it doesn't let me input a string and prints out: "There are 0 occurrences of '(inputted character)' in '(inputted string)'." on a new line. I need it to be able to find the occurrences of the character over any given amount of words inputted as the string. What can I do to make it function properly? Thanks.
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a character for which to search: ");
char ch = input.next().charAt(0);
System.out.println("Enter the string to search: ");
String str = input.nextLine();
int counter = 0;
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i)) {
counter++;
}
}
System.out.printf("There are %d occurrences of '%s' in '%s'.", counter, ch, str);
System.out.println();
}
}
What happens is that the next() method doesn't consume the new-line character that is entered when you press Enter. Since that character is still there waiting to be read, the nextLine() consumes it. To fix this you can add a nextLine() after the next() call:
char ch = input.next().charAt(0);
input.nextLine(); // consumes new-line character
// ...
For futher information, you could read this post.
After entering your number I guess you are pressing <enter> so this needs to be chewed up before entering your string
try
char ch = input.next().charAt(0);
input.nextLine();
System.out.println("Enter the string to search: ");
String str = input.nextLine();
Related
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;
}
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
so my problem is that I need to get the user to enter a string. then they will enter a character that they want counted. So the program is supposed to count how many times the character they entered will appear in the string, this is my issue. If someone can give me some information as to how to do this, it'll be greatly appreciated.
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they wan counted in the string
String character= keyboard.nextLine();
}
}
Here is a solution taken from this previously asked question and edited to better fit your situation.
Either have the user enter a char, or take the first character from
the string they entered using character.chatAt(0).
Use word.length to figure out how long the string is
Create a for loop and use word.charAt() to count how many times your character appears.
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they want counted in the string
String character = keyboard.nextLine();
char myChar = character.charAt(0);
int charCount = 0;
for (int i = 1; i < word.length();i++)
{
if (word.charAt(i) == myChar)
{
charCount++;
}
}
System.out.printf("It appears %d times",charCount);
This should do it. What it does is that it gets a string to look at, gets a character to look at, iterates through the string looking for matches, counts the number of matches, and then returns the information. There are more elegant ways to do this (for example, using a regex matcher would also work).
#SuppressWarnings("resource") Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count + (count == 1 ? " time" : " times"));
import java.util.*;
public class VowelCounter
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Input a series of characters: ");
String letters = keyboard.next();
int count = 0;
for (int i = 0; i < letters.length(); i++)
{
char characters = letters.charAt(i);
if (isVowel(characters) == true)
{
count++;
}
}
System.out.println("The number of vowels is: " + count);
}
public static boolean isVowel(char characters)
{
boolean result;
if(characters=='a' || characters=='e' || characters=='i' || characters=='o' || characters=='u')
result = true;
else
result = false;
return result;
}
}
The code works but im suppose to input "Spring break only comes once a year." which if i do with the spaces my program will only find the vowels of Spring. how do i make it so it will skip the spaces and read the whole sentence.
This is your problem:
String letters = keyboard.next();
It has nothing to do with the vowel-counting part - but everything to do with reading the value. The Scanner.next() method will only read to the end of the token - which means it stops on whitespace, by default.
Change that to
String letters = keyboard.nextLine();
and you should be fine.
You should verify this is the problem by printing out the string you're working with, e.g.
System.out.println("Counting vowels in: " + letters);
When you do:
String letters = keyboard.next();
The Scanner stops reading at the first whitespace.
To read the complete phrase until you press enter, you should use nextLine() instead:
String letters = keyboard.nextLine();
Just use
String letters = keyboard.nextLine();
instead of
String letters = keyboard.next();
This is because .nextLine() will read line by line so that you can have your complete statement in latters. Hope this will help you