Skipping An Input line in java - java

So I have an addItem() method where I can add a book, tape, or cd object to my inventory. To store the book, tape, or cd object, I obtain the title, author, and price of the object from the user. HOWEVER, when I run the program, it skips the "please enter the title: " and goes right to "please enter the author:". Then when I have it show the information, the title field is 'null'.
static void addItem(int type) {
String title;
String author;
Double price;
System.out.println("Please enter the title");
title = keyboard.nextLine()
System.out.println("Please enter the author");
author = keyboard.nextLine();
System.out.println("Please enter the price");
price = keyboard.nextDouble();
if(type == 0){
Book BookStoreItem;
BookStoreItem = new Book(title, author, price);
System.out.println("You've entered:");
System.out.println("Title: " + BookStoreItem.getTitle());
System.out.println("Author: " + BookStoreItem.getAuthor());
System.out.println("Price: " + BookStoreItem.getPrice());
}
if(type == 1){
Tape BookStoreItem;
BookStoreItem = new Tape(title, author, price);
System.out.println("You've entered:");
System.out.println("Title: " + BookStoreItem.getTitle());
System.out.println("Author: " + BookStoreItem.getAuthor());
System.out.println("Price: " + BookStoreItem.getPrice());
}
if(type == 2){
CD BookStoreItem;
BookStoreItem = new CD(title, author, price);
System.out.println("You've entered:");
System.out.println("Title: " + BookStoreItem.getTitle());
System.out.println("Author: " + BookStoreItem.getAuthor());
System.out.println("Price: " + BookStoreItem.getPrice());
}
}//end of addItem()
Here is a sample output:
Press:
0 To add a book to the inventory
1 To add a tape to the inventory
2 To add a Cd to the inventory
Please enter your choice: 0
Please enter the title:
Please enter the author: John Smith
Please enter the price: 55.50
Title: null
Author: John Smith
Price: 55.5
Here's an update with the menu on it:
static void printMenu() {
System.out.println("\nPress:");
System.out.println("\t" + ADD_BOOK + "\tTo add a book to the inventory\n");
System.out.println("\t" + ADD_TAPE + "\tTo add a tape to the inventory\n");
System.out.println("\t" + ADD_CD + "\tTo add a CD to the inventory\n");
System.out.println("\t" + SHOW_ITEM_LIST + "\tTo display a list of available books\n");
System.out.println("\t" + SEARCH_ITEM + "\tTo search for a specific book\n");
System.out.println("\t" + QUIT + "\tTo exit\n");
}
and with the choices:
static void runBookStoreApplication() {
int userChoice = QUIT;
String quitMessage = "\nThank you for using the BookStoreApplication!";
String invalidOptionMessage = "\nInvalid option!";
do{
printMenu();
userChoice = getUserChoice();
switch (userChoice) {
case ADD_BOOK:
addItem(0);
break;
case ADD_TAPE:
addItem(1);
case ADD_CD:
addItem(2);
case SHOW_ITEM_LIST:
showItemList();
break;
case SEARCH_ITEM:
searchItem();
break;
case QUIT:
System.out.println(quitMessage);
break;
default:
System.out.println(invalidOptionMessage);
}
} while(userChoice != QUIT);
}//end of runBookStoreApplication
with getUserChoice:
static int getUserChoice() {
int choice;
System.out.print("Please enter your choice: ");
choice = keyboard.nextInt();
return choice;
}

You didn't show us the code where you ask "Please enter your choice:", but I bet that you are using keyboard.nextInt() or something. This method does not consume all the line, just the integer 0, so when you call nextLine() afterwards it actually returns immediately with the rest of the line (that is, with an empty string).
To solve this, call keyboard.nextLine() before your method.
Edit:
now that you have put your getUserChoice() method, you can see that there is a call to keyboard.nextInt(), as I presumed. Just call nextLine() after it so you consume all the line and the scanner is ready for your next input:
static int getUserChoice() {
int choice;
System.out.print("Please enter your choice: ");
choice = keyboard.nextInt(); // consume just the integer
// consume the rest of the line
keyboard.nextLine();
return choice;
}

Related

I am trying to make my switch case loop back again if they get the default

//Choice of choosing a dog or a cat
String pet = input.next();
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
}
case 'b' -> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
}
default -> System.out.println("That is not a valid option. Please choose again.");
}
input.close();
}
I can't find a loop to use that would bring it back to case a and repeatedly until the user answers using one of the choices, Any help would be awesome! Thanks
Using do while loop is a simple way to solve it.
I used a variable repeat to check, If I need to ask for the input again or not
Also, note that now even If I add another case(say case 'c') I don't need to modify condition for my do while loop
boolean repeat;
do {
String pet = input.next();
repeat = false;
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
}
case 'b'-> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
}
default: System.out.println("That is not a valid option. Please choose again.");
repeat = true;
}
} while(repeat);
input.close();
Looping is good solution but you can also use the Recessive methods in java.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome To The Choices Game... ");
System.out.println("Please enter your name: " );
String playerName = input.nextLine();
System.out.println("What is " + playerName + "'s" + " favorite pet?");
System.out.println("a. Dog \nb. Cat");
//Choice of choosing a dog or a cat
method();
input.close();
}
public void method()
{
String pet = input.next();
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
}
case 'b' -> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
}
default -> System.out.println("That is not a valid option. Please choose again.");
method();
}
}
To loop the entire switch-case section, you can try putting it in a do-while loop. As for the condition to use with the do-while block you could try:-
do {...}while(pet.charAt(0)!='a' || pet.charAt(0)!='b');
I am providing you with a possible solution below:-
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome To The Choices Game... ");
System.out.println("Please enter your name: " );
String playerName = input.nextLine();
System.out.println("What is " + playerName + "'s" + " favorite pet?");
System.out.println("a. Dog \nb. Cat");
//Choice of choosing a dog or a cat
do{
String pet = input.next();
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
break;}
case 'b' -> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
break;}
default -> System.out.println("That is not a valid option. Please choose again.");
}
}while(pet.charAt(0)!='a' && pet.charAt(0)!='b');
input.close();
}

I am trying to make my switch case loop back again if they get the user gets the default

I can't find a loop to use that would bring it back to the beginning of the switch case and repeatedly until the user answers using one of the choices, Any help would be awesome! Thanks. (I have also tried using a do-while loop that someone suggested but it just seems to spam the default.) ((which I left in the code))
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome To The Choices Game... ");
System.out.println("Please enter your name: ");
String playerName = input.nextLine();
System.out.println("What is " + playerName + "'s" + " favorite pet?");
System.out.println("a. Dog \nb. Cat");
//Choice of choosing a dog or a cat
String pet = input.next();
do {
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
break;
}
case 'b' -> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
break;
}
default -> System.out.println("That is not a valid option. Please choose again.");
}
} while (pet.charAt(0) != 'a' && pet.charAt(0) != 'b');
input.close();
}
You need to take the input for Cat/Dog (option a or option b) inside the do loop so that after wrong input code can ask for updated input. As below:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome To The Choices Game... ");
System.out.println("Please enter your name: ");
String playerName = input.nextLine();
System.out.println("What is " + playerName + "'s" + " favorite pet?");
System.out.println("a. Dog \nb. Cat");
// Here is change in code
String pet = null;
do {
// Choice of choosing a dog or a cat
// Here is change in code
pet = input.next();
switch (pet.charAt(0)) {
case 'a': {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
break;
}
case 'b': {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
break;
}
default: {
System.out.println("That is not a valid option. Please choose again.");
}
}
} while (pet.charAt(0) != 'a' && pet.charAt(0) != 'b');
input.close();
}

Add method and while loop do not execute properly

This program is a contact book. There is a contact class and contact book class. When I execute case 2, the add method from the contact book class does not let me enter name and phone number individually. "Enter a name" and "Enter an address" appear at the same time.
Here is the switch case in the main method:
while (!done)
{
ContactBook cb = new ContactBook();
System.out.println("1) List all contacts" + "\n" + "2) Add a contact"
+ "\n" + "3) Update a contact" + "\n" + "4) Remove a contact" +
"\n" + "5) Quit");
userChoice = sc.nextInt();
switch (userChoice)
{
case 1:
c.toString();
break;
case 2:
cb.add(sc);
break;
case 3:
cb.update(sc);
break;
case 4:
cb.remove(sc);
}
if (userChoice == 5);
{
done = true;
}
}
}
Here is the add method from the contact book class:
public void add (Scanner sc)
{
Contact c = new Contact(name, address, phone, email);
System.out.println("Enter a name: ");
c.setName(sc.nextLine());
System.out.println("Enter an address: ");
c.setAddress(sc.nextLine());
System.out.println("Enter a phone number: ");
c.setPhone(sc.nextLine());
System.out.println("Enter an email: ");
c.setEmail(sc.nextLine());
entries = Arrays.copyOf(entries, entries.length + 1);
}
You need to change the following:
userChoice = sc.nextInt();
to
userChoice = Integer.valueOf(sc.nextLine());
I think this should fix your problem
System.out.print("Enter a name: ");
c.setName(sc.nextLine());
System.out.println()

Problems with try/catch java

I am having trouble using this try/catch statement. I am trying to use it to throw an error message that says, "Please enter an integer!" if the user enters a letter. The first one I used worked, but it ends up taking 2 lines of user input rather than just one, so it essentially skips over a question that was supposed to be asked. After that, none of the other ones work at all, they just get completely skipped. I also need to do the same thing for user input where if a user enters an integer where a letter should be, it throws an error message that says "Please enter a string!". I know I am pretty close!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean validInput = false;
int val = 0;
System.out.print("Enter your first name: ");
String firstName = input.nextLine();
System.out.print("Enter your last name: ");
String lastName = input.nextLine();
System.out.print("Enter your address: ");
String address = input.nextLine();
System.out.print("Enter your city: ");
String city = input.nextLine();
System.out.print("Enter your state: ");
String state = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.nextLine();
}
}
System.out.print("Enter amount owed: ");
String amount = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.next();
}
}
System.out.print("Enter your payment amount: ");
String payment = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.next();
}
}
System.out.print("Enter the date of payment: ");
String date = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.next();
}
}
System.out.println("\t\t\t\t\t" + "XYZ Hospital");
System.out.println();
System.out.println("Name Information" + "\t\t\t\t" + "Address" + "\t\t\t\t\t\t" + "Payment");
System.out.println();
System.out.println("Last" +"\t"+ "First" + "\t\t\t" + "Address Line 1" + "\t" + "City" + "\t" + "State" + "\t" + "Zip" + "\t" + "Amount Owed" + "\t" + "Payment Amount" + "\t" + "Payment Date");
System.out.println();
System.out.println(lastName + " " + firstName + "\t" + address + " " + city + ", " + state + " " + zip + "\t" + amount + "\t\t" + payment +"\t\t"+ date);
System.out.print("Would you like to enter abother patient? Type Yes or No: ");
String userInput = input.nextLine();
if (userInput.equals("Yes")) {
while (userInput.equals("Yes")) {
System.out.print("Enter your first name: ");
String firstName2 = input.nextLine();
System.out.print("Enter your last name: ");
String lastName2 = input.nextLine();
System.out.print("Enter your address: ");
String address2 = input.nextLine();
System.out.print("Enter your city: ");
String city2 = input.nextLine();
System.out.print("Enter your state: ");
String state2 = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip2 = input.nextLine();
System.out.print("Enter amount owed: ");
String amount2 = input.nextLine();
System.out.print("Enter your payment amount: ");
String payment2 = input.nextLine();
System.out.print("Enter the date of payment: ");
String date2 = input.nextLine();
System.out.println("\t\t\t\t\t" + "XYZ Hospital");
System.out.println();
System.out.println("Name Information" + "\t\t\t\t" + "Address" + "\t\t\t\t\t\t" + "Payment");
System.out.println();
System.out.println("Last" +"\t"+ "First" + "\t\t\t" + "Address Line 1" + "\t" + "City" + "\t" + "State" + "\t" + "Zip" + "\t" + "Amount Owed" + "\t" + "Payment Amount" + "\t" + "Payment Date");
System.out.println();
System.out.println(lastName2 + " " + firstName2 + "\t" + address2 + " " + city2 + ", " + state2 + " " + zip2 + "\t" + amount2 + "\t\t" + payment2 +"\t\t"+ date2);
System.out.print("Would you like to enter another patient? Type Yes or No: ");
userInput = input.nextLine();
}
}
else if (userInput.equals("No")) {
System.out.println("Goodbye");
}
You don't reset validInput to False after your first while loop. So it doesn't enter the next.
You should take input in catch block comment input.nextLine() in catch block then it should work properly
I have added explanation in the code itself
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean validInput = false;
int val = 0;
System.out.print("Enter your first name: ");
String firstName = input.nextLine();
System.out.print("Enter your last name: ");
String lastName = input.nextLine();
System.out.print("Enter your address: ");
String address = input.nextLine();
System.out.print("Enter your city: ");
String city = input.nextLine();
System.out.print("Enter your state: ");
String state = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip = input.nextLine();
while (!validInput) {
try {
val = input.nextInt();
validInput = true; //if exception occurs this line wont be executed
} catch (Exception e) {
System.out.println("Please enter an integer!");
// input.nextLine(); --remove this line
}
}
System.out.print("Enter amount owed: ");
String amount = input.nextLine();
//reset the value of validInput
//validInput will true after the execution of above while loop
validInput = false;
while (!validInput) {
try {
val = input.nextInt();
validInput = true; //if exception occurs this line wont be executed
} catch (Exception e) {
System.out.println("Please enter an integer!");
// input.next(); -- remove this line
}
}
}
A quick solution maybe, I've used Scanner.hasNextInt to check what the next token is before getting required ints:
import java.util.Scanner;
public class java_so {
private static int privateGetInt(String request, Scanner input) {
// cant be false, but we return when done.
while (true) {
// print the question
System.out.println(request);
// check what the next token is, if an int we can then retrieve
if (input.hasNextInt() == true) {
int out = input.nextInt();
input.nextLine(); // clear line, as nextInt is token orientated, not line,
return out;
} else {
// else for when not an int, clear line and try again
input.nextLine();
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your first name: ");
System.out.println(input.nextLine());
// call function above
System.out.println(privateGetInt("enter an Int", input));
System.out.print("Enter your last name: ");
System.out.println(input.nextLine());
System.out.print("Enter your address: ");
System.out.println(input.nextLine());
}
}
It seems a bit like the problem may have been after a call to input.nextInt you haven't got rid of the rest of the line (which is probably just "\n") so the next call to input.getLine() only gets that, jumping on one. Following input.getInt with input.getLine clears this.

cant get do while loop to work right-java

My problem is that when I run this program I have to press 2 twice, or 3 three times to get the else if statements to run. I have tried switching the input to string and it has the same issues. (you can ignore all the code except the (sc.nextInt()==1)/(sc.nextInt()==2)/(sc.nextInt()==3)) Those are where I'm having problems. Thanks
Scanner sc = new Scanner(System.in);
int running = 0;
do
{
System.out.println("What would you like to do?");
System.out.println("(1)Enter hourly employee");
System.out.println("(2)Enter commissionary employee");
System.out.println("(3)Terminate program");
System.out.println();
if (sc.nextInt()==1){
System.out.println("Enter their first name. \n");
hour.firstName= sc.next();
System.out.println("Enter their last name. \n");
hour.lastName= sc.next();
System.out.println("Enter their Id #. \n");
hour.id= sc.nextInt();
System.out.println("Enter their wage amount. \n");
hour.wage= sc.nextInt();
System.out.println("Enter how many hours they will be working. \n");
hour.hrs= sc.nextInt();
System.out.println("employee "+ hour.id + "'s name is " + hour.firstName + " "+ hour.lastName + " their id is "+ hour.id);
System.out.println("employee "+ hour.id + "'s wage is " + hour.wage + "$ and will be working "+ hour.hrs +" hours per week.");
running++;
}
//have to type 2 twice here
else if (sc.nextInt()== 2){
System.out.println("Enter their first name. \n");
com.firstName= sc.next();
System.out.println("Enter their last name. \n");
com.lastName= sc.next();
System.out.println("Enter their Id #. \n");
com.id= sc.nextInt();
System.out.println("Enter their base salary. \n");
bcom.baseSalary= sc.nextInt();
System.out.println("Enter their wage commission rate. \n");
com.cRate= sc.nextInt();
System.out.println("Enter their expected gross sales goal. \n");
com.gSales= sc.nextInt();
System.out.println("employee "+ com.id + "'s name is " + com.firstName + " "+ com.lastName + " their id is "+ com.id);
System.out.println("employee "+ com.id + "'s base salary is "+ bcom.baseSalary + "$ their commission rate is \n" + com.cRate + "% and is estimated to make "+ com.gSales +"$ in gross sales.");
running++;
}
//have to type 3 three times here
else if (sc.nextInt()== 3)
{
running++;
}
}while(running < 1);
Scanner sc = new Scanner(System.in);
int running = 0;
do
{
System.out.println("What would you like to do?");
System.out.println("(1)Enter hourly employee");
System.out.println("(2)Enter commissionary employee");
System.out.println("(3)Terminate program");
System.out.println();
int i = sc.nextInt();
if (i==1){
System.out.println("Enter their first name. \n");
hour.firstName= sc.next();
System.out.println("Enter their last name. \n");
hour.lastName= sc.next();
System.out.println("Enter their Id #. \n");
hour.id= sc.nextInt();
System.out.println("Enter their wage amount. \n");
hour.wage= sc.nextInt();
System.out.println("Enter how many hours they will be working. \n");
hour.hrs= sc.nextInt();
System.out.println("employee "+ hour.id + "'s name is " + hour.firstName + " "+ hour.lastName + " their id is "+ hour.id);
System.out.println("employee "+ hour.id + "'s wage is " + hour.wage + "$ and will be working "+ hour.hrs +" hours per week.");
running++;
}
//have to type 2 twice here
else if (i== 2){
System.out.println("Enter their first name. \n");
com.firstName= sc.next();
System.out.println("Enter their last name. \n");
com.lastName= sc.next();
System.out.println("Enter their Id #. \n");
com.id= sc.nextInt();
System.out.println("Enter their base salary. \n");
bcom.baseSalary= sc.nextInt();
System.out.println("Enter their wage commission rate. \n");
com.cRate= sc.nextInt();
System.out.println("Enter their expected gross sales goal. \n");
com.gSales= sc.nextInt();
System.out.println("employee "+ com.id + "'s name is " + com.firstName + " "+ com.lastName + " their id is "+ com.id);
System.out.println("employee "+ com.id + "'s base salary is "+ bcom.baseSalary + "$ their commission rate is \n" + com.cRate + "% and is estimated to make "+ com.gSales +"$ in gross sales.");
running++;
}
//have to type 3 three times here
else if (i== 3)
{
running++;
}
}while(running < 1);
because each time u write nextInt(), it will wait for input from User. So, just try to catch 1 input from User, then just check whats the input is.
You are reading a 2nd time from sc.nextInt() in your 'else'.
Read once before the 'if', then test the value.
Whenever you call nextInt(), the process waits and reads your input once.
So, the first if(sc.nextInt()==1) reads your input once, and you need to type the second time to reach else if (sc.nextInt()==2).
To solve this, try following structure:
int input = sc.nextInt();
if (input == 1) {
} else if (input == 2) {
} else if (input == 3) {
}

Categories

Resources