while loop: while sentence does not contain a word - java

I'm getting user input and checking to see if the word 'java' is in the sentence. I did a while loop but even when the word 'java' is in the sentence, it tells me that it's not and continues with the while loop. If I remove the while loop, everything else that I want my program to do works. here is the code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//declare all variables
String sentence;
int java_index_number;
String stop_program;
String java;
String Java;
String JAVA;
String java_capital_first_letter;
String java_all_caps;
//scanner to get user input
Scanner user_input = new Scanner(System.in);
//prompt the user for a sentence
System.out.print("Enter a line of text containing the word 'java' somewhere within it: ");
sentence = user_input.nextLine();
java = "java";
Java = "Java";
JAVA = "JAVA";
while(!sentence.contains(java) || !sentence.contains(Java) || !sentence.contains(JAVA)) {
System.out.println("Your sentence does not have the word 'java' within it.");
System.out.print("Enter a line of text containing the word 'java' somewhere within it: ");
sentence = user_input.nextLine();
}
//output
System.out.println();
System.out.println("The string read is: " + sentence);
System.out.println("Length in chars is: " + sentence.length());
System.out.println("All lowercase is: " + sentence.toLowerCase());
System.out.println("All uppercase is is: " + sentence.toUpperCase());
//store java index pos in variable
java_index_number = sentence.indexOf("java");
System.out.println("Found 'java' or at pos: " + java_index_number);
//make first letter of java a capital letter
java_capital_first_letter = sentence.substring(0, java_index_number) + sentence.substring(java_index_number,
java_index_number + 1).toUpperCase() + sentence.substring(java_index_number + 1, java_index_number + 4)
+ sentence.substring(java_index_number + 4);
//make java all caps
java_all_caps = sentence.substring(0, java_index_number) + sentence.substring(java_index_number,
java_index_number + 4).toUpperCase() + sentence.substring(java_index_number + 4);
//output
System.out.println("Changing to 'Java': " + java_capital_first_letter);
System.out.println("Changing to 'JAVA': " + java_all_caps);
// Keep console window alive until 'enter' pressed
System.out.println();
System.out.println("Done - press enter key to end program");
stop_program = user_input.nextLine();
}
}
How do I get the while loop to work?
UPDATE: after the awesome feedback that I got, I finally got it to work.. Thanks everyone who helped!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//declare all variables
String sentence;
int java_index_number;
String stop_program;
String java_capital_first_letter;
String java_all_caps;
//scanner to get user input
Scanner user_input = new Scanner(System.in);
//prompt the user for a sentence
System.out.print("Enter a line of text containing the word 'java' somewhere within it: ");
sentence = user_input.nextLine();
while(!sentence.toLowerCase().contains("java")) {
System.out.println("Your sentence does not have the word 'java' within it.");
System.out.print("Enter a line of text containing the word 'java' somewhere within it: ");
sentence = user_input.nextLine();
}
//output
System.out.println();
System.out.println("The string read is: " + sentence);
System.out.println("Length in chars is: " + sentence.length());
System.out.println("All lowercase is: " + sentence.toLowerCase());
System.out.println("All uppercase is is: " + sentence.toUpperCase());
//store java index pos in variable
sentence = sentence.toLowerCase();
java_index_number = sentence.indexOf("java");
System.out.println("Found 'java' or at pos: " + java_index_number);
//make first letter of java a capital letter
java_capital_first_letter = sentence.substring(0, java_index_number) + sentence.substring(java_index_number,
java_index_number + 1).toUpperCase() + sentence.substring(java_index_number + 1, java_index_number + 4)
+ sentence.substring(java_index_number + 4);
//make java all caps
java_all_caps = sentence.substring(0, java_index_number) + sentence.substring(java_index_number,
java_index_number + 4).toUpperCase() + sentence.substring(java_index_number + 4);
//output
System.out.println("Changing to 'Java': " + java_capital_first_letter);
System.out.println("Changing to 'JAVA': " + java_all_caps);
// Keep console window alive until 'enter' pressed
System.out.println();
System.out.println("Done - press enter key to end program");
stop_program = user_input.nextLine();
}
}

The problem is in how you created the boolean clause inside the while. So, currently you have this:
while(!sentence.contains(java) || !sentence.contains(Java) || !sentence.contains(JAVA))
Let's suppose that the sentence contains "java". So, !sentence.contains(java) is false. However, !sentence.contains(Java) is true, since the sentence contains "java" but not "Java". Because you're using logical ORs (||) a single true is enough to make the entire clause true, and the inside of the while loop is executed.
Probably, what you're trying to do would be done this way:
while(!sentence.contains(java) && !sentence.contains(Java) && !sentence.contains(JAVA))
In that case, all of the clauses above have to be true, meaning that sentence cannot contain "java", "Java" or "JAVA".

Try to avoid all those different variables for "Java". I think you're trying to find when the java appear. So apply to your sentence an sentence.toLowerCase().contains("java")
The user input will be converted to lower case and just check if contains the word java in lower case, so you can avoid the use of so many or.
Inside your while just put a while(true), and check with an if(sentence.toLowerCase().contains("java")){break;}.

Related

Strings getting messed up within the loop

So guys, I've made a program that counts how many words and letters a given sentence has. For instance, if my input is "stack overflow", it would return 2 WORDS and 13 LETTERS. But I've been having a problem to read single letters that are also contained in another word within the sentence. For example, the input "a alex" has been returning me 2 words and 4 LETTERS, when it should be returning 5 letters... I noticed that, as soon as it reads the first "a", the second string "alex" becomes "lex" for some reason, but I don't know how to solve it... here's the snippet, thx in advance!
package Uri;
import java.util.Scanner;
import java.lang.Math;
import java.lang.StringBuilder;
public class Facil{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String lida=sc.nextLine();
int letras=0, palavras=0;
while(lida != ""){
System.out.println("current sentence = " + lida);
if (lida.charAt(0) == ' ') {
lida = lida.replaceFirst(" ", "");
continue;
}
if (!lida.contains(" ")) {
palavras++;
letras+=lida.length();
System.out.println("quantity of added letters = " + lida.length());
break;
}
String separada = lida.substring(0,lida.indexOf(" "));
System.out.println("separated word = " + separada);
if (!separada.contains("..") && separada.endsWith(".") || !separada.contains(".")){
palavras++;
letras+=separada.length();
lida = lida.replace(separada, "");
System.out.println("added letters = " + separada.length());
}
}
System.out.println("\n RESULT: ");
System.out.println("quantity of words = " + palavras);
System.out.println("quantity of letters = " + letras);
}
}
}
Your problem comes from lida = lida.replace(separada, ""); where you replace 'a' with space
How about using lida.split(" ") then get the length of the array for the number of words? And for each word, use String.length() to count for the letters?

Trying to get the length of a sentence from a user input but it stops after the first word and space

The Java task is to have the user type a sentence/phrase and then print out how many characters the sentence has. My .length() method is only counting the first word and space as characters. I've read previous questions and answers involving nextLine() but if I use that instead of next() it only lets the user type it's question and waits, doesn't print anything else immediately anymore. I'm brand new to Java and I think this can be fixed with a delimiter but I'm not sure how or what I'm missing. TIA!!
Update: Here's my code.
import java.util.Scanner;
class StringStuff{
public static void main( String [] args){
Scanner keyboard = new Scanner(System.in);
int number;
System.out.print("Welcome! Please enter a phrase or sentence: ");
System.out.println();
String sentence = keyboard.next();
System.out.println();
int sentenceLength = keyboard.next().length();
System.out.println("Your sentence has " + sentenceLength + " characters.");
System.out.println("The first character of your sentence is " + sentence.substring(0,1) + ".");
System.out.println("The index of the first space is " + sentence.indexOf(" ") + ".");
}
}
when I type "Hello world." as the sentence it prints:
Your sentence has 6 characters.
The first character of your sentence is H.
The index of the first space is -1.
keyboard.next call is waiting for user input. You're calling it twice, so your program expects the user to enter two words.
So, when you type in "Hello world." it reads "Hello" and "world." separately:
//Here, the sentence is "Hello"
String sentence = keyboard.next();
System.out.println();
//Here, keyboard.next() returns "World."
int sentenceLength = keyboard.next().length();
And when you use nextLine your code is waiting for the user to enter two lines.
To fix this you need to:
Read the whole line with nextLine.
Use sentence instead of requesting user input the second time.
Something like this should work:
String sentence = keyboard.nextLine();
System.out.println();
int sentenceLength = sentence.length();
import java.util.Scanner;
public Stringcount
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter the sentence:");
String str=s.nextLine();
int count = 0;
System.out.println("The entered string is: "+str);
for(int i = 0; i < str.length(); i++)
{
if(str.charAt(i) != ' ')
count++;
}
System.out.println("Total number of characters in the string: " + count);
System.out.println("The first character of your sentence is " + str.substring(0,1) + ".");
System.out.println("The index of the first space is " + str.indexOf(" ") + ".");
}
}

Counting matching characters on a string

I have been asked to created a program that asks the user for two inputs, both of which have to be stored as strings. The first input can be one or multiple words, and the second input has to be one sole character. After the user enters both inputs the program should count how many times, if any, the sole charter appears in the first string. Once the iteration through the first string is done the program should then output the number of instances of the second string. Example:
"There is 1 occurrence(s) of 'e' in test."
The program must use the a while loop and string values. This is the solution I have as of right now following the parameters established by the professor
public static void main(String[] args) {
String inputEntry; // User's word(s)
String inputCharacter; // User's sole character
String charCapture; // Used to create subtrings of char
int i = 0; // Counter for while loop
int charCount = 0; // Counter for veryfiying how many times char is in string
int charCountDisplay = 0; // Displays instances of char in string
Scanner scan = new Scanner(System.in);
System.out.print("Enter some words here: "); // Captures word(s)
inputEntry = scan.nextLine();
System.out.print("Enter a character here: "); // Captures char
inputCharacter = scan.nextLine();
if (inputCharacter.length() > 1 || inputCharacter.length() < 1) // if user is not in compliance
{
System.out.print("Please enter one character. Try again.");
return;
}
else if (inputCharacter.length() == 1) // if user is in compliance
{
while( i < inputEntry.length()) // iterates through word(s)
{
charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
if (charCapture.equals(inputCharacter))
{
++charCountDisplay;
}
++charCount;
++i;
}
System.out.print("There is " + charCountDisplay +
" occurrence(s) of " + inputCharacter + " in the test.");
}
}
This iteration has a bug. Instead of counting all the instances of the inputCharacter variable it only counts up to one, regardless of how many instances appear on the string. I know the problem is in this part of the code:
while( i < inputEntry.length()) // iterates through word(s)
{
charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
if (charCapture.equals(inputCharacter))
{
++charCountDisplay;
}
++charCount;
++i;
}
I just can't quiet pin down what I'm doing wrong. It seems to me that the charCountDisplay variable reverts to zero after each iteration. Isn't that supposed to be avoided by declaring the variable at the very beginning?... I'm one confused fellow.
This is wrong
charCapture = inputEntry.substring(charCount);
does not return one char
try using inputEntry.charAt(charCount)
Another hint is to define your variables close to where you use them rather than at the top of your method like:
String inputEntry;
inputEntry = scan.nextLine();
Even better would be to do inline
String inputEntry = scan.nextLine();
It will make your code a lot more concise and readable.
A more concise way to do your code is:
Scanner scan = new Scanner(System.in);
System.out.print("Enter some words here: "); // Captures word(s)
String inputEntry = scan.nextLine();
System.out.print("Enter a character here: "); // Captures char
String inputCharacter = scan.nextLine();
// validate
// then
int len = inputEntry.length();
inputEntry = inputEntry.replace(inputCharacter, "");
int newlen = inputEntry.length();
System.out.format("There is %d occurrence(s) of %s in the test.%n",
len - newlen, inputCharacter);
output
Enter some words here: scarywombat writes code
Enter a character here: o
There is 2 occurrence(s) of o in the test.
Here is a complete MVCE:
package com.example.countcharacters;
/**
* EXAMPLE OUTPUT:
* Enter some words here:
* How now brown cow
* Enter a character here:
* abc
* Please enter one character. Try again.
* Enter a character here:
* o
* There are 4 occurrence(s) of o in the text How now brown cow.
*/
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Captures word(s)
String inputEntry;
System.out.println("Enter some words here: ");
inputEntry = scan.nextLine();
// Captures char
char inputCharacter;
while (true) {
System.out.println("Enter a character here: ");
String line = scan.nextLine();
if (line.length() == 1) {
inputCharacter = line.charAt(0);
break;
} else {
// if user is not in compliance
System.out.println("Please enter one character. Try again.");
}
}
// iterates through word(s)
int charCountDisplay = 0;
int i = 0;
while(i < inputEntry.length()) {
char c = inputEntry.charAt(i++);
if (c == inputCharacter) {
++charCountDisplay;
}
}
// Print results
System.out.print("There are " + charCountDisplay +
" occurrence(s) of " + inputCharacter +
" in the text " + inputEntry + ".");
}
}
NOTES:
You can use "char" and "String.charAt()" to simplify your code.
In general, it's preferable to declare variables close to where you use them (rather than at the top).
You can put your test for "one character only" in its own loop.
'Hope that helps!
inputEntry.chars().filter(tempVar -> tempVar == inputCharacter).count() will give you the number of occurrences of a character in the string.
String inputEntry = "text";
char inputCharacter = 'x';
System.out.print("There is " + inputEntry.chars().filter(tempVar -> tempVar == inputCharacter).count() + " occurrence(s) of " + inputCharacter + " in the text " + inputEntry + ".");

Getting length of names in Java with nextLine()

I am very new to Java. I'm in my first Java class and we are just working on the basics. I am supposed to write a program that prompts the user to enter their first, middle, and last name with spaces. Then display the length of the first name, the length of the middle name, the initials, and the full name in all upper case. Here is the class example
Example Output:
Enter a first name middle name and surname
Peggy Sue Palmer
Length of your name: 16 characters
Length of your middle name: 3 characters
Your initials are PSP
PEGGY SUE PALMER
I have worked on some code so far and I am able to get some of the output correctly but when I go to enter Peggy Sue Palmer I have to input the name one at a time with a space at the end and then press enter to input the next name. Also it displays the length of the middle initial as 4 instead of 3. I know that I can have the input all on one line by just having one input String name = input.nextLine(), which allows the input format I am looking for but if I do that I have no clue how to get the length of the middle name or the initials. Sorry this is a dumb question but this is my first Java class and we are just learning the basics.
package tracy2prog1;
import java.util.Scanner;
public class Tracy2prog1 {
public static void main(String[] args) {
//create new scanner class
Scanner input = new Scanner(System.in);
//prompt user to enter first middle and last name
System.out.println("Please enter your first middle and last name with spaces between them");
String firstname = input.nextLine();
String middlename = input.nextLine();
String lastname = input.nextLine();
System.out.println(firstname.length() + middlename.length() + lastname.length());
System.out.println("The length of your middle name is " + middlename.length() + " characters");
System.out.println("Your initials are " + firstname.charAt(0) + middlename.charAt(0) +lastname.charAt(0));
System.out.println(firstname.toUpperCase() + middlename.toUpperCase() + lastname.toUpperCase());
}
}
Here is the updated code that works, only issue is its not counting the spaces in the output of the full name to 16, I am getting 14.
package tracy2prog2;
import java.util.Scanner;
public class Tracy2prog2 {
public static void main(String[] args) {
//create new scanner class
Scanner input = new Scanner(System.in);
//prompt user to enter first middle and last name
System.out.println("Please enter your first middle and last name with spaces between them");
String firstname = input.next();
String middlename = input.next();
String lastname = input.next();
System.out.print("Your name is ");
System.out.println(firstname.length() + middlename.length() + lastname.length() + " characters");
System.out.println("The length of your middle name is " + middlename.length() + " characters");
System.out.println("Your initials are " + firstname.charAt(0) + middlename.charAt(0) +lastname.charAt(0));
System.out.println(firstname.toUpperCase() + " " + middlename.toUpperCase() + " " + lastname.toUpperCase());
}
}
I have to input the name one at a time with a space at the end and then press enter to input the next name.
Let's look at how you get the name:
String firstname = input.nextLine();
String middlename = input.nextLine();
String lastname = input.nextLine();
You are reading three separate lines here which is why you have to press enter between each part of the name. Instead you should read the entire name at once:
String name = input.nextLine();
Now you need to parse the name into separate pieces. I'll leave this for you to figure out how to do. You should look at the documentation of the String class to find any functions which might be helpful to finish solving the problem.
Take a look at how you can do it (one of many examples) - Maybe this will help you in the future, as you probably don't know arrays yet (I didn't know you were in your first class, I went to the problem before reading all - don't do that by the way, sorry!)
import java.util.Scanner;
public class Tracy2prog1 {
public static void main(String[] args) {
//create new scanner class
Scanner input = new Scanner(System.in);
//prompt user to enter first middle and last name
System.out.println("Please enter your first middle and last name with spaces between them");
//Here you will have your names without " ", then its length is 2 characters shorter
String[] names = input.nextLine().split(" ");
//As your names are in an array now, you can get then directly
System.out.println(names[0].length() + names[1].length() + names[2].length());
System.out.println("The length of your middle name is " + names[1].length() + " characters");
System.out.println("Your initials are " + names[0].charAt(0) + names[1].charAt(0) +names[2].charAt(0));
System.out.println(names[0].toUpperCase() + " " + names[1].toUpperCase() + " " + names[2].toUpperCase());
//Peggy Sue Palmer
//Considering you did this: String[] names = input.nextLine().split(" ");
//your array is ["Peggy", "Sue", "Palmer"]
//then array[0] is "Peggy"
//then "Peggy".length == 5
//plus: names[0].charAt(0) means "Peggy".charAt(0) which is "P"
System.out.println("The length of your first name is " + names[0].length() + " characters");
System.out.println("The initial of your first name is " + names[0].charAt(0));
}
}

Java - String Class, Scanner Class

How do I read a sentence (string) from a line of input, and print whether it represents a declarative sentence (i.e., ending in a period), interrogatory (ending in a question mark), or an exclamation (ending in exclamation point) or is not a sentence (anything else)?
import java.util.*;
public class StringDemo {
public static void main(String[] args){
Scanner console = new Scanner(System.in);
// enter a string:
System.out.println("Enter a string: ");
String dog = console.nextLine();
dog = dog.toUpperCase();
System.out.println(dog + " has " + dog.length() +
" letters and starts with " + dog.substring(0, 1));
// enter another string:
System.out.println("Enter another string: ");
String cat = console.nextLine();
cat = cat.toUpperCase();
System.out.println(cat + " has " + cat.length() +
" letters and starts with " + cat.substring(0, 1));
// check contents here
if(dog.equals(cat))
System.out.println("Input Strings are matching ");
else
System.out.println("Input Strings are not matching ");
}
}
Need to use .equals() method to check content equality as below.
import java.util.*;
public class StringDemo {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
// enter a string:
System.out.println("Enter a string: ");
String dog = console.nextLine();
dog = dog.toUpperCase();
System.out.println(dog + " has " + dog.length() +
" letters and starts with " + dog.substring(0, 1));
// enter another string:
System.out.println("Enter another string: ");
String cat = console.nextLine();
cat = cat.toUpperCase();
System.out.println(cat + " has " + cat.length() +
" letters and starts with " + cat.substring(0, 1));
// check contents here
if(dog.endsWith("?"))
System.out.println("Input Strings ends in a question mark ");
}
}

Categories

Resources