Java error with a while and if statement - java

Hi I'm new to Java and for my intro class I have to program something that does the following: Define a problem with user input, user output, While Statement and some mathematical computation.
What I want to do is have it prompt the user for feet and inches for height, if it's over 5'8 they can't go on the roller coaster; if it's 5'8 or less they can. I realize this would be much easier with like an if else kind of thing but I'm required to use while; also we haven't covered do while yet so I can't use that either. I'm probably messing up horribly and there's some better way to do this, but this is what I have so far.
import java.util.Scanner;
public class coasterHeight
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int feet;
int inches;
System.out.println ("Your must be at least 5'8 to ride this ride.");
System.out.println ("Please enter your height in feet:");
feet = keyboard.nextInt();
System.out.println ("Please enter your height in inches:");
inches = keyboard.nextInt ();
while (feet <= 5 && inches <= 8)
{
System.out.println("You can go on this ride.");
break;
}
{
if (feet >= 6 && inches >=9)
{
System.out.println ("You cannot go on this ride.");
}
}
}
}
So here's the problem. When the input meets the while requirements it works fine (it used to go on an infinite loop with "You can go on this ride" but I discovered break;), but for the if statement, nothing appears in the output. The "You cannot go on this ride", nothing appears, there's no error or anything it just ends the output after I enter a height that is over 5'8. Like I said this is probably awful but any help would be appreciated, thanks.

The reason your program doesn't work as you expect is because your logic is incorrect.
Look carefully at your conditions and think about the different possibilities the user can enter.
feet <= 5 && inches <= 8
The and operation && means both parts of this must be true at the same time in order for the statement to evaluate to true. So someone who is 5 feet 9 inches tall would cause this condition to evaluate to false.
The same problem occurs with feet >= 6 && inches >=9 in that someone who is 7 feet 1 inch tall would cause this condition to evaluate to false.
Also, it seems you have your conditions reversed. At the top of the program you say someone must be at least 5 feet 8 inches in order to go on the ride but then you check for less than that and allow them to go on.

Try using float or double instead, where float height = 0.00 or double height = 0.0.
Then you can use it in the while statement such as
while (height >= 5.8){
System.out.println("You cannot enter the ride");
break;
}
while (height < 5.8){
System.out.println("You can enter the ride");
break;
}

To answer this in pseudo-code (you can fill in the details using what you've already got):
while not valid input (not a number, is negative, etc.)
get height from user
if height allowed on ride
say "ok"
else
say "no dice"
As another note: notice that feet <= 5 && inches <= 8 is true for (for example) feet = 7 and inches = 1. I feel they should probably be allowed on the ride.

Related

If and if else again

The problem I seem to be having is that I am unsure on how to make the program recognize if the player is in one of the "MVP" positions (C,SS,CF) before moving forward with my program logic.
These three positions qualify for "MVP" status only if their OPS is above 800 for everyone else, it has to be 900 or above to be considered for "MVP".
Once again, I am having trouble with the "if" and "if else" statement.
Again, This IS school given problem and I don't want the answer. Only insight into what I am doing wrong. I want to learn this not have it done for me. Thank you in advance.
import java.util.Scanner;
public class baseBall {
public static void main(String[] args) {
/* A good part of a baseball player's offensive value is captured by the
statistic OPS - the sum of the player's on base percentage and slugging
percentage. An MVP candidate will typically have an OPS above 900,
however if they play a difficult defensive position (catcher, shortstop, or center field)
then they are an MVP candidate if their OPS is above 800. Write a program that will prompt the user for
a player's name, their on base percentage, slugging percentage, and defensive position and report whether the player is an MVP candidate*/
Scanner input = new Scanner(System.in);
System.out.println("Please enter players name: ");
String name = input.next();
System.out.println("Please enter On Base Percentage: ");
double Obp = input.nextDouble();
System.out.println("Please enter slugging Percentage: ");
double Slg = input.nextDouble();
System.out
.println("Please enter position (P,C,1B,2B,3B,SS,LF,CF,RF): ");
String ball = input.next();
String position;
double Ops = Obp + Slg;
if ( position.equalsIgnoreCase("ss")){
if (position.equalsIgnoreCase("cf")){
if (position.equalsIgnoreCase("c")){
System.out.println("MVP Candidate!");
else
System.out.println("NOT an MVP Candidate!);
}
}
}
}
}
Try doing it without nested IFs. Instead, try using Boolean operators like AND and OR.
As previously stated try using a paper first. Try drawing a decision tree to see what and where it might be going wrong.
Your code is checking if the player position is c AND ss AND cf. But the player will be only in one position, it can't be in all the three, so your code will always print "Not an MVP Candidate!".
To make it simple your code is checking if the position is c AND ss AND CF, instead you want to check if the position is c OR ss OR cf.
So you have to use the conditional operator OR -> ||:
if(position.equalsIgnoreCase("ss") || position.equalsIgnoreCase("cf") || position.equalsIgnoreCase("c") {
System.out.println("MVP Candidate!");
} else {
System.out.println("NOT an MVP Candidate!);
}
Your nested ifs will never be true. Think about this logically and on paper.
If position equals ss how can it equal cf and c at the same time? Always ask yourself: "does this make sense?" -- do this before committing code to screen and you'll be golden.
As a side recommendation, please get rid of those distracting // from your question text. They serve no purpose other than to annoy.

Printing negative values in Java

My variables are
float amountLeft, amount;
char v1;
My goal is to let the user know If he uses more than a $1000 he will be in debt, the user can keep purchasing but he will be in debt. I can't get my head around negative numbers. How would I keep track of the negative numbers?
For example: "You just went over your limit. You owe us -5$ "
If you want to take a look at my code here it is.
amountLeft = 1000.0f;
while(amountLeft > 0) {
System.out.println(String.format("%3s %,1.2f %3s", "You have" , amountLeft, "money remaining to spend."));
System.out.println("Enter the cost of the item you want buy");
amount = new Scanner(System.in).nextFloat();
System.out.println("are you sure you wanna purchase this item?");
v1 = keyboard.next().charAt(0);
if (v1 == 'y')
{
amountLeft = amountLeft - amount;
System.out.printf("%.2f",amountLeft);
You can to create a situation that allows that user to spend if he is negative if (amountleft < 0)
Also, that loop should be while (amount >= 0) because the user won't owe anything if he is at 0 dollars.
Simply add a new statement inside your amount left:
if (amountLeft < 0) {
// alert user that hes over the amount
}
Add this at the end of your code, and then you can print his negative amount every type the loop is executed.
You can then print the amount as per normal.
Variables can start at positive, and end at negative, or go from positive, to negative, to positive with no dramas.
Let me paraphrase your question. You want to let the user buy stuff even though his/her money is not enough. And each time he/she does that, you print "you owe us $xxx". But now you are printing "you owe us $-xxx". You basically want the negative number to be printed out as a positive number, right?
The other answers tell you how to check for negative value but you are actually asking how to print negative values as positive ones.
There is a method for this in the java.lang.Math class! You can print -5 as a positive number this way:
System.out.println ("You owe us $" + Math.abs(amountLeft));

Break a while loop without using If or Break

I need to create a program that uses while to find the volume of a cylinder. I need the while loop to break if the user inputs a negative value for the height. My code looks like this:
double sentinel=1, h=1, v=0, r, count=0; // declares all variables needed
final double PI=3.14159;
boolean NotNegative=true;
while(NotNegative){// && count==0){ // while both the height is positive AND the total times run is 0
System.out.print("Enter height (Use negative to exit): "); // has the user input the height
h=Double.parseDouble(br.readLine());
sentinel=h; // save sentinel as the inputted height
while(sentinel>0){
System.out.print("Enter radius: "); // have the user input the radius
r=Double.parseDouble(br.readLine());
v=PI*(r*r)*h; // find the volume
System.out.println("The volume is " + v); // print out the volume
count++; // increase the count each time this runs
NotNegative=true;
sentinel=-1;
}
}
Any help?
You can throw an Exception which you catch and ignore. This is bad idea as
if and/or break is more efficient and simpler.
it's slow
it's confusing.
However, since you are using a while loop, which is like using an if & break, you can do the following.
NotNegative = h >= 0;
Add the following code inside the while(NotNegative){, after reading the input.
NotNegative = h >= 0;

Couldnt find the Error in Guess Game Class

Okay, this is part of the full code of a guessing game.
public static void Game(){ //Second page of game with option of continue playing when guessed close enough to answer.
Scanner scan = new Scanner(System.in);
GuessingGame testgame=new GuessingGame();
testgame.Generator();
int num = testgame.GetGenNum();
//Produces a random number between 1 and 100 inclusive of 1 and 100
System.out.println("Guess the target integer which is between 1 and 100 inclusive");
int guess=scan.nextInt();
int difference=(guess-num);
while(guess!=num){
int yesCounter=0;
System.out.println("Guess again " +num+" "+difference);
guess=scan.nextInt();
difference=(guess-num);
///something wrong here, shouldnt repeat if difference too big
if(difference<=5||difference>=-5){ //something wrong with the condition, it says its close enough even tho it isnt.
while(yesCounter<1){
System.out.println("Close enough, do you want to keep Guessing? Y/N ");
yesCounter++;
String play = scan.nextLine();
//play=play1;
while(!(play.equalsIgnoreCase("y")))
{
if(play.equalsIgnoreCase("n")){
System.exit(1);
}
else{
if((play.equalsIgnoreCase("y"))){
invalid();
guess=scan.nextInt();
}
else{
Game(); ///TAKE note as it might restart the game with new random integer
}
}
}
}
}
}
output is:
.........................
Play? Y/N
y
Guess the target integer which is between 1 and 100 inclusive
50
Guess again 44 6
44
Close enough, do you want to keep Guessing? Y/N
Guess the target integer which is between 1 and 100 inclusive
..........................
the problem is, when user guess a number, the condition is if the difference between the guess and the generated number is 5 or smaller, tell user that its close enough, and ask if user wants to continue guessing, but the condition wasn't fulfilled and yet still runs, can someone help?
while(!(play.equalsIgnoreCase("y")))
{
if(play.equalsIgnoreCase("n")){
System.exit(1);
}
else{
if((play.equalsIgnoreCase("y"))){
invalid();
guess=scan.nextInt();
....
That isn't right, if((play.equalsIgnoreCase("y"))) can never be true, since the loop it is in, explicitely cannot be entered if it is true. That's where your problem is, it will always restart the game because it calls Game() in the else-branch. In short, this is what you do:
boolean _true = true;
while(! _true) {
if(_true) {
//impossible
}
else {
Game(); //ALWAYS
}
}
Since you tagged your question with homework, I will not give the full correction, but now you know where it goes wrong, you should be able to figure out what you need to change in order to advance :)
You mixed or and and (Note: The condition you used (difference<=5||difference>=-5) is always true.). You may use any of the following
if (difference<=5 && difference>=-5) { ... } # difference is 5 or less
or
if (difference<=-5 || difference>=5) { ... } # difference is 5 or more
Better readable if you use Math.abs(...) instead:
if (Math.abs(difference)<=5) { ... } # difference is 5 or less
and
if (Math.abs(difference)>=5) { ... } # difference is 5 or more
resp.
if(difference<=5||difference>=-5) This says if the difference is less than 5 or greater than -5. All numbers are less than 5 or greater than -5, so this is always true.
I'm assuming what you want is something like if(Math.abs(difference)<=5). This will tell you if the absolute value of your difference variable is less than or equal to 5.

Ending a for loop by pressing 'q'

I have been doing a project for my java class. For the project I have to have the user enter input and calculate their body mass index and body surface area the program is supposed to remain running until the user enters a "q". I cannot get my program to stop running when a "q" is put in it just crashes. Also I am very new to java and programming in general so I would appreciate any help. My code is as follows.
Thanks : )
public static void main(String[] args) {
//Scanner
Scanner stdIn = new Scanner(System.in);
//Variables
final double METERS_TO_CM = 100; // The constant to convert meters to centimeters
final double BSA_CONSTANT = 3600; // The constant to divide by for bsa
double bmi; // Body Mass Index
String weight; // Weight in kilograms
String height; // Height in meters
String classification; // Classifies the user into BMI categories
double bsa; // Body surface area
do {
System.out.print("Welcome to the BMI and BSA Calculator to begin enter weight in kilograms.");
weight = stdIn.next();
System.out.print("Enter height in meters: ");
height = stdIn.next();
double height2 = Double.parseDouble(height);
double weight2 = Double.parseDouble(weight);
bmi = weight2/(height2*height2);
if (bmi < 18.5)
{
classification = "Underweight";
}
else if (bmi < 25)
{
classification = "Normal";
}
else if (bmi < 30)
{
classification = "Overweight";
}
else
{
classification = "Obese";
}
System.out.println("Your classification is: " + classification);
bsa = Math.sqrt(((height2*METERS_TO_CM)*weight2)/BSA_CONSTANT);
System.out.printf("BMI: %.1f\n", bmi);
System.out.printf("BSA: %.2f\n", bsa);
System.out.println("Hit 'q' to quit");
} while (stdIn.nextLine().compareToIgnoreCase("q")==0);
}
}
I would guess that your "q" input is written in weight and therefore you try to parse it to a Double, which throws an unhandled Exception and stops the execution.
You should handle this Exception and make the system break the while loop when triggering it.
You're grabbing the entire line for your while loop condition.
Try just grabbing the next() instead of nextLine().
Also, you're looking at while it DOES equal 0 ... meaning equal. I'd change that to != instead. You want to continue looping while the next token is NOT Q.
Let's make a structural change to make this easier for you to do.
We are going to change it so that your do-while loop always is running, until you explicitly tell it to stop.
Your current while is:
while(stdIn.nextLine().compareToIgnoreCase("q")==0);
Which works ok, but we have a more simple way to do this. Have you heard of the break statement?
I would suggest you use break. This statement will 'break' you out of the while loop; basically it tells the program to stop looping when it is called. This will be a bit easier to follow than your somewhat confusing do-while.
do {
//Your Do code goes here, as before
...
//
//Your newly added break statement will go here.
//This breaks out of the while loop when your inputed 'choice' value is
//equal to the string of "q" (for quit)
if (Choice.equals("q"))){
break;
//When break is called nothing else in the loop will run
}
//Same thing but with the string of "quit"
if (Choice.equals("quit"){
break;
}
}while (true);
//Your new while statement is simply while(true) which will run until break is called
Hopefully that is helpful to you.
Don't actually use a loop. Since it's impractical someone would ever max the call stack out by answering too many questions, just make the whole operation a function. At the end of the function, call itself if the result isn't Q.
its simple use this
while (true)
{
Console.WriteLine("Start processing");
//processing code here
Console.WriteLine("finish processing");
Console.WriteLine("start again? y/n?");
if (Console.ReadLine().Equals("n"))
break;
}

Categories