Getting length of names in Java with nextLine() - java

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

Related

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

Loop not executing more than once

I'm supposed to make a program that continuously accepts desk order data and displays all the relevant information for oak desks that are over 36 inches long and have at least one drawer.
import java.util.*;
public class MangMaxB
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
char ans;
int orderNum=0, length=0, width=0, numDrawer=0, price=1000;
String name;
System.out.print("Do you wish to enter Oak " +
"desk order data? (y/n)");
ans = input.nextLine().charAt(0);
while (ans != 'n')
{
System.out.print("Enter customer name: ");
name=input.nextLine();
System.out.print("Enter order number: ");
orderNum=input.nextInt();
System.out.print("Enter length and width of Oak desk" +
" separated by a space: ");
length = input.nextInt();
width = input.nextInt();
System.out.print("Enter number of drawer/s: ");
numDrawer=input.nextInt();
if ((length>36)&&(numDrawer>=1))
{
if ((length*width)>750)
{
price+= 250;
}
price+= (numDrawer*100);
price+= 300;
System.out.println("\nOak desk order information:\n"
+ "Order number: " + orderNum + "\n"
+ "Customer name: " + name + "\n"
+ "Length: " + length + ", width: "
+ width + ", surface: " + (length*width)
+ "\n" + "Number of drawer/s: " + numDrawer
+ "\nPrice of the desk is P " + price);
}
else
{
System.out.println("\nOak desk order isn't over 36 " +
"inches long and doesn't have a drawer");
}
System.out.print("Any more items? (y/n) ");
ans = input.nextLine().charAt(0);
}
}
}
I was able to enter data and display it but on the second attempt since it is a loop, it didn't work.
It says "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at controlStruc.MangMaxB.main"
how do I fix this?
nextInt() doesn't read the end of the line - just the next integer. You need to call nextLine() after nextInt() if you want to read the remainder of that line.
At present, you're not doing so, so the last nextLine() method just reads the rest of the empty line after the integer, and returns immediately with an empty string, causing the exception.
In this case, putting a nextLine() call here should do the trick:
System.out.print("Enter number of drawer/s: ");
numDrawer=input.nextInt();
input.nextLine(); //Added nextLine() call
Please use like the below,
System.out.print("Any more items? (y/n) ");
input = new Scanner(System.in);
ans = input.nextLine().charAt(0);
beacuse input.nextLine() returns empty string, so when try to get 0th char it returns StringIndexOutOfBoundsException
You need to get a String before calling input.nextLine()
Are you just pressing enter?
ans = input.nextLine().charAt(0);
is throwing this error when it's an empty string. Your exception is clearly telling you this. You need to check if the "nextLine" is an empty string or not.
Clearly according to documentaion:
nextLine()-Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
nextInt()-Scans the next token of the input as an int.
And henceforth ans = input.nextLine() in your code is returning you with '' and char(0) leading for StringIndexOutOfBoundsException.

Java - Adding constraints

I have made this class for fun, and now I want to add some constraints and if statements. But don't know how.
Problem 1) I don't know how to do an if statement on System.out.print outputs. Say, if the user enter more than 50 characters then they'll be stopped.
I know how to do this in MySQL but not in Java as I'm very inexperienced ATM. :|
Problem 2) I also want to restrict myself from entering digits if it's nextLine, or text if it's nextInt.
Can anyone help me on these two problems?
import java.util.Scanner;
class AppForm {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name... ");
System.out.println("Your name is " + sc.nextLine());
System.out.print("Enter your age... ");
System.out.println("Your age is " + sc.nextInt());
}
}
Thanks.
You should start by breaking apart the input and output code by storing the result of nextLine() in a variable:
System.out.print("Enter your name... ");
String line = sc.nextLine();
System.out.println("Your name is " + line);
You can then perform any check you need on the line string variable. The typical paradigm in the case of an interactive program is to print out an error message and ask the user to repeat the entry in case of invalid input:
System.out.print("Enter your name... ");
String line = sc.nextLine();
while (line.length() > 50) {
System.out.println("Error: you entered more than 50 characters");
// Ask the user for their name again...
System.out.print("Enter your name... ");
line = sc.nextLine();
}
System.out.println("Your name is " + line);
Unfortunately there is no way to prevent the user from typing invalid characters - you can only check the content of the line after the user has finished typing and your program receives the typed line.
I would recommend at taking a look at while loops.
Some possibilities:
String name;
do {
System.out.print("Enter your name... ");
String line = sc.nextLine();
while (StringUtils.isEmpty(name) || name.length() > 50)
Or:
String name;
while (StringUtils.isEmpty(name)) {
System.out.print("Enter your name... ");
name = sc.nextLine();
if (name.length >= 50) {
System.out.println("Max name length is 50");
}
}
But there are plenty of flow control options.

Categories

Resources