Java - String Class, Scanner Class - java

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 ");
}
}

Related

I can't print out letters in my code? If I remove the 0 from the circle brackets the code won't run

So this question is to let the user enter the product id, the name, how much in stock and how much is bought from the store. Everything in the code works just fine but when I enter the letters for the name, only the first letter shows up.
import java.util.Scanner;
public class ProductStock {
public static void main(String[] args) {
{
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
char name = sc.next().charAt(0);
int stock = sc.nextInt();
int sold = sc.nextInt();
sc.close();
System.out.print(id + " " + name + " " + stock + " " + sold);
}
}
}
A char in Java represents a single character. To have a sequence of characters, you should use a String. With using charAt(0) in your snippet, you only take the first character of the name you input, but you want to keep the whole String. By calling next() on the scanner, you actually get a String as the return value, so there is nothing more to do.
The fixed example should look like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
String name = sc.next();
int stock = sc.nextInt();
int sold = sc.nextInt();
System.out.print(id + " " + name + " " + stock + " " + sold);
sc.close();
}
Just a heads up: once you should be aware that calling close() on a Scanner using System.in, you won't be able to use System.in for the rest of the runtime of your program.
in code char name was storing only the first character and because of char which can only store one character and print that one, so you have to use String for storing and displaying a complete text.
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
String name = sc.next();
int stock = sc.nextInt();
int sold = sc.nextInt();
sc.close();
System.out.print(id + " " + name + " " + stock + " " + sold);

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(" ") + ".");
}
}

how to make the whole phrase turn into uppercase and lower case, not just the first word or letter but the entire phrase

i cant seem to make the whole phrase upper case or lower case, only the first word shows and capitalizes
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//declarations
Scanner keyboard = new Scanner(System.in);
//input section
System.out.print("Enter Your First Name: ");
String first = keyboard.next();
System.out.print("Enter Your Middle Name: ");
String middle = keyboard.next();
System.out.print("Enter Your Last Name: ");
String last = keyboard.next();
System.out.print("Enter Your Favorite Phrase: ");
int stringSize;
String phrase = keyboard.next();
String upper = phrase.toUpperCase();
String lower = phrase.toLowerCase();
//processing
String initials = first.substring(0, 1) + middle.substring(0, 1) + last.substring(0, 1);
System.out.println("Your initials are: " + initials);
System.out.println("Your phrase in all CAPS: " + upper);
System.out.println("Your phrase in all lower case: " + lower);
}
}
the output should read:
Enter your first name: Mark
Enter your middle name: Clay
Enter your last name: Dietrich
Enter your favorite saying: Never give up, never surrender!
Your initials are: MCD
Your phrase in all caps: NEVER GIVE UP, NEVER SURRENDER!
Your phrase in all lowercase: never give up, never surrender!
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//declarations
Scanner keyboard = new Scanner(System.in);
//input section
System.out.print("Enter Your First Name: ");
String first = keyboard.nextLine();
System.out.print("Enter Your Middle Name: ");
String middle = keyboard.nextLine();
System.out.print("Enter Your Last Name: ");
String last = keyboard.nextLine();
System.out.print("Enter Your Favorite Phrase: ");
//int stringSize; // dont think you need this
String phrase = keyboard.nextLine();
String upper = phrase.toUpperCase();
String lower = phrase.toLowerCase();
//processing
String initials = first.substring(0, 1) + middle.substring(0, 1) + last.substring(0, 1);
System.out.println("Your initials are: " + initials);
System.out.println("Your phrase in all CAPS: " + upper);
System.out.println("Your phrase in all lower case: " + lower);
}
}

while loop: while sentence does not contain a word

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;}.

String input with Scanner

I am trying to construct a simple 5 word sentence where each word labled and displayed. I.e. Subject-Verb, etc. Then at the end it would do an entire cohesive sentence. Yet When I run the code I get an error and I am not sure why.
public class Sentence {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
System.out.println("Enter Subject:");
int Subject = input.nextInt();
System.out.println("Enter Verb:");
int Verb = input.nextInt();
System.out.println("Enter Adjective:");
String Adjective;
Adjective = input.next();
System.out.println("Enter Object:");
String Object;
Object = input.next();
System.out.println("Enter Adverb:");
String Adverb;
Adverb = input.next();
System.out.println("Subject + Verb + Adjective + Object + Adverb");
}
}
i think that all must read string content (the two first wait for a int) so maybe u want some like this
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
System.out.println("Enter Subject:");
String subject = input.next();
System.out.println("Enter Verb:");
String verb = input.next();
System.out.println("Enter Adjective:");
String adjective;
adjective = input.next();
System.out.println("Enter Object:");
String object;
object = input.next();
System.out.println("Enter Adverb:");
String adverb;
adverb = input.next();
System.out.println(subject + " " + verb + " " + adjective + " " + object + " " + adverb);
}
You said you want to make a cohensive sentence. Now,take a look at your code.You will see that you used integer that makes no sense.
1) You use Scanner but You didn't import Scanner class.That was your first problem. If you want to use Scanner, you should always import "Scanner class" at the start of your code.
2)You wanted to make a cohensive sentence so it should have words in it.But you used integer.You should'a use String and NextLine(); for it.
3)At the end of your code,System.out.println("Subject + Verb + Adjective + Object + Adverb");
Delete all the quotation marks and your code should work well.
So your code should look like this.

Categories

Resources