I'm currently doing a java project. The project involves a database about NHL Statistics and about accessing bits of information from the database through user input. I'm using a while loop to ask for user input in multiple circumstances, such as asking for the number of penalties received, the number of goals scored, amount of points etc. I am having difficulty with one specific part, it asks the user input for which statistic they want (points, goals, assists, penalties, assists, player, club). After that, if the user types player as their choice, then the system is supposed to ask the user which players statistics they wish to see. The problem is that since I'm using a while loop after the user inputs the first time, the loop is executed and the program ends before the player can input the second time. Any help would be appreciated, here is my code:
import java.util.Scanner;
import nhlstats.NHLStatistics;
public class NhlStatisticsPart2 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("NHL statistics service");
while (true) {
System.out.println("");
System.out.print("command (points, goals, assists, penalties, player, club, quit): ");
String command = reader.nextLine();
if (command.equals("quit")) {
break;
}
if (command.equals("points")) {
NHLStatistics.sortByPoints();
NHLStatistics.top(10);
// Print the top ten players sorted by points.
} else if (command.equals("goals")) {
NHLStatistics.sortByGoals();
NHLStatistics.top(10);
// Print the top ten players sorted by goals.
} else if (command.equals("assists")) {
NHLStatistics.sortByAssists();
NHLStatistics.top(10);
// Print the top ten players sorted by assists.
} else if (command.equals("penalties")) {
NHLStatistics.sortByPenalties();
NHLStatistics.top(10);
// Print the top ten players sorted by penalties.
} else if (command.equals("player")) {
System.out.println("Which player statistics?");
NHLStatistics.searchByPlayer(command);
// Ask the user first which player's statistics are needed and then print them.
} else if (command.equals("club")) {
// Ask the user first which club's statistics are needed and then print them.
// Note: When printing statistics they should be ordered by points (so the players with the most points come first).
}
}
}
}
This is the message I receive:
command (points, goals, assists, penalties, player, club, quit): player
Which player statistics?
command (points, goals, assists, penalties, player, club, quit):
As can be seen, instead of allowing the user to enter which player's statistic they want to see, the program goes back to the previous questions without allowing for user input. Is there a way, whereby the user can answer the question (Which player statistics?) without the loop executing?
Well you need to ask the user to input the player. So you need to use the scanner to scan another value. If you do it when you are in the if condition it won't continue until the user inputs the value.
.....
} else if (command.equals("player")) {
System.out.println("Which player statistics?");
command = reader.nextLine(); //Read again from the input
NHLStatistics.searchByPlayer(command); //now use that second value
}
.......
Related
I'm fairly new to Java and I'm facing some difficulties. So i've been instructed to run a program where you will login in to a system by entering a pin number and school name. You have 3 attempts for each until a message prompts that tells you that the login has failed. My problem is. Everything is fine but in PIN SECTION, (userInputPin==PIN) section, it automatically inputs "Attempt #2 - Enter your school name - Incorrect. upon first correct attempt. When writing the correct school name, it shows login failed as well when it should notify that you have logged in. What's the error?
Note:Ignore comment, I'll fix them.
public class Login {
public static final int PIN = 1234; //Declaring constant for fixed PIN
//Declaring constant for first school name
public static final String FIRST_SCHOOL = "St. Charles";
public static void main(String[] args) {
Scanner kb = new Scanner (System.in); //Declaring scanner object
int attempts = 1; //Declaring variable for attempt number
//Printing first paragraph section of the program
System.out.println("This program simulates logging into a bank account,"
+ "\nasking certain questions for security.\n");
// PIN Section
while(attempts<=3) //While loop
{
System.out.print("Attempt #"+attempts+" - Enter PIN: ");
int userInputPin = kb.nextInt(); //User inputs pin number
//Conditional situations
if(userInputPin==PIN)
{
attempts=1;
while(attempts<=3)
{
System.out.print("\nAttempt #"+ attempts+" - Enter your first school: ");
String userInputSchool = kb.next();
//Conditional situations
if(userInputSchool.equals(FIRST_SCHOOL))
{
System.out.println("\nYou're logged in.");
}
else{
if(attempts==3)
{
System.out.println("\nLogin failed.");
}
else
{
System.out.println("Incorrect.\n");
}
}
attempts++;
}
}
else{
if(attempts==3){
System.out.println("\nLogin failed.");
}
else{
System.out.println("Incorrect.\n");
}
}
attempts++; //Increments attempt by 1 when PIN is incorrect
}
Ah yes, ye ol' Scanner. I can't begin to tell you how many times I've suffered the same problem.
The problem lies in the fact that the nextInt() function sometimes regards the enter key as another token. So when you input the first value, nextInt() recognizes the number inputted. But after printing the second message, the scanner object still has the enter key stored in it. The only way to move forward is to empty the object like so:
if(kb.hasNext()) kb.nextLine();
Insert this after each time you input a number.
I'm writing a program that gathers a first name, a last name, and the sales figure of an employee. I have all the basics working perfectly but I have 1 issue. In my while loop I have programmed it so if the user enters "add" then it will call a method I made in a different class and add whatever number they entered to the employees current sales total. The code works, but for some reason when I test it I have to enter "add" twice before it runs; is there anyway I can fix this?(I left out a bunch of code in the middle as I feel it wasn't important to this question.)
//local constants
final int QUIT = -1;
final String ADD = "add";
final String SUBTRACT = "subtract";
//local variables
int soldItems;
String addition;
String subtraction;
String nameFirst;
String nameLast;
//while the input is not QUIT
while(soldItems != QUIT)
{
//Clear screen then prompt the user to add or subtract
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.print(Util.setLeft(35, "Add or Subtract: "));
addition = Keyboard.readString();
subtraction = Keyboard.readString();
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//if the user enters add the program will add to the employee total
if(addition.equals(ADD))
{
info.addition(soldItems);
}
//else the program will subtract from the employee total
else
{
info.subtraction(soldItems);
}
//Displays the employee information and prompts the user for the next sales figure
System.out.println(info.toString());
System.out.println();
System.out.print(Util.setLeft(40, "Input the next Sales Figure: "));
soldItems = Keyboard.readInt();
}//end while
//clear screen
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//End of program message and Final employee information
System.out.print(Util.setLeft(45, "Final Employee Information"));
System.out.println(info.toString());
addition = Keyboard.readString();
subtraction = Keyboard.readString();
You dont need to use two of them, just use input = Keyboard.readString(); and then check the input and process it accordingly.
I am taking the first Java class and working on my second project. The project is about creating an program as a network of rooms on a virtual three-dimensional work area. Each room provides a virtual environment that together can be assemble into a simulated or virtual world.
Basically, the beginning of the program, I used while loop, and at the end I want to ask user if he/she wants to quit the program, and print a thank you message. However, the while loop does not work. My program quit no matter I entered y or n. Below is my codes.
import java.util.Scanner;
public class Project
{
public static void main(String[] args)
{
Map map = new Map();
int floor = 0;
int row = 0;
int col = 0;
String input = " ";
Scanner scan = new Scanner(System.in);
// Begin user dialog. Welcome message
System.out.println("Welcome to the L.A Underground! (Verson 1.1)");
System.out.println();
String choice = "y";
while(!input.equalsIgnoreCase("quit"))
{
input = scan.nextLine().toLowerCase();
// My codes are here
if (input.equals("south")
{statement}
else
System.out.println("You can't go that way.");
else if (input.equals("quit"))
{ // See if user wants to continue
System.out.println("Do you wish to leave the Underground (Y/N)? >");
choice = scan.nextLine();
System.out.println();
}
// if user enters other words than quit
else
System.out.println("I don't recognize the word '" + input +"'");
}
System.out.println("Thank you for visiting L.A Underground.");
}
}
When I typed "quit" the console printed the message: "Do you wish to leave the Underground? (Y/N)? >". I tried Y/N (y/n) the program terminated. Any help is appreciated. Thank you.
Updated: Sorry for the confusion. What I wanted the program to run is when the user types "quit", the message will print out "Do you wish to leave the Underground (Y/N)?>?" , and if the user types "hello", the message will be "I don't understand the word 'hello'". And when the user type y, the program will quit, otherwise (type n), the program will start over again.
Ask for user input inside of your loop. If input.equalsIgnoreCase("quit"), then prompt the user an "are you sure" message. If the input.equalsIgnoreCase("y"), then break the loop, otherwise, keep going.
Scanner scan = new Scanner(System.in);
String input;
// Begin user dialog. Welcome message
System.out.println("Welcome to the L.A Underground! (Verson 1.1)");
System.out.println();
while (true) {
input = scan.nextLine();
if (input.equalsIgnoreCase("quit")) {
System.out.print("Do you wish to leave the Underground (Y/N)? >");
if (scan.nextLine().equals("y")) {
break;
}
}
// input wasn't "quit", so do other stuff here
}
System.out.println("Thank you for visiting L.A Underground.");
Your code loops until it gets "quit" ... then asks for "yes/no" ... then simply exits, regardless.
You need to change your loop, so that it includes BOTH "MY CODES HERE" AND the "quit y/n" check.
EXAMPLE:
...
boolean done = false;
while(!done) {
//MY CODES ARE HERE
if (input.equalsIgnoreCase("quit") && getYesNo ()) == 'y') {
done = true;
}
}
"getYesNo()" is a method you write. For example:
char getYesNo () {
System.out.print("Do you wish to leave the Underground (Y/N)? >");
String line = scan.nextLine();
return line.charAt(0);
}
In the code you've posted, your loop is being controlled by the condition !input.equalsIgnoreCase("quit"). That is, if input is "quit", the loop is terminated.
But the following block is executed only if input is "quit":
if (input.equals("quit"))
{
// See if user wants to continue
System.out.println("Do you wish to leave the Underground (Y/N)? >");
choice = scan.nextLine();
System.out.println();
}
So if this block is executed, !input.equalsIgnoreCase("quit") evaluates to false and the loop is terminated. And that's not what you want.
Now that you know what's wrong, fixing it is easy. Check the value of choice in the above if block: if choice is not yes, don't quit i.e. reset input to a default value.
I've pasted the working code here on pastebin.
I'm making a console-based game of black jack that prompts the user asking him/her if he/she wants to: 'h' for hit, 's' for stay, or 'q' for quit. I'm using the Scanner class to receive input from the user in a while loop. The code works the first time it prompts the user and receives input, but it never works the second time. After the second prompt comes up, no matter what the user types, the program just waits and does nothing even though it's still running. I've been trying to get this to work for hours and have read the Java Docs, many SO questions, etc. Here's the relevant code:
public void gameloop() {
while (thedeck.cards.size() >= 1) {
prompt();
}
}
public void prompt() {
String command = "";
Boolean invalid = true;
System.out.println("Enter a command - h for hit, s for stay, q for quit: ");
Scanner scanner = new Scanner(System.in);
while (invalid) {
if (scanner.hasNext()) {
command = scanner.next();
if (command.trim().equals("h")) {
deal();
invalid = false;
} else if (command.trim().equals("s")) {
dealerturn();
invalid = false;
} else if (command.trim().equals("q")) {
invalid = false;
System.exit(0);
} else {
System.out.println("Invalid input");
scanner.next();
}
}
}
scanner.close();
}
Here's what the code outputs:
Dealer has shuffled the deck.
Dealer deals the cards.
Player's hand:
Three of Clubs: 3
Five of Clubs: 5
Enter a command - h for hit, s for stay, q for quit:
h
Dealer deals you a card:
Player's hand:
Three of Clubs: 3
Five of Clubs: 5
Queen of Hearts: 10
Enter a command - h for hit, s for stay, q for quit:
h (Program just stops here, you can keep entering characters,
but it does nothing even though the code is still running)
Any idea as to what's going wrong would be greatly appreciated. I also realize the while loop is a little ugly, but I just want to get this program in working condition before I start to revamp any code.
From the documentation for Scanner.close:
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
Here you close your scanner, and this causes System.In to be closed, which means you can't read any more input:
scanner.close();
It is better to open the scanner once and reuse it. Close it only when are sure you have finished reading all input, or are closing your application.
I'm trying to figure out how to write this?
Write a Java program that will serve as a basic sales calculator. The program should present the user with a choice of four different products of your choosing in a simple menu. After the user selects a product by entering a character corresponding to a product, the program should prompt the user for the quantity and then calculate the Subtotal, Sales Tax Amount, and Total Sale Amount. The calculations should be performed as follows:
Subtotal = (Price * Quantity)
Sales Tax Amount = Subtotal * Sales Tax Percentage (use 6.5% for the sales tax percentage)
Total Sale Amount = Subtotal + Sales Tax Amount
Be sure to use variables to store temporary values. The program should output the product sold, quantity sold, and the calculated values for Subtotal, Sales Tax Amount, and Total Sale Amount. Your assignment submittal should include your java code which is properly commented, and the class file..
this is what i have so far and not sure if I am on the right track?
import java.util.scanner;
public class Sales //Defines the class
Public static void main (String args[]){
System.out.println("Welcome to Super Shopper");
System.out.println("1) Star Wars DVD");
System.out.println("2) X-box 360 ");
System.out.println("3) I-Pad 3");
System.out.println(“4) 2 liter Soda”);
System.out.println("5) Quit");
Scanner sc = new Scanner (System.in);
System.out.print("Please select item :");
int choice = keyword.nextInt();
Scanner number = new scanner (System.in);
System.out.print("Please select quantity :");
Int choice = quantity.nextInt();
String userInput;
}
}
Since this is a homework question, I won't be providing you with the answer to your problem, but hopefully I will be able to help you in figuring out how to structure your program, as well as explain how to use the Scanner class to gather input from the user. The rest will be up to you.
First you will need to develop the pseudo-code for your main program. Basically a flow of execution based on the events that should happen.
pseudo-code is NOT code that will compile, but is useful in figuring out the structure of a program. Here is the pseudo code for your program.
show greeting with choices.
get choice from user
if choice is valid and choice is not exit
prompt user for quantity
if quantity is valid
calculate total and show it to the user
restart program
if quantity is invalid
prompt user for a valid quantity again
if choice is valid and choice is exit
show exit message and exit program
if choice is invalid
show error message and restart program
Notice that upon successful completion of getting the total cost of a purchase, we "restart the program". If you were more advanced, this might entail calling a function, but my guess is that you are still a beginner, so doing the same thing more than once should remind you of a loop. In this case a while loop.
Thus we can rewrite this pseudocode to the following
done = false
while not done
get choice from user
if choice is valid and choice is not exit
prompt user for quantity
if quantity is valid
calculate total and show it to the user
if quantity is invalid
prompt user for a valid quantity again
if choice is valid and choice is exit
done = true
if choice is not valid
show error message
exit program
Now, notice how when the user inputs an invalid quantity (ie: Something that is not an integer > 1) we ask for a quantity AGAIN. Doing the same thing multiple times? That's right, that means we should probably use another while loop again.
For this second while loop, the basic thinking is, "keep asking the user for a quantity until we have a valid quantity". The simplest way to accomplish this, is to create a boolean variable we call haveQuantity, and loop until that value is true.
Our pseudo-code now becomes:
done = false
while not done
get choice from user
if choice is valid and choice is not exit
haveQuantity = false
while not haveQuantity
prompt user for quantity
get quantity from user
if quantity is valid
haveQuantity = true
calculate total and show it to the user
if choice is valid and choice is exit
done = true
if choice is not valid
show error message
exit program
This should be the general structure of your program. In the following section, I will show you how to properly use the scanner class to get input from the user.
public class EchoInt
{
import java.util.Scanner;
public static void main(String[] args)
{
//Declaration of variables outside the while loop
Scanner scan = new Scanner(System.in); //declaring variables outside of a loop saves space and speeds up execution as the jvm does not need to reallocate space for an object inside the loop.
boolean done = false; //this will be our conditional for the while loop
int input = -1;
while(!done) //while done is equal to false.
{
System.out.println("Please enter a positive int to echo or 0 to exit: ");
if(scan.hasNextInt()) //If the user has inputted a valid int
input = scan.nextInt(); //set the value of input to that int.
else //The scanner does not have a integer token to consume
{
/*
THIS IS IMPORTANT. If the scanner actually does have a token
which was not an int. For example if the user entered a string,
you need to consume the token to prepare to accept further tokens.
*/
if(scan.hasNext())
scan.next(); //Actually consumes the token
input = -1; //This is used to indicate that an invalid input was submitted
}
if(input == 0) //The user chose to exit the program
done = true; //set done to true to kick out of the while loop
else if(input == -1) //This means the user inputed an invalid input
System.out.println("ERROR! Try again."); //show error message
else //The user inputted valid input
System.out.println("echo: "+input); //Echo the int
}
scan.close(); //We are done, so close the scanner
System.out.println("Exiting. Goodbye!"); //Show a goodbye message
System.exit(0); //exit the program. The zero tells us we exited without errors.
}
}
Hope this helps. And feel free to ask more questions.
Stackoverflow really excels when you have a very specific question to ask. As for your requirements, you are asking the user for input thats good. But you are not mapping items to prices or quantities. You are hardcoding in the items position ie "3) I-Pad 3" which will make it harder to get the actual item name later and match it to it's price.