What's Wrong? Number Of Words In a Sentence Java - java

int numOfWords = str.length() - str.replace(" ", "").length();
Why does that not work? If str is equal to "Hello bye", numOfWords should equal 2, but when ran numOfWords equals 0. Any help would be greatly appreciated!

You are only replacing one blank, so the output will be 1 (at least this is what is produce in my JVM)
If you want to know the number of words then either add 1 to this number or use
str.split(" ").length;

Why dont you use :
int numOfWords = str.split(" ").length;

I hope out put is much clear
public static void main(String[] args) {
String str = "Hello bye";
System.out.println("Length of Input String = " + str.length() + " for String = " + str);
System.out.println("Length of Input String with space removed = " + str.replace(" ", "").length() + " for String = "
+ str.replace(" ", ""));
int numOfWords = str.length() - str.replace(" ", "").length();
System.out.println(numOfWords);
}
Output
Length of Input String = 9 for String = Hello bye
Length of Input String with space removed = 8 for String = Hellobye
1

Related

How to format an output?

(In Java) Write a program that accepts names and formats them as follows: If the input is:
John Anthony Brown
Then the output must be:
Brown, John A.
Here is what I have
int mn;
String input3;
int fn;
int ln;
String firstName;
String lastName;
String middleName;
Scanner scnr = new Scanner(System.in);
String input = scnr.nextLine();
fn = input.indexOf(" ");
firstName = input.substring(0, fn);
middleName = input.substring(fn+1, input.length());
mn = middleName.indexOf(" ");
lastName = input.substring(mn+1, input.length());
System.out.println(lastName + ", " + mn + " " + firstName + ".");
}
I keep trying different things and get weird outputs such as "ry A Lee, 1 Mary." for the input "Marry A Lee"
This topic was never covered in my class and I am very confused.
Because this is homework, I’ll give code fragments:
Firstly, use split() to break up the text into words:
String[] names = input.split(" ");
Then build up your result:
String result = names[2] + ", " + names[0] + ", " + names[1].charAt(0) + ".";
There are more elegant ways of doing it, but this way is arguably the easiest to understand.
You could get fancier by catering for varying numbers of names.
Try something like this:
String[] items = input.split(" ");
//if there are three item in items, then it is the pattern you mentioned
if (items.length == 3) {
System.out.println(items[2] + "," + items[0] + items[1].charAt(0) + ".");
}

Problems with Output in Java

I have no idea why my output is not coming out correct. For example, if the input is "Running is fun" then the output should read "Is running fun". However, the output I am getting is "Iunning".
import java.util.Scanner;
public class Problem1 {
public static void main( String [] args ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String sentence = sc.nextLine();
int space = sentence.indexOf(" ");
String firstWord = sentence.substring(0, space + 1);
String removedWord = sentence.replaceFirst(firstWord, "");
String newSentence = removedWord.substring(0,1).toUpperCase() +
firstWord.substring(1).toLowerCase();
System.out.println("");
System.out.println( newSentence );
}
}
removedWord.substring(0,1).toUpperCase() this line adds the capitalized first letter of the second word in the sentence. (I)
firstWord.substring(1).toLowerCase(); adds every letter of the first word to the end of the sentence. (unning)
Thus this creates the output of Iunning. You need to add the rest of removedWord to the String, as well as a space, and the first letter of firstWord, as a lower case letter at the space in removedWord. You can do this more by using indexOf to find the space, and then using substring() to add on firstWord.toLowerCase() right after the index of the space:
removedWord = removedWord.substring(0, removedWord.indexOf(" ")) + " " +
firstWord.toLowerCase() +
removedWord.substring(removedWord.indexOf(" ") + 1,
removedWord.length());
String newSentence = removedWord.substring(0,1).toUpperCase() +
removedWord.substring(1, removedWord.length());
Output:
Is running fun
Your problem is that
firstWord.substring(1).toLowerCase()
Is not working as you expect it to work.
Given firstWord is “Running“ as in your example, then
”Running“.substring(1)
Returns ”unning“
”unning“.toLowerCase()
Obviously returns ”unning“
The problem is at String newSentence. You not make the right combination of firstWord and removedWord.
This is how should be for your case:
String newSentence = removedWord.substring(0, 1).toUpperCase() // I
+ removedWord.substring(1,2) + " " // s
+ firstWord.toLowerCase().trim() + " " // running
+ removedWord.substring(2).trim(); // fun
EDIT(add new solution. credits #andy):
String[] words = sentence.split(" ");
words[1] = words[1].substring(0, 1).toUpperCase() + words[1].substring(1);
String newSentence = words[1] + " "
+ words[0].toLowerCase() + " "
+ words[2].toLowerCase();
This works properly:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String sentence = sc.nextLine();
int space1 = sentence.indexOf(' ');
int space2 = sentence.indexOf(' ', space1 + 1);
if (space1 != -1 && space2 != -1) {
String firstWord = sentence.substring(0, space1 + 1);
String secondWord = sentence.substring(space1 + 1, space2 + 1);
StringBuilder newSentence = new StringBuilder(sentence);
newSentence.replace(0, secondWord.length(), secondWord);
newSentence.replace(secondWord.length(), secondWord.length()+ firstWord.length(), firstWord);
newSentence.setCharAt(0, Character.toUpperCase(newSentence.charAt(0)));
newSentence.setCharAt(secondWord.length(), Character.toLowerCase(newSentence.charAt(secondWord.length())));
System.out.println(newSentence);
}
}

How to only add something to a string if it doesn't contain it?

I am making a Lipogram program where any words with the banned letter are printed, however, the words are sometimes printed twice. How do I get it to not repeat the words?
Here is my code:
public String allWordsWith(char letter) {
String str = "";
String word = "";
s = s.replace(".", " ");
s = s.replace(",", " ");
s = s.replace("?", " ");
s = s.replace("!", " ");
s = " " + s + " ";
for (int i = 0; i <= s.lastIndexOf(letter); i++) {
if (s.charAt(i) == letter) {
if (str.contains(s.substring(s.lastIndexOf(" ", i), s.lastIndexOf(" ", i) + 1) + '\n') == true) {
} else {
word += s.substring(s.lastIndexOf(" ", i), s.indexOf(" ", i)) + '\n';
str += word;
}
}
}
return str;
}
Important clarification: Is the function run with the letter chosen as "o" on the string "hello hi hello howdy" meant to return "hello hello howdy" or "hello howdy". I.e., if the word appears twice, do you want to print it twice, or do you only want to print it once regardless of repetition?
If only once regardless of repetition, then you should be using a Set to store your data.
However, I think there's a chance you're instead dealing with an issue that when running the function with the letter chosen as "l" on that same string, "hello hi hello howdy", you are getting an output of "hello hello hello hello". Correct?
The issue here is that you are checking every letter and not testing each word. To fix this, I would use:
String[] words = s.split(" ");
to create an array of your words. Test each value in that array to see if it contains the given letter using:
if(words[index].contains(letter)){
str += " " + words[index];
}

Java split line not working

this is my code
//Numbers (Need errors on sort and numbers)
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n"))
{
//split the already split line with "n thename "
String[] LineSplit2 = line.split("n " + LineSplit[0] + " ");
String text = "var " + LineSplit[1] + "=" + LineSplit2[0] + ";";
text = text.replace("\n", "").replace("\r", "");
JAVASCRIPTTextToWrite += text;
}
}
the line of text is
n number 1
the output should be
var number = 1;
but the output is
var number=n number = 1;
can some one please tell me how to fix this? the code looks right but doesn't work :(
String line = "n number 1";
String JAVASCRIPTTextToWrite="";
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n"))
{
//split the already split line with "n thename "
String[] LineSplit2 = line.split("n " + LineSplit[1] + " ");
System.out.println( LineSplit[1]);
System.out.println( LineSplit2[0]);
String text = "var " + LineSplit[1] + "=" + LineSplit2[1] + ";";
text = text.replace("\n", "").replace("\r", "");
JAVASCRIPTTextToWrite += text;
System.out.println(JAVASCRIPTTextToWrite);
}
}
String number = "n number 1";
Sting[] temp = number.split(" ");
StringBuilder sb = new StringBuilder("var ");
sb.append(temp[1]);
sb.append(temp[2]);
perform this operation if your condition satisfied
String line = "n number 1";
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n")) {
//split the already split line with "n thename "
String LineSplit2 = line.substring(line.lastIndexOf(" ") + 1 , line.length());
String text = "var " + LineSplit[1] + "=" + LineSplit2 + ";";
//text = text.replace("\n", "").replace("\r", "");
System.out.println(text);
}
}
Output:
var number=1;
I do not know what is your purpose for split the string twice. Just for the out put you want, I think the solution below is enough. Please look at the code below whether is you want:
String line = "n number 1";
String JAVASCRIPTTextToWrite = "";
//Numbers (Need errors on sort and numbers)
if(line.contains("n")) {
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit.length == 3) {
StringBuilder text = new StringBuilder();
text.append("var ");
text.append(LineSplit[1]);
text.append("=");
text.append(LineSplit[2]);
text.append(";");
JAVASCRIPTTextToWrite += text.toString().replace("\n", "").replace("\r", "");
System.out.println(JAVASCRIPTTextToWrite);
}
}

Swapping the position of elements within an array in java?

Ok, so it's the first time I am posting out here, so bear with me.
I have a name in the format of "Smith, Bob I" and I need to switch this string around to read "Bob I. Smith". Any ideas on how to go about doing this?
This is one way that I've tried, and while it does get the job done, It looks pretty sloppy.
public static void main(String[] args) {
String s = "Smith, Bob I.", r = "";
String[] names;
for(int i =0; i < s.length(); i++){
if(s.indexOf(',') != -1){
if(s.charAt(i) != ',')
r += s.charAt(i);
}
}
names = r.split(" ");
for(int i = 0; i < names.length; i++){
}
System.out.println(names[1] +" " + names[2] + " " + names[0]);
}
If the name is always <last name>, <firstname>, try this:
String name = "Smith, Bob I.".replaceAll( "(.*),\\s+(.*)", "$2 $1" );
This will collect Smith into group 1 and Bob I. into group 2, which then are accessed as $1 and $2 in the replacement string. Due to the (.*) groups in the expression the entire string matches and will be replaced completely by the replacement, which is just the 2 groups swapped and separated by a space character.
String[] names = "Smith, Bob I.".split("[, ]+");
System.out.println(names[1] + " " + names[2] + " " + names[0]);
final String[] s = "Smith, Bob I.".split(",");
System.out.println(String.format("%s %s", s[1].trim(), s[0]));
String s = "Smith, Bob I.";
String result = s.substring(s.indexOf(" ")).trim() + " "
+ s.substring(0, s.indexOf(","));

Categories