Skipped nextLine() - java

I'm trying to make a short game where the player has to open a treasure chest and buy stuff from a shop, but when i exit the shop, it tells me "Invalid command. Use "shop" or "open."" I added the "end of loop" and found out that after store is finished, it ends the loop and ignores the nextLine() command and goes directly to the if-else ladder. Can anyone help me solve this?
while (win == 0)
{
opt = s.nextLine();
er = 1;
if (opt.equalsIgnoreCase("shop"))
{
store();
er = 0;
}
else if (opt.equalsIgnoreCase("open"))
{
gold += open();
}
else if (opt.equalsIgnoreCase("exit"))
{
return;
}
else if (er == 1)
{
System.out.println("Invalid command. Use \"Shop\" or \"Open.\"");
wait (1);
}
if (gold >= 1000000)
{
win = 1;
}
System.out.println ("End of loop");

Related

If statement within if statement is not running

So i am trying to make a text based rpg game and what is supposed to happen here is when you activate a hunt by typing hunt it asks you yes or no. However even when i input yes, the you killed the boar message does not pop up. I am fairly new to java so sorry if the code is bad.
//Branches
if (ins.equals("branches") && loc.equals("forest")) {
System.out.println("You got a branch");
ib++;
} else if (ins.equals("branches") && !"forest".equals(loc)) {
System.out.println("You need to be in the forest to cut branches");
} else if (ins.equals("bcount")) {
System.out.println(ib);
}
//Branches
//Stones
if (ins.equals("stones") && loc.equals("mountains")) {
System.out.println("You got a stone");
is++;
} else if (ins.equals("stones") && !"mountains".equals(loc)) {
System.out.println("You need to be in the mountains to gather stones");
} else if (ins.equals("scount")) {
System.out.println(is);
}
//Stones
//Spears
if (ins.equals("spear") && is >= 1 && ib >= 1) {
System.out.println("+1 spear");
is--;
ib--;
ispear++;
} else if (ins.equals("spear") && is < 1) {
System.out.println("Insufficient resources");
} else if (ins.equals("spear") && ib < 1) {
System.out.println("Insufficient resources");
} else if (ins.equals("spearcount")) {
System.out.println(ispear);
}
//Spears
//Hunt
if (ins.equals("hunt") && ispear >= 1) {
System.out.println("A wild boar comes charging at you! Throw spear? (yes or no)");
if (ins.equals("yes")) {
System.out.println("You killed the boar!");
}
} else if (ins.equals("hunt") && ispear < 1) {
System.out.println("You dont have any spears");
}
}
If the while loop at the top controls the input then it is not possible for the code to get back to that inner if statements because ins cannot equal both "hunt" and "yes" at the same time. You need to do what #Spectric suggested in the comments and read the input again, or you need to use another way.
In the example below, we have used a boolean as a flag Boolean hunting = false;, and an OR condition || to allow us to get back inside the hunting section if (huting == true || ins.equals("hunt")....) then finally we need to make sure we trigger the flag on/off when hunting starts/ends like this hunting = true; or hunting = false;
Then all put together:
//Flag that allows us to trigger hunting
//This needs to be placed outside of the while loop
Boolean hunting = false;
//While loop that gets input and prints the next instruction
while (ins != null)
{
//Your code here to get the input
//...
//ins = scanner.nextLine();
//...
//Hunt
//add an or "||" condition so that if the hunting flag is true then we can get back inside this if statement:
if (hunting == true || ins.equals("hunt") && ispear >= 1)
{
//Set the hunting flag to true, so that we can get back to here in the next loop:
hunting = true;
System.out.println("A wild boar comes charging at you! Throw spear? (yes or no)");
if (ins.equals("yes"))
{
System.out.println("You killed the boar!");
//Reset the hunting flag so future commands don't break:
hunting = false;
}
//Make sure you have an else statement to set the hunting flag back to false
else
{
System.out.println("The boar ran away!");
//Reset the hunting flag so future commands don't break:
hunting = false;
}
}
else if (ins.equals("hunt") && ispear < 1)
{
System.out.println("You dont have any spears");
}
}

How can I check that the next input is an integer while checking if it's > and < at the same time in Java?

There's two things I'm needing help with. Loop issue 1) I have to initialize this variable outside of the loop, which makes the loop fail if the user inputs a string. Is there a way around that? Basically, if I set N to anything then the do-while loop just immediately reads it after getting out of the
import java.util.Scanner;
/**
* Calculates sum between given number
*/
public class PrintSum {
public static void main(String[] args) {
int N = 0;
String word;
boolean okay;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number from 1-100: ");
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
} else {
okay = true;
}
} while (!okay);
loop(N, 0);
}
public static void loop(int P, int total) {
while (P >= 1) {
total = total + P;
P--;
}
System.out.println(total);
}
}
If not, then the issue becomes, how do I solve this? I thing that I need to be able to say
if (scan.hasNextInt() || ??? > 100 || ??? < 1) {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
} else {
okay = true;
}
What do I put in the ??? to make this work? I think I just don't know enough syntax.
Thank you!
Why don't you try this?
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
continue;
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
continue;
} else {
okay = true;
}
} while (!okay);
break is used to end the loop as soon as the user enters the invalid character(condition of the else clause), so the loop doesn't fail.
Looking at your edited question, continue is what you are looking for if you might want to allow the user to enter another value after entering the invalid value.
Use break or continue based on requirement. More on breaks and continue.
Your second approach can be solved as follows:
if (scan.hasNextInt()){
N = scan.nextInt();
if (N > 100 || N < 1) {
System.err.print("Invalid input. Try again. ");
}
//perform some operation with the input
}
else{
System.err.print("Invalid Input. Try again. ");
}

Is the following flowchart correct for the given code?

I have designed a flowchart that is based on this code in Java.
public static void main(String args[]) throws IOException {
BufferedReader bw = new BufferedReader(new InputStreamReader(System.in));
attendance_and_student_management object = new attendance_and_student_management();
int flag = 1;
do {
{
int var = object.menu();
if (var == 1) {
System.out.println("\f");
object.add_student();
System.out.println();
} else if (var == 2) {
System.out.println("\f");
object.search_student();
System.out.println();
} else if (var == 3) {
System.out.println("\f");
object.change_student_information();
System.out.println();
} else if (var == 4) {
System.out.println("\f");
object.take_attendance();
System.out.println();
} else if (var == 5) {
System.out.println("\f");
object.attendance_summary();
System.out.println();
} else if (var == 6) {
System.out.println("\f");
object.monthly_defaulter_list();
System.out.println();
} else if (var == 7) {
System.out.println("\f");
System.out.println("THANK YOU FOR USING THE PROGRAM!!");
System.exit(0);
} else {
System.out.println("\f");
System.out.println();
System.out.println("Invalid Input. Would you like to try again? Press 1 for Yes");
int choice1 = Integer.parseInt(bw.readLine());
if (choice1 == 1) {
continue;
} else {
break;
}
}
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag = Integer.parseInt(bw.readLine());
if (flag != 1) {
System.out.println("Are you sure you want to exit? Press 1 for Yes");
int flag2 = Integer.parseInt(bw.readLine());
if (flag2 == 1)
flag = 0;
else
flag = 1;
}
}
}
while (flag == 1);
}
The flowchart is given below:
I am still learning how to construct flowcharts, therefore, I am not sure whether this diagram is correct. Any inputs or suggestions will be much appreciated.
PS: I tried to make the flow chart a bit simpler, please do tell if this is more appropriate than the previous one...
Your condition on the chart
Is var equal to 1,2,3,4,5,6 or 7?
ist not 100% right.
Your program works with if and else if conditions, which check each condition serial. You first check the 1, then the 2, then the 3 and so one...
Your chart shows this conditions as an All-In-One condition, what in java mean a switch).
So your chart should show these if's more like this:
Next, you dont need to draw the chart-boxes
Execute Method
In your code, you can draw just one box for the action in a true if-condition (like my added image).
And finally, you should have only one "Exit / End" point on the chart. Each flow that stopps the program, should link to this End-Point.

How can I print a previous state of a variable and exit a loop without break

Can someone explain how I can end the program after hitting the 'capacity exceeded' message without using a break or system.exit, but continue to prompt for 'leaving' and 'entering' if the message is not reached?
Also, for the 'capacity exceeded' message it also displays the totalPeople. totalPeople in this section becomes however many people I enter to leave or enter. How can I make so it's the totalPeople stored before I enter the leave or enter values to make it exceed capacity?
int numLeaving = Integer.parseInt(JOptionPane.showInputDialog("number leaving"));
int numEntering = Integer.parseInt(JOptionPane.showInputDialog("number entering:"));
while (totalPeople <= 65 && totalPeople >= 0) {
try {
if (numLeaving >= 0 && numEntering >= 0) {
totalPeople = (totalPeople + numEntering) - numLeaving;
JOptionPane.showMessageDialog(null,"Total people = " + totalPeople);
}
else {
JOptionPane.showMessageDialog(null,"Invalid data");
}
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"Enter numbers only");
}
if (totalPeople > 65) {
JOptionPane.showMessageDialog(null,"Capacity exceeded\n" + "Total people = " + totalPeople);
}
numLeaving = Integer.parseInt(JOptionPane.showInputDialog("number leaving"));
numEntering = Integer.parseInt(JOptionPane.showInputDialog("number entering:"));
}
I think you should save your limit of people that could enter in a constant. Like this:
static final int maximumPeople = 65;
So now you can use it for conditions in your loops and whatever you want:
while (totalPeople <= maximumPeople && totalPeople >= 0)
{
//code
}
if (totalPeople > maximumPeople) {
//code
}
And another variable that you are going to modify, in your case, totalPeople. In this case, you can show your message of the total of people that can enter:
if (totalPeople > maximumPeople)
{
JOptionPane.showMessageDialog(null,"Capacity exceeded\n" + "Total people = " + maximumPeople);
}
But it also will leaves your loop because you are using totalPeople (the real number of people that has entered).
I expect it will be helpful for you!
To do not continue looping, we have to make the looping condition false:
if (totalPeople > 65) {
JOptionPane.showMessageDialog(null,"Capacity exceeded\n" + "Total people = " + totalPeople);
totalPeople = -1;
}
The rest of loop code will be executed, but it will not entering while loop again.
If you want to keep the value of totalPeople, the easiest way is to add a boolean variable and use it in the condition of looping:
boolean exit= false;
while (totalPeople <= 65 && totalPeople >= 0 && !exit) {
// ..
if (totalPeople > 65) {
JOptionPane.showMessageDialog(null,"Capacity exceeded\n" + "Total people = " + totalPeople);
exit= true;
}
// ..
Put the current code in a while loop and store the totalPeople in another variable.

Java: Loop issues

I'm writing a relatively simple Java program that calculates discounts for shoppers if they have certain vouchers or bonuses. It's working okay, but I have an issue when the program asks the user if they have any vouchers.
If they type "n", they still have to go through the loop as if they responded with "y" once before they can exit. I know it's probably a dumb mistake in there somewhere, but it's been driving me crazy and I'd appreciate a pair of fresh eyes to once it over.
do {
System.out.println("Please enter the total price of the goods");
price = keyboard.nextDouble();
if (price < limits[0] || price > limits[1]) {
System.out.println("Invalid price. Please try again");
validPrice = false;
} else {
validPrice = true;
}
} while (!validPrice);
keyboard.nextLine();
do {
System.out.println("Does the customer have any additional discounts? y/n");
choice = keyboard.nextLine();
if (!choice.matches(inputRegexMatchPattern)) {
System.out.println("Invalid input – please re-enter");
} else if (choice.toLowerCase().charAt(0) == 'y') ;
{
System.out.println(choice);
do {
System.out.println("What type of discount does the customer have? [L]oyalty Card/[D]iscount Voucher");
input = keyboard.nextLine();
if (!input.matches(discountRegexMatchPattern)) {
System.out.println("Invalid input – please re-enter");
}
} while (!input.matches(discountRegexMatchPattern));
if (input.charAt(0) == 'l' || input.charAt(0) == 'L') {
voucherDiscounts += voucherDiscountsArray[0];
System.out.println("Loyalty Card discount accepted");
} else if (input.charAt(0) == 'd' || input.charAt(0) == 'D') {
voucherDiscounts += voucherDiscountsArray[1];
System.out.println("Discount Voucher accepted");
}
}
} while (!(choice.toLowerCase().charAt(0) == 'n'));
You have a semicolon here:
else if (choice.toLowerCase().charAt(0) == 'y') ;
What that means is your loop will continue to execute in spite of the selection you make. Java interprets this if statement as not having any body.
Remove the semicolon and you should be good to go.
The do while construct always performs the content of the loop BEFORE it actually tests the condition.
I guess what you want here is a simple while loop.

Categories