Loop not executing more than once - java

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.

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

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

Do While Loop Skipping User Input

I want it to loop again when the user enters "Y" or "y" and quit when they enter "N" or "n". The quitting option works, however, when they enter Y/y, it shows the first system out, but does not let the user pick which operation they wish to do. Instead the option to continue pops up again and inhibits the user from making any choice.
Here is the code:
import java.util.Scanner;
public class Calc2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double numOne, numTwo, ans;
String option;
do {
System.out.println(
"For addition press '1', for subtraction press '2', for division press '3', for multiplication press '4'");
String choice = input.nextLine();
if (choice.contains("1")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne + numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
}
else if (choice.contains("2")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne - numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
} else if (choice.contains("4")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne * numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
} else if (choice.contains("3")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne / numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
}
System.out.println("Press 'Y' to continue or 'N' to quit.");
option = input.next();
} while (option.equals("Y") || option.equals("y"));
if (option.equals("N") || option.equals("n")) {
System.out.println("Thank you. ");
}
}
}
If anyone can help me, it'd be greatly appreciated. Thanks!
Please change below line in your code
String choice = input.nextLine();
from this code
String choice = input.next();
There trouble you see here is the use of nextLine after nextDouble. Check here [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
Your problem appears to be at the beginning of your do-while loop as such:
System.out.println(
"For addition press '1', for subtraction press '2', " +
"for division press '3', for multiplication press '4'");
String choice = input.nextLine();
This is the only place where you use nextLine method (rahter than next or nextDouble and so on). This means that after you've read the option argument at the end of the iteration:
option = input.next();
there's still a new line character that hasn't been read by the scanner. When you do nextLine() in the next iteration it reads the new line character before the user has any chance to input something).
Either change that first line to input.next() as well, or make sure every time you read a value, you clear the new line character (for instance by reading nextLine and then casting the value - this would also allow you to do input validations).

Program does not ask for gender although it asks for everything else

Can someone tell me why my program does not ask for gender when I run it although it asks for everything else?
import java.util.*;
public class registration {
public static void main (String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter first name");
String firstName=in.nextLine();
System.out.println ("Enter surname");
String surname=in.nextLine();
System.out.println ("Enter address");
String address=in.nextLine();
System.out.println ("Enter age");
int age=in.nextInt();
System.out.println ("Enter gender");
String gender=in.nextLine();
System.out.println ("Enter telephone contact");
String teleContact=in.nextLine();
System.out.println ("Enter P for Platinum, G for Gold or S for Silver membership type");
String memberType=in.nextLine();
int birth;
birth=2014-age;
String surname2;
surname2 = surname.toUpperCase();
String memberId;
memberId=memberType + surname2 + birth;
System.out.printf ("MEMBER ID : " + memberId + " ");
System.out.printf ("FIRSTNAME : " + surname + " ");
System.out.printf ("SURNAME : " + firstName + " ");
System.out.printf ("AGE : " + age + " ");
System.out.printf ("GENDER : " + gender + " ");
System.out.printf ("TELEPHONE : " + teleContact + " ");
System.out.printf ("MEMBERSHIP TYPE : " + memberType + " ");
System.out.printf ("ADDRESS : " + address + " ");
}
}
nextInt() is not consuming the new line character you are entering, so it is then consumed by the following in.nextLine(), and therefore you don't get the chance to enter the gender.
I suggest you change the nextInt for nextLine() and then call Integer.parseInt() on that line, catching the necessary exception, in case the line is not a valid number.
int age=in.nextInt();
Is only consuming the "int" part.
The
String gender=in.nextLine();
Consumes the (empty) newline and moves on.
You need to consume both before you prompt for Gender.
The problem is that nextInt() doesn't expect a newline, so the input is stalled pending a newline. Change the nextInt() to nextLine() and parse the int, and it'll work.
put in.nextLine() after System.out.println ("Enter gender"); line.Because after integer it takes newline as string therefore it just skip by pressing "enter".

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