Hey guys this is my code and what it is doing is going in an loop but what its suppose to do is if the user types in borrow then it will ask the user how much which it does but then they type in a number and it will ask them again would you like to borrow or sell and it is in an infinite loop.
case 3:
do{
System.out.println("What would you like to do? Please type borrow to borrow money or sell to sell assets: ");
b = scan.nextLine().toLowerCase();
if(b.equals("borrow")){
System.out.print("how much would you like to borrow Remmber if you go over 50000 debt its game over.");
try {
input = scan.nextInt();
} catch (Exception e) {
System.err.println("That is not a number!!");
}
account.setdebt(account.getDebt() + input);
account.setBalance(account.getBalance() + input);
System.out.println("Your new Balance is " + account.getBalance());
}
else if(b.equals("sell")){
sellA();
}else{
System.out.println("You didn't input 'borrow' or 'sell'. Reinput please");
}
}while(!b.equals("borrow") || !b.equals("sell"));
break;
You need to change || to && inside while, otherwise the condition is always true. There'll always be at least one of those two values that b is not equal to.
Related
I am fully aware this question has been asked many times, it is a classic first year problem in CSC. I am not looking for the solution to the problem itself. I think I have it basically done however I am missing something that I cannot find how to do.
Here is my code:
import java.util.Scanner;
import java.util.Random;
public class HiLow
{
public static void main (String[] args)
{
Random generator = new Random();
Scanner scan = new Scanner(System.in);
int num1,guess;
int count = 0;
num1 = generator.nextInt(100) + 1;
while(true) {
System.out.print("Enter an integer between 1 or 100 or enter 0 at anytime to quit: ");
guess = scan.nextInt();
count++;
if(guess == num1 || guess == 0) {
if(guess == 0) {
System.out.println("Thanks for playing");
break;
}
System.out.println("Congrats you've guessed correct and your total guesses is " + count );
break;
}
else if (guess > 100 || guess < 1) {
System.out.print("I see you cannot follow instructions. I said ");
count--;
}
else if (guess > num1) {
System.out.println("You have guessed too high. ");
}
else {
System.out.println("You have guessed too low.");
}
}
}
}
My problem is i am required to prompt the user at the point of "if the user quits or successfully guesses the correct number, prompt the user to see if they wish to play again". I am lost and not sure how to continue my while loop from the beginning after my breaks. Is there a way to end the break condition i have from (guess == num1 || guess ==0) and direct my program to start again at the while(true) statement?
Thanks
I will say search up continue;
Tips to help further:
The continue statement is used to bring the loop back to the start, try it instead of a break where you want the user to continue.
You need some sort of check if the user wants to continue, (try asking them to type in some specific int you check, p.s negative numbers are integers as well)
#Ahmed thinks you should continue, I would rather not break, or conditionally break.
Well there are multiple ways you could accomplish this, One would be to just to prompt the user with a "press q to quit" dialogue using the Scanner class where .next() returns the String when the user hits enter:
if(guess == num1 || guess == 0) {
if(guess == 0) {
System.out.println("Thanks for playing");
}else{
System.out.println("Congrats you've guessed correct and your total guesses is " + count );
}
System.out.println("would you like to play again [y/n]?");
if(scan.next().equals("y")){
num1 = generator.nextInt(100) + 1;
count=0;
}else{
break;
}
}
If thats what you mean. Hopefully I helped.
or maybe you can have it only quit at zero, if so just remove that second break and replace it with num1 = generator.nextInt(100) + 1; to set the new value to guess.
I have started out recently, this site has helped me once and I'm hoping it helps me again.
I know I have to connect else to if but I don't know how, here is my code,
import java.util.Scanner;
public class even {
public static void main(String[] args) {
System.out.println("Enter a number.");
Scanner scan = new Scanner(System.in);
int n;
n = scan.nextInt();
boolean even;
even = n % 2 == 0;
if (even = true) {
System.out.println("Your number number is even");
else
System.out.println("Your number is odd");
}
}
}
and i am very sorry if this question is off topic but i am new and learning, please don't dislike it and suggest what to do next time
Close the brace, something like
if (even) { // even = true is not good. even == true would work. but if (even)
// is shorter.
System.out.println("Your number number is even");
} else {
System.out.println("Your number is odd");
}
When you say if (even = true) you are assigning true to even which also evaluates to true.
if (even == true) { //can be also written as if (even)
System.out.println("Your number number is even");
} else { //we enter the next block only when `even` is not true
System.out.println("Your number is odd");
}
More details about the if statement, here.
If/Else statements are knitted together by use of curly braces to control the flow of your code and logic. Your if-statement should be altered to:
if (even) {//even is true
System.out.println("Your number number is even");
} else {
System.out.println("Your number is odd");
}
I'm writing a program called Revenue, I've satisfied all of the requirements except for one.
System.out.print("\t Enter quantity(ies): ");
quantity = keyboard.nextInt();
if (quantity < 0 || quantity > 150 || quantity == '.'){
System.out.println();
System.out.println("\t Invalid item price.");
System.out.println("\t Please run the program again");
System.out.println();
System.out.println("Thank you for using \"Temple\" store");
System.exit(0);
We have to ask the user for the quantity of the item they're purchasing and it cannot have a decimal or '.' in it. For example, when the user is asked to input the amount of of items they want to purchase, they will enter the number. If they enter a number with a decimal, it should print out
Invalid item price.
Please run the program again
Thank you for using "Temple" store
keyboard.nextInt() will not allow decimals. If you type something like "3.14.15" it will throw an exception. For your error handling, you need to catch this exception and print out a better error message than the stack trace which you see by default.
Use the try-catch block to accomplish what you want:
System.out.print("\t Enter quantity(ies): ");
try{
quantity = keyboard.nextInt();
if (quantity < 0 || quantity > 150)
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
System.out.println();
System.out.println("\t Invalid item price.");
System.out.println("\t Please run the program again");
System.out.println();
System.out.println("Thank you for using \"Temple\" store");
System.exit(-1); //-1 signs an error to the application that launched the program
}
Use below code:
String quantity = keyboard.next(); // use keyboard.next() instead of keyboard.nextInt()
// because it will throw Exception if value is other
//than int
boolean flag = quantity.matches("[0-9]+");
if (flag) {
if (Integer.parseInt(quantity) < 0
|| Integer.parseInt(quantity) > 150) {
flag = false;
}
}
if (!flag) {
System.out.println();
System.out.println("\t Invalid item price.");
System.out.println("\t Please run the program again");
System.out.println();
System.out.println("Thank you for using \"Temple\" store");
System.exit(0);
}
I need two outcomes after a Do Else While statement, right now the user can input data and it will be stored in a String, if they want to add anything else they type 'y', if 'n' it will end the program and tell them what they've inputed. If they input neither of those and input 'd' for example it stops the statement running and takes me through to the Else statement
In the Else statement I want two outcomes, either "You have added the following" and "Error, you inputted something wrong"
Here is the Do Else While statement:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} else {
System.out.println("You have added the following:");
System.out.println("Error, you inputted something wrong");
break;
}
} while (true);
What do I write to get two outcomes depending on what the user has done? (said 'n' or wrote something wrong).
Just add another if-else:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y"))
{
System.out.println("Enter : ");
list.add(input.next());
}
else
{
if(//valid input condition)
System.out.println("You have added the following:");
else
System.out.println("Error, you inputted something wrong");
break;
}
} while (true);
Try this:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} else if (input.next().startsWith("n")) {
System.out.println("You have added the following:");
break;
} else {
System.out.println("Error, you inputted something wrong");
}
} while (true);
Introduce another condition in the else. Preferably, use else if:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
String userInput = input.next();
if (userInput.startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} elseif (userInput.startsWith("n")) {
// user wants to stop
System.out.println("You have added the following:");
break;
} else {
System.out.println("Error, you inputted something wrong");
break;
}
} while (true);
Try to use "IF" statement inside else statement
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} else {
if (input.next().startsWith("n")) {
// Your code for "n"
}else{
//else here.
System.out.println("You have added the following:");
System.out.println("Error, you inputted something wrong");
break;
}
}
I think some of the logic and flow of your program is slightly off. I would change it to this.
Code:
boolean keepGoing = true; // can use a boolean to change the while loop condition to false.
while (keepGoing) {
System.out.println("Enter : ");
list.add(input.next());
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) { // 'if' to check if 'y', then execute this code.
keepGoing = true; // don't really need this, but it's here as example
} else if (input.next().startsWith("n")){ // 'else if' to check if 'n'.
System.out.println("You have added the following: " + list);
keepGoing = false; //change to false to stop the loop
} else { // and lastly a single 'else' if the input was invalid based on 2 previous conditions.
System.out.println("Error, you inputted something wrong"); // if for some reason the input isn't accepted this will show.
}
}
It follows a more logical flow and easier to understand. A simple while loop is easier for others to understand being that they can evaluate the condition before they enter the body of the loop.
You also don't need the Boolean and can simply use true in the while loop and break; in the else if portion, but as with do while loops, breaks can create confusion as far as when others need to look at your code once you start writing larger programs.
Here is the code in my World.java
while (option == 1)
{
a.generate();
a.count();
System.out.println("Max number is "+ a.maximum(max));
System.out.println("Average number is "+ a.average(aver));
System.out.println("Min number is "+ a.minimum(min));
System.out.println("Do you want to run it again (y/n)?: ");
a.getchoice();
}
if (option == 2)
{
System.out.println("Program exits.");
System.exit(0);
}
And here is the code in my rg.java
public int getchoice() {
Scanner reader = new Scanner(System.in);
String selection = reader.nextLine();
if(!selection.toLowerCase().equals("y") && !selection.toLowerCase().equals("n"))
{
System.out.print("Invalid. Please enter āyā or ānā: ");
return this.getchoice();
}
if (selection.toLowerCase().equals("y")){
return 1;
}
else
{
return 2;
}
I want to return variable to run the option y/n in the world class.
But the problem is if i press y after run the program, then something went wrong, either i press y or n the program is still execute as if the option is 1.
Can anybody check to find out which part was wronged in my code? Sorry about this newb code, since i just begin to learn java
You never set option.
Try this:
option = a.getChoice();
You don't catch the result of your method getChoice() in the variable option. So the while loop will never terminate.
Change to
while (option == 1)
{
a.generate();
a.count();
System.out.println("Max number is "+ a.maximum(max));
System.out.println("Average number is "+ a.average(aver));
System.out.println("Min number is "+ a.minimum(min));
System.out.println("Do you want to run it again (y/n)?: ");
option = a.getchoice();
}