I'm trying to separate the words in a sentence. Each word of the sentence is stored into the string word, and then it adds everything back into one string again.
But why do I get an error with the substring line?
String sent = IO.readString();
char x;
String word ="";
int count = 0;
for(int i = 0; i < sent.length(); i++){
x = sent.charAt(i);
if(x == ' ')
{
word = sent.substring(x-count,x);
word = word + ' ';
count =0;
}
count++;
}
word = sent.substring(x-count,x); should be word = sent.substring(i-count,i);
Because x is a char, not an int, here
word = sent.substring(x-count,x);
and it should (probably) be something like
word = sent.substring(i-count,i);
because i is the position in the String.
You should consider using String.split(), which returns a String array.
Documentation: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
To use spaces and punctuation as a separator, you could do something like this:
String[] arrWords = sentence.split("([ ,.]+)");
If you really want to go with your original route, you'll have to add some special cases for the first word and last word. Although, what happens when there are multiple spaces, or punctuation? Test it and find out!
public class SeparateWords
{
public static void main(String[] args)
{
String sent ="Hello there how are you";
char x;
String word ="";
int count = 0;
for(int i = 0; i <= sent.length(); i++){
if (i == sent.length()){
word = sent.substring(i-count+1,i);
System.out.println(word);
break;
}
x = sent.charAt(i);
if(x == ' ')
{
if ((i-count) == 0){
word = sent.substring(i-count,i);
}
else{
word = sent.substring(i-count+1,i);
}
System.out.println(word);
word = word + ' ';
count =0;
}
count++;
}
}
}
Output:
Hello
there
how
are
you
Related
Count vowel in the word for method
public class Methods6 {
public static int countVowel(String words) {
int count = 0;
char[] vowel = {'a', 'e', 'i', 'o', 'u'};
for (int i = 0; i < words.length(); i++) {
char ch = words.charAt(i);
for (char cc : vowel) {
if (ch == cc) {
count++;
}
}
}
return count;
}
**Find max vowel in sentence **
public static String maxVowelWords() {
String sentence = getSentence().toLowerCase();
String words[] = sentence.split(" ");
int maxvowel = CountVowel(words[0]), count;
String maxWord = words[0];
for (int i = 1; i < words.length; i++) {
count = CountVowel(words[i]);
if (count > maxvowel) {
maxvowel = count;
maxWord = words[i] + " ";
}
}
return maxWord;
}}// 2 methods are located in the same Method Class
public class Test {
public static void main(String[] args) {
System.out.println(Methods6.MaxVowelWords());}}
When writing this method, it gives only the first word with the most vowel letters (eg. --------- hello my friend! ----------- just hello, hello and friend -------no!
How can I change the method of this?
Thanks for helps!
The way I interpret this question is that:
Find the word in the supplied String which contains the most vowels
in it.
If one or more words within that very same String contain equal
maximum number of vowels then concatenate the words together
delimited by a whitespace (or whatever).
So, if the String supplied was: "hello my friend" then both words, hello and friend, would be returned from the maxVowelWords() method in the form of (let's say):
hello, friend
Since both hello and friend contain 2 vowels which so happens to be the the max number of vowels in any given word then both words are returned.
If the supplied string however was: "hello my friend - I live on the Mississippi river." then only Mississippi is returned from the method since it is the only word within that String that contains a maximun number of 4 vowels. All other words containing vowels within the string contain a lesser vowel count.
If this is indeed the situation then your method should look something like this:
public static String maxVowelWords() {
String sentence = getSentence();
String words[] = sentence.split(" ");
int maxvowel = 0;
String maxWord = "";
for (int i = 0; i < words.length; i++) {
int count = countVowels(words[i]);
if (count == maxvowel) {
maxvowel = count;
// Ternary Operator is used here to applt the delimiter (", ") if needed,
maxWord += (maxWord.equals("") ? words[i] : ", " + words[i]) + " (" + count + " vowels)";
}
else if(count > maxvowel) {
maxvowel = count;
maxWord = words[i] + " (" + count + " vowels)";;
}
}
return maxWord;
}
Yes, you start your loop from 0 and maxWord String variable should be initialized to hold an empty string (""). Let the for loop do its work. And No, count is not a waste, it's actually a requirement in order to to acquire the maximum vowel count for maxvowel as each string word is placed through the process.
You utilize a method named getSentence() to acquire the String to process and right away you distort that Original String by setting it to all lower case. You really shouldn't do that since the words you return from your maxVowelWords() method will not be the originally supplied words should they happen to have upper case vowels. A small modification to the countVowel() method can take care of that business, for example:
if (Character.toLowerCase(ch) == cc) {
count++;
}
There are few bugs in your code. Try this :
public static String maxVowelWords() {
String sentence = getSentence().toLowerCase();
String words[] = sentence.split(" ");
int maxvowel = 0, count;
String maxWord = "";
for (int i = 0; i < words.length; i++) {
count = countVowel(words[i]);
if (count > maxvowel) {
maxvowel = count;
maxWord = "";
}
if(count == maxvowel){
maxWord = maxWord + words[i]+ " ";
}
}
return maxWord.trim();
}
Given a String sentence entered by the user. Print each word on a separate line with the word #. For example, If the sentence "The cat in the hat" was entered, the following would be the output
word #1: The
word #2: cat
word #3: in
word #4: the
word #5: hat
Scanner input = new Scanner (System.in);
String sentence;
String words = "";
int count = 1;
sentence = input.nextLine();
for (int i = 1; i < sentence.length(); i++)
{
if (sentence.charAt(i) == ' ')
count++;
}
{
words = sentence.substring(0,sentence.indexOf(' '));
System.out.println(words);
}
String s = "The cat in the hat";
Scanner scan = new Scanner(s);
int wordNum = 1;
while(scan.hasNext()){
String temp = scan.next();
System.out.println("word#" + wordNum + ": \t" + temp);
wordNum++;
}
or
System.out.print("word#" + wordNum + ": \t" + temp + "\t");
if you want all on the same line
In your for loop, keep track of the starting index of each word (e.g. store it in a variable). Whenever you hit a new space, print out the word using substring with the number appended to it.
A few cases you may want to handle. If the sentence begins or ends with a bunch of spaces, you need to handle this without printing anything or incrementing your word count. You will need to do the same if there are multiple spaces between words.
The following code separates the word of given string
import java.util.Scanner;
import java.util.StringTokenizer;
public class StringTokenDemo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String sentence=sc.nextLine();
StringTokenizer tokenizer=new StringTokenizer(sentence," ");
int i=1;
while (tokenizer.hasMoreTokens())
{
String token=(String)tokenizer.nextToken();
System.out.println("#word"+i+" "+token);
i++;
}
}
}
This is not the right place to post homework, anyway the below code do what you want. If you want to print the words you need to store them, for example in a list or in an array.
List<String> words = new ArrayList<>();
String sentence = "The cat in the hat ";
int pos = 0;
int lastCharIndex = sentence.length() - 1 ;
for (int i = 0; i < sentence.length(); i++){
char cur = sentence.charAt(i);
//start to collect char for word only if
//the starting char is not a space
if(sentence.charAt(pos) == ' ' ){
pos+=1;
continue;
}
//continue the cycle if the current char is not a space
// and it isn't the last char
if(cur != ' ' && i != lastCharIndex){
continue;
}
//last word could not terminate with space
if(i == lastCharIndex && cur != ' '){
i+=1;
}
String word = sentence.substring(pos,i);
pos=i;
words.add(word);
}
System.out.println(words);
the code also take care if extra space between word or at the end of the sentence. Hope this can help.
did you try stringbuilder, or you can add all the elements in a arraylist and then count them. or count the chars.
Scanner input = new Scanner (System.in);
String sentence;
String words = "";
int count = 0;
for(char c : input.toCharArray()){
count++;
}
System.out.println("The word count is "+ count);
I have been trying to write a Java program which converts the first letter of every word of a string into a capital letter. Right now it looks like this:
package strings;
import java.util.Scanner;
public class small_cap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String st = sc.next();
String str = " " + st;
int j = 0; char chr = ' ';
for (int i = 0; i < str.length(); i++){
j = i + 1;
chr = str.charAt(j);
if (chr == ' '){
char a = Character.toUpperCase(str.charAt(j));
str = str.replace(str.charAt(j), a);
}
else{
char a = Character.toLowerCase(str.charAt(j));
str = str.replace(str.charAt(j), a);
}
}
System.out.println(str);
}
}
Unfortunately I keep on getting the error:
java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at small_cap.main(small_cap.java:19)
I don't really see any fault in the code. Can someone please point out where I am going wrong?
You were using Scanner.next() rather then Scanner.nextLine() which will read the whole sentence rather then single word.
You are adding extra space in String. Don't know the big reason behind that. It can be done without it.
Let say the Input is : "abc def" which will become " abc def" after adding extra space. Length of string will become : 7
Now for loop will iterate from 0 to 6. But on i = 6 it will try to alter the element on 7th position (since you are doing j=i+1) which will cause string index out of range error.
You are using String.Replace which will replace all matching characters irrespective of their position.
import java.util.Scanner;
public class small_cap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String st = sc.nextLine();
String str = " " + st;
int j = 0; char chr = ' ';
for (int i = 0; i < str.length()-1; i++){
j = i+1;
chr = str.charAt(i);
if (chr == ' '){
char a = Character.toUpperCase(str.charAt(j));
str = str.substring(0,j)+a+str.substring(j+1);
}
else{
char a = Character.toLowerCase(str.charAt(j));
str = str.substring(0,j)+a+str.substring(j+1);
}
}
System.out.println(str);
}
}
for (int i = 0; i < str.length(); i++){
j = i + 1;
When i reaches the last valid index length - 1, j will be equal to length, which is out of bounds.
I don't really see the point of the j variable to begin with - did you mean to use i somewhere else inside the loop as well, or should you just make your loop start from 1? Or did you perhaps mean to check the previous character by doing j = i - 1; (in that case make sure you don't read before index 0)
My programs throws StringIndexOutOfBoundsException at this segment of code: temp1 = temp.replace('-', temp.charAt(p)); I'm trying to get the index of the same letter (after comparing inputted letter and word) and removing the '-' to show that the user has guessed correctly.** **I've been trying for hours to no avail. I think the problem lies in my loops. Thanks for the answers :) if I violated anything, please forgive me.
run:
-----
Enter a letter:
a
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:
3
at java.lang.String.charAt(String.java:658)
at Hangman.main(Hangman.java:34)
Java Result: 1
import java.util.Scanner;
public class Hangman {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
String word = "Sample";
String temp = null;
String temp1 = null;
String letter = null;
int n;
int m=0;
int p = 0;
for (n = 0; n<word.length(); n++){
temp = word.replaceAll(word, "-"); //replaces the String word with "-" and prints
System.out.print(temp);
}
while (m<=5){ //the player can only guess incorrectly 5 times
System.out.println("\nEnter a letter:");
letter = sc.nextLine();
letter.toLowerCase();
if (word.contains(letter) == true){
p = word.indexOf(letter);
temp1 = temp.replace('-', temp.charAt(p)); //if the word contains the letter, "-" is replaced by the letter.
System.out.print(temp1);
}
else {
System.out.print("\nMissed: "+letter); //if not, Missed: +the given letter
m++; //to count for incorrect guesses
}
System.out.print(temp1);
}
System.out.println("Game Over.");
}
}
When you do this:
temp = word.replaceAll(word, "-");
...you are setting temp to be just "-", and not (for example) "----". To see why, consider if word is "hello"; then this line looks like:
temp = "hello".replaceAll("hello", "-");
So then later you are assuming that temp is as long as word is, because you find an index in word and try to access that character in temp. But temp is only one character long, hence the exception.
p = word.indexOf(letter);
temp1 = temp.replace('-', temp.charAt(p));
Try this one.....
This will solve your problem...!!
package beans;
import java.util.Scanner;
public class Hangman {
public static String replace(String str, int index, char replace){
if(str==null){
return str;
}else if(index<0 || index>=str.length()){
return str;
}
char[] chars = str.toCharArray();
chars[index] = replace;
return String.valueOf(chars);
}
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
String word = "Sample";
String temp = "";
String letter = null;
int n;
int m=0;
int p = 0;
for (n = 0; n<word.length(); n++){
temp = temp + word.replaceAll(word, "-"); //replaces the String word with "-" and prints
}
System.out.print(temp);
while (m <= 5){ //the player can only guess incorrectly 5 times
System.out.println("\nEnter a letter:");
letter = sc.nextLine();
letter.toLowerCase();
if (word.contains(letter) == true){
p = word.indexOf(letter);
temp = replace(temp, p , word.charAt(p)); //if the word contains the letter, "-" is replaced by the letter.
System.out.println(temp);
}
else {
System.out.print("\nMissed: "+letter); //if not, Missed: +the given letter
m++; //to count for incorrect guesses
}
}
System.out.println("Game Over.");
}
}
You shoud check documentation for replaceAll() method.Cause you are using it wrong.
replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
You putting whole string into regex parameter
If you do myString.replaceAll("\\.","-"); (use double backslash to specify regex) will replace any character beside newline with "-" check into regex. Regullar expressions
if (word.contains(letter) == true){
p = word.indexOf(letter);
temp1 = temp.replace('-', temp.charAt(p)); //if the word contains the letter, "-" is replaced by the letter.
System.out.print(temp1);
}
the word.indexOf(letter); return index of letter if that latter is present in string otherwise -1. that's why you are getting Exception.
I am new to java and I have been trying to solve a problem which I feel might have a simpler answer than my code.The problem was to print the initials of a user input name of any length along with the full surname.But this has to be done without any String.split() or arrays.I tried getting the user to input his name one word at a time, but is there any there a possible way to get the whole name at once and do as required.
My code is as follows:
import java.io.*;
public class Initials {
public static void main(String[]args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of words your name contains");
int n=Integer.parseInt(br.readLine());
String str="";
for(int x=1;x<=n-1;x++){
System.out.println("Enter your name's word number:"+" "+x);
String s=br.readLine();
String st=s.toUpperCase();
char ch=st.charAt(0);
str=str+ch+".";
}
System.out.println("Enter your surname");
String sur=br.readLine();
str=str+" "+sur.toUpperCase();
System.out.println(str);
}
}
Use a regular expression (namely (?<=\w)\w+(?=\s)):
String name = "John Paul Jones"; // read this from the user
System.out.println(name.replaceAll("(?<=\\w)\\w+(?=\\s)", "."));
J. P. Jones
No split(), no arrays :)
A little explanation: We essentially want to replace all letters of each word that is followed by a whitespace character except the first letter, with a . character. To match such words, we use (?<=\w)\w+(?=\s):
(?<=\w) is a positive lookbehind; it checks that a word-character exists at the start of the match but does not include it in the match itself. We have this component because we don't want to match the first character of each name, but rather all but the first (except for the last name, which we'll deal with shortly).
\w+ matches any continuous string of word characters; we use this to match the rest of the name.
(?=\s) is a positive lookahead; it checks that our match is followed by a whitespace character, but does not include it in the match itself. We include this component because we don't want to replace anything on the last name, which should not be followed by a whitespace character and hence should not match the regular expression.
Another way around---
import java.util.Scanner;
//a class that will print your output
class Initial {
public void Initials() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Full name:");
String name = sc.nextLine();
int l = name.length();
int pos = 0;
for (int i = l - 1; i >= 0; i--) {
char ch = name.charAt(i);
if (ch == ' ') {
pos = i; //getting the last space before Surname
break;
}
}
System.out.print("The initials are: ");
System.out.print(name.charAt(0) + ".");//prints first name initial
// with dot
for (int x = 1; x < pos; x++) //finds midname initial
{
char ch = name.charAt(x);
if (ch == ' ') {
System.out.print(name.charAt(x + 1) + ".");
}
}
for (int i = pos; i < l; i++) { //for printing Surname
System.out.print(name.charAt(i));
}
}
}
public class Str {
public static void main(String[] args) {
Initial i = new Initial();
i.Initials();
}
}
//This code will work for any no. of words in the name
class Surnam {
public static void main(String name) {
name = " " + name;
int l=name.length(), p=0, m=0, r=0;
char y;
String word=" ", words=" ";
for(int i = 0; i = 0; i--) {
y=name.charAt(i);
if(y==' ') {
r=name.lastIndexOf(y); //extracting the last space of the string
word=name.substring(i,l); //extracting the surname
words=name.replace(word," "); //removing the surname break;
}
}
for (int i = 0; i <= r - 1; i++) {
char x=words.charAt(i);
if (x == ' ') {
System.out.print(words.charAt(i + 1) + "."); //Printing all initials before the surname with a dot
}
}
for (int i = l - 1; i >= 0; i--) {
char x=name.charAt(i);
if(x==' ') {
m=i;
name=name.substring(m,l); //extracting the surname
name=name.trim(); //removing all the spaces before the surname
System.out.print(name);
break;
}
}
}
}