This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 9 years ago.
I updated my code from previous suggestions, and it is only reading the first word in my sentence, any suggestions on how to get it to read the whole sentence? (I have to use a for loop)
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char letter;
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
count ++;
}
}
System.out.printf("There are %d occurrences of %s in %s", count,
letter, sentence);
}
}
Output:
Enter a character for which to search
h
Enter the string to search
hello how are you
There are 1 occurrences of h in hello
It's a little tricky here. You will need two readLines().
System.out.println("Enter a character for which to search");
letter = in.nextLine().charAt(0);
System.out.println("Enter the string to search");
sentence = in.nextLine();
Scanner.next() only reads one word and does not finish the line.
// Assume input: "foo" [enter] "test this yourself!"
Scanner.next(); // "foo"
Scanner.nextLine(); // EMPTY STRING!
Scanner.nextLine(); // "test this yourself!"
Your scanner only reads the next word (in.next()). If you want to read a whole line, you should use the method nextLine of your Scanner.
If you expect the user to input several values, you will have to read accordingly from that Scanner (so you will also have to read the newline from the answer of the first question you are asking the user).
I will not give you code to fix the issue, this is just meant as a pointer in the right direction. It would be very good if you familiarize yourself with those standard classes. Sun/Oracle have done a very good job in documentation. So the first look should always be in the Java Doc of the classes you are using.
Here is the doc for the class Scanner.
Related
This question already has answers here:
Scanner only reads first word instead of line
(5 answers)
Closed 2 years ago.
I'm trying to write code that receives a string as input and then counts the number of words within said string, but it returns 1 no matter the input. Surprisingly, pasting the sample code from my textbook (C. Thomas Wu - An Introduction to Object-Oriented Programming) gives the same problem and I can't figure out why.
My code is as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String sentence = scanner.next();
char BLANK = ' ';
int index = 0, wordCount = 0;
int numberOfCharacters = sentence.length();
while (index < sentence.length()){
while (index < sentence.length() && sentence.charAt(index) != BLANK){
index++;
}
while (index < sentence.length() && sentence.charAt(index) == BLANK){
index++;
}
wordCount++;
}
System.out.println(wordCount);
}
}
Thanks in advance for any help!
You have used scanner.next() which will capture only the first word of the sentence. It stops where it finds a white space. You need to use scanner.nextLine().
Also, given below is another way of doing it:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
System.out.println("Total no. of words: " + scanner.nextLine().split("\\s+").length);
}
}
A sample run:
Enter a sentence: Ram is a good boy.
Total no. of words: 5
Another sample run:
Enter a sentence: Harry is an intelligent guy.
Total no. of words: 5
In this program, we are splitting the input on space(s) using String::split function, which returns a String[] with the words of the input as its elements, and then we are printing the length of this resulting String[].
Scanner.next returns only a single "word" (for some definition of word), and every time you call it will return the next word in the input.
To get an entire line of text, with multiple words, use nextLine:
String sentence = scanner.nextLine();
Hello you can do this by using sentence.split(' ') and getting the length.
For an example:
String sentence = "I like eating apples everyday";
String[] words = sentence.split(' ');
int wordCount = words.length;
Code to check count number of words in a string:
String sentence = "I'm new user of Java!";
int word_count = 0;
for (int i = 1; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
char ch2 = sentence.charAt(i-1);
if (ch == ' ' && ch2 != ' ')
word_count++;
}
System.out.println("Word count: " + word_count);
out:
Word count: 4
java code at online compilier
You can use regex to count all types of spaces including more than 1 successive space characters, tabs & line returns:
\\s is a regex that matches space characters
.split(): split the string into different strings based on a separator/delimiter which is the \\s+ regex
String sentence = scanner.next();
String[] split= sentence.split("\\s+");
int wordCount = split.length;
System.out.println(wordCount);
I want the user to type in a string.
The console output should have string.length lines (plus the line where the user inputs the string).
The first line should output the first symbol of the string (string.length) times.
The second line should output the first symbol of the string and then repeat the second symbol (string.length - 1) times, and so on.
Here is an example of what I want the console output the be with the word "example".
What will your word be?: example
eeeeeee
exxxxxx
exaaaaa
exammmm
examppp
exampll
example
I have no idea where to start with this one. I'd appreciate any help.
Edit
Sorry for being so unclear and not providing any code. This is what I have so far.
import java.util.Scanner;
public class muster{
public static void main(String s[]){
Scanner sc=new Scanner(System.in);
System.out.println("What will your string be?");
String word=sc.next();
for(int i=0;i<word.length();i++)
System.out.println(word.substring(0,i+1));
}
}
This will read the users input and print the word starting from the first letter with a new letter in each new line. What I still need is that the code repeats the letters for as long as the rest of word.length is.
You got very close. You already had the idea to print the substring from 0 to i. Then you just need an inner loop that starts at i+1 and loops until word.length and print out the char at i. Also you need to use System.out.print() so that they will be on the same line:
Scanner sc=new Scanner(System.in);
System.out.println("What will your string be?");
String word=sc.next();
for(int i=0;i<word.length();i++) {
System.out.print(word.substring(0,i+1));
for(int j = i+1; j < word.length(); j++) {
System.out.print(word.charAt(i));
}
System.out.println();
}
Output:
What will your string be?
example
eeeeeee
exxxxxx
exaaaaa
exammmm
examppp
exampll
example
So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.
I am wondering how to count the number of times that a letter entered by a user appears in a string that is also entered by a user. I have to use Loops and if/else statements. I think I'm on the right track, but I get caught up when compiling (using BlueJ), with the error message "cannot find symbol - variable position". Any help is greatly appreciated, thanks.
String input;
String sentence;
String letter;
int times=0;
int position;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a string: ");
input = kb.nextLine();
sentence = input.toLowerCase();
System.out.print("Thank you.\nPlease enter the character you wish to be counted: ");
letter = kb.next();
for (position=0; position<=sentence.length(); position++) {
if (sentence.charAt(position) == letter) {
times++;
}
}
System.out.print("There are "+times+" ocurrances of the letter "+letter
+" in the string "+sentence);`
First, you have a typo in your if statement:
sentence.charAt(posotion)
should be
sentence.charAt(position)
Then, you are assigning rather than testing equality:
if (sentence.charAt(position) = letter) {
should be
if (sentence.charAt(position) == letter) {
Next, you are comparing a char with a string in that if statement. There are several ways to solve this, one way is (assuming letter has at least one character):
if (sentence.charAt(position) == letter.charAt(0)) {
And lastly, you probably don't what to check past the end of the string so:
for (position=0; position<=sentence.length(); position++) {
should be
for (position=0; position<sentence.length(); position++) {
I am having some trouble preventing the user from entering numbers with the scanner class. This is what I have:
package palindrome;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word;
String inverse = "";
System.out.println("Write a sentence or word: ");
while (!input.hasNext("[A-Za-z]+")) {
System.out.println("Not valid! Try again: ");
input.nextLine();
}
word = input.nextLine();
word = word.replaceAll("\\s+","");
word = word.toLowerCase();
int length = word.length();
length = length - 1;
for (int i = length; i >= 0; i--) {
inverse = inverse + word.charAt(i);
}
if (word.equals(inverse)) {
System.out.println("Is a palindrome.");
} else {
System.out.println("Is not a palindrome.");
}
}
}
Basically when I enter a word or sentence I want it to check if it has any numbers anywhere in the input, if it has then you need to enter another one until it doesn't. Here is an example of output:
Write a sentence or word:
--> 11
Not valid! Try again:
--> 1 test
Not valid! Try again:
--> test 1
Is not a palindrome.
As you can see it works for most cases, but when I enter a word FIRST and then a space followed by a number it evaluates it without the number. I am assuming this is happening because in the while loop is checking for only input.hasNext but it should be input.hasNextLine I believe to check the entire string. However I cannot have any arguments if I do that. Help much appreciated!
Change your regex from: [A-Za-z]+ to ^[A-Za-z]+$ in order to prevent numbers anywhere in the input-string