Java using else if to assign a value [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm very new to programming and Java. I'm trying to use else if to assign a value to a variable if they selected the correct input. But whenever I try to compile it, it says it cannot find the variable.
import java.util.Scanner;
public class TDEE
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
double tdee = 0.0;
System.out.print("Please enter your name: ");
String name = in.next();
System.out.print("Please enter your BMR: ");
double bmr = in.nextDouble();
System.out.print("Please enter your Gender (M/F): ");
String gender = in.next();
System.out.println();
// providing menu items
System.out.println("Select your activity level: ");
System.out.println("[0] Resting (Sleeping. Reclining)");
System.out.println("[1] Sedentary (Minimal Movement)");
System.out.println("[2] Light (Sitting, Standing)");
System.out.println("[3] Moderate (Light Manual Labor, Dancing, Riding Bike)");
System.out.println("[4] Very Active (Team Sports, Hard Manual Labor)");
System.out.println("[5] Extremely Active (Full-time Athlete, Heavy Manual Labor)");
System.out.println();
// accept user choice with a Scanner class method
System.out.print("Enter the number corresponding to your activty level(0,1,2,3,4, or 5): ");
String choice = in.next();
System.out.println();
if(choice.equalsIgnoreCase("0"))
{
double activityFactor = 1.0;
}
else if(choice.equalsIgnoreCase("1"))
{
double activityFactor = 1.3;
}
else if(choice.equalsIgnoreCase("2") && "M".equals(gender))
{
double activityFactor = 1.6;
}
else if(choice.equalsIgnoreCase("2") && "F".equals(gender))
{
double activityFactor = 1.5;
}
else if(choice.equalsIgnoreCase("3") && "M".equals(gender))
{
double activityFactor = 1.7;
}
else if(choice.equalsIgnoreCase("3") && "F".equals(gender))
{
double activityFactor = 1.6;
}
else if(choice.equalsIgnoreCase("4") && "M".equals(gender))
{
double activityFactor = 2.1;
}
else if(choice.equalsIgnoreCase("4") && "F".equals(gender))
{
double activityFactor = 1.9;
}
else if(choice.equalsIgnoreCase("5") && "M".equals(gender))
{
double activityFactor = 2.4;
}
else if(choice.equalsIgnoreCase("5") && "F".equals(gender))
{
double activityFactor = 2.2;
}
else
{
System.out.println("You did not choose a valid manu option.");
}
tdee = bmr * activityFactor;
System.out.println();
System.out.println("Name: " + name + " Gender: " + gender);
System.out.println("BMR: " + bmr + " Activity Factor: " + activityFactor);
System.out.println("TDEE: " + tdee);
}
}

The reason it is not compiling is because of scoping. The variable you are declaring is inside an if statement. That gives its scope, ability to access it, to only within the if statement. In order to reference it outside the if statement, you must declare it within the scope you want to access it. Then you can assign values to it like as follows, activityFactor = 1.0;, within the if else statements. Where you declare your variables determines what can access them.
You have to declare double activityFactor outside of the if else statements. Just include double activityFactor; above the statements and replace all double activityFactor with activityFactor, and it should compile.

Related

Else if not working correctly when scanning file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
import java.io.FileReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Coursework2 {
public static void main(String[] args)
throws FileNotFoundException { {
Scanner reader = new Scanner(new FileReader("seats.txt"));
Scanner scan = new Scanner (System.in);
double defaultdiscount = 17.5, discount = 16.97;
boolean random = true;
while (random) {
System.out.println("Please enter your Surname:");
String name = scan.nextLine();
System.out.println("Good morning, Manager " + name + " Would you like to apply a specific discount rate?");
String decision = scan.nextLine();
if (decision.equalsIgnoreCase("yes") || decision.equalsIgnoreCase("y")) {
System.out.println("That's great, Mananger " + name + ".");
System.out.println("How much discount would you like? (1-100)");
break;
} else if (decision.equalsIgnoreCase("no") || decision.equalsIgnoreCase("n")) {
System.out.println("Alright, " + name + " Here's all the seats without discounts:");
//break;
}
System.out.println("Invalid Input, please try again. Restarting.");
}
discount = scan.nextDouble();
defaultdiscount = discount;
while (reader.hasNext()) {
String table = reader.next();
double price = reader.nextDouble();
int bookings = reader.nextInt();
double newdiscount = (((price/100.00*discount)*bookings));
double newincome = (price*bookings-(((price/100.00*discount)*bookings)));
System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings );
System.out.printf("Discount: £%.2f, Income: £%.2f %n", newdiscount, newincome);
String decision;
do {
System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings );
//decision = scan.nextLine();
decision = scan.next();
}
while (decision.equalsIgnoreCase("No"));
System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings );
}
reader.close();
scan.close();
}
}
}
I understand that the code runs sequentially, but when it comes to trying to run the read files through the else if (No), it can't go above the while reader or inside the else if or it won't see the info from the text file, and when outside, it can't see the variables. I'm just a bit confused. It feels like something might be in the wrong place and I can't wrap my head around it.
I've given this a go, using the correct comparisons, and declaring the string inside of the while. But I'm still getting some errors. I'm thinking maybe setting the string to "null" isn't the correct way of resetting, since I've already declared it has a scan.nextLine previously?
Try doing the if statement like this
while(random){
if (decision.equalsIgnoreCase("yes") || decision.equalsIgnoreCase("y")) {
System.out.println("That's great, Mananger " + name + ".");
System.out.println("How much discount would you like? (1-100)");
random = false;
}
else if (decision.equalsIgnoreCase("no") || decision.equalsIgnoreCase("n")) {
System.out.println("Alright, " + name + " Here's all the seats without discounts:");
random = false;
}
else
System.out.println("Invalid Input, please try again. Restarting.");
}
You will not loop it if you never change "random" boolean to false. Also, try not using break in this case.
Also, try creating the variable "name" and "decision" outside the loop, as good practice. You should also rename "random" to something like "isBadAnswer"

How do I add an working if to my code? - Java

I'm building this weird BMI/BMR calculator for school and right now the code does what I want it to do. But I need to add an if (I think) that makes sure that the user doesn't type in values that are too small or too big. The user is only allowed to type in "vikt" between 0.5 and 2.2. If the user types in a faulty value I need the program to execute an else that prints out a "nope you did it wrong".
My problem is that I do not know where to put the if so that the code still works.
So my question is, where and how do I add an if to my code?
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
// Ledtext
System.out.println("Beräkna ditt BMI");
System.out.print("Tryck j för att starta: " );
char fortsätt = input.next().charAt(0);
System.out.println(" ");
do
{
//Användaren matar in sin data
System.out.print("Ange personens vikt (kg): ");
double vikt = input.nextDouble();
System.out.print("Ange personens längd (m): ");
double längd = input.nextDouble();
System.out.print("Ange personens ålder: ");
double ålder = input.nextDouble();
System.out.println(" ");
System.out.println("Beräknat BMI för både män och kvinnor är " + bmi(vikt, längd));
System.out.println("Beräknat BMR för män är: " + kalorier_Män(vikt, längd, ålder));
System.out.println("Beräknat BMR för kvinnor är: "+ kalorier_Kvinnor(vikt, längd, ålder));
System.out.println(" ");
System.out.print("Fortsätta? (j/n): ");
fortsätt = input.next().charAt(0);
}
while (fortsätt != 'n');
}
static double bmi(double vikt, double längd){
double bmiMänochKvinnor;
bmiMänochKvinnor = (1.3 * vikt) / Math.pow(längd, 2.5);
return bmiMänochKvinnor;
}
static double kalorier_Män (double vikt,double längd,double ålder){
double manBmr;
manBmr = (9.99 * vikt) + (6.25 * längd) - (4.92 * ålder) + 5;
return manBmr;
}
static double kalorier_Kvinnor (double vikt,double längd,double ålder){
double kvinnaBmr;
kvinnaBmr = (9.99 * vikt) + (6.25 * längd) - (4.92 * ålder) - 161;
return kvinnaBmr;
}
}
From my understanding you want to constrain the values the user can use as an input for this line:
double vikt = input.nextDouble();
You can simply do this by adding an if statement right after that where you check the entered value. If the value doesn't match the condition, you can send a message and continue the loop.
if (vikt < 0.5 || vikt > 2.2) {
// send some message
continue;
}
You can check the values directly after they are read, with an if else statement like this:
if(vikt > 2.2 || vikt < 0.5){
System.out.println("nope you did it wrong");
return; // this will stop the code
}
A better way of handling this problem would be the following function:
private static double retrieveValue(Scanner input, double min, double max, String requestMessage){
while(true){
System.out.println(requestMessage);
double measure = input.nextDouble();
if (measure >= min && measure <= max){
return measure;
} else{
System.out.println("This values is not allowed, please try again:");
}
}
}
You can call it like this:
double vikt = retrieveValue(input, 0.5, 2.2, "Ange personens vikt (kg):");

If the customer pays less than the ticket price [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Help me here i tried make success , program but theres a mistakes here can?
any one solve it and send it ,
If the customer pays less than the ticket price, I want to print the money less than the ticket price and print the rest to pay, or if the customer pays more than the ticket price, the rest of the money is printed to the customer, and finally if he pays the ticket amount, you print welcome
import java.util.Scanner;
public class Flow {
static Scanner input = new Scanner(System.in);
static int age;
static double ticketpricetax = 0.15 * 100 + 10;
public static double remainigamount = ticketpricetax;
public static double howmuchpay = 10;
public static void main(String[] args) {
System.out.println("Age");
int age = input.nextInt();
if (age > 12 || age <= 50) {
System.out.println("ticket price is ");
System.out.println(ticketpricetax);
System.out.println("Please pay your ticket");
}
input.nextInt();
if (ticketpricetax > howmuchpay) {
System.out.println("the money less than ticket price");
} else if (ticketpricetax > howmuchpay) {
System.out.println("the money is greater than ticket price");
} else {
System.out.println("welcome");
}
}
}
Your price input is not stored in any variable and it should be double not int, and then you are comparing ticketpricetax and howmuchpay with their initialized values,howmuchpay is not updated with input. In addition you're making an incorrect check and missing some statements.
Here is the correction :
import java.util.Scanner;
public class Flow {
static Scanner input = new Scanner(System.in);
static int age;
static double ticketpricetax = 0.15 * 100 + 10;
public static double howmuchpay = 10;
public static void main(String[] args) {
System.out.println("Age");
int age = input.nextInt();
if (age > 12 || age <= 50) {
System.out.println("ticket price is ");
System.out.println(ticketpricetax);
System.out.println("Please pay your ticket");
}
howmuchpay = input.nextDouble();
if (ticketpricetax > howmuchpay) {
System.out.println("the money less than ticket price");
System.out.println("rest of the money to pay = "+(ticketpricetax-howmuchpay));
} else if (ticketpricetax < howmuchpay) {
System.out.println("the money is greater than ticket price");
System.out.println("rest of the money = "+(howmuchpay-ticketpricetax));
} else {
System.out.println("welcome");
}
}
}

my program doesn't run completely [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
For some reason, my program stops when it reaches the part that asks the user if it know it's exam 1 score. I need the user to be able to enter yes or no. Why does the program stop? I need it to work properly. I have all the if-else statements. I am able to enter the percentage weights, but that is all that the program will do. More must be done. My code extends far beyond entering the percentage weights. Please help me.
import java.util.Scanner;
public class GradeCalculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner grade = new Scanner (System.in);
// A new scanner must be created. The scanner is essential to this program performing properly.
double A = 90-100;
double B = 80-89;
double C = 70-79;
double D = 60-69;
double F = 0-59;
String LetterGrade;
String yes;
String no;
double Exam1, Exam2, finalExam, Labs, Projects, Attendance, Quizzes;
double Exam1Grade, Exam2Grade, finalExamGrade, LabAverage, ProjectsAverage, AttendanceAverage, QuizzesAverage;
double knownWeight;
double PercentageWeights;
// As always, the variables must be declared at the beginning of the program.
System.out.print(
"Grading Scale:\n"+
"A = 90-100 \n"+
"B = 80-89 \n"+
"C = 70-79 \n"+
"D = 60-69 \n"+
"F = 00-59 \n");
System.out.println("What letter grade do you want to achieve in this course?");
LetterGrade = grade.next();
// The user will type the letter grade that it wants in this part.
System.out.println("\nEnter Percentage Weights: \t");
String input = grade.nextLine();
// The string above is needed when the user enters the exam grades and averages.
System.out.print("\n\nExam 1: \t");
Exam1 = grade.nextShort();
System.out.print("\nExam 2: \t");
Exam2 = grade.nextShort();
System.out.print("\nFinal Exam: \t");
finalExam = grade.nextShort();
System.out.print("\nLabs: \t");
Labs = grade.nextShort();
System.out.print("\nProjects: \t");
Projects = grade.nextShort();
System.out.print("\nAttendance: \t");
Attendance = grade.nextShort();
System.out.print("\nQuizzes: \t");
Quizzes = grade.nextShort();
PercentageWeights = (int)(Exam1 + Exam2 + finalExam + Labs + Projects + Attendance + Quizzes);
// The equation above will provide the sum of the percentage weights. Since the variables in the equation were
// originally declared as doubles, I had to put "int" before the actual equation.
if (PercentageWeights > 100 || PercentageWeights < 100) {
System.out.println("\nWeights do not add up to 100. Program exiting. Have a nice day!");
System.exit(0);
}
else {
System.out.println("\nEnter your scores out of a 100: \t");
}
// The part above is very important to continue the rest of the program. If the sum of the percentage weights equals 100,
// the program will continue to run. If the sum is greater than or less than 100, the program will terminate.
System.out.print("\nDo you know your Exam 1 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 1: ");
Exam1Grade = grade.nextDouble();
}
else{
Exam1Grade = 0;
}
System.out.print("\nDo you know your Exam 2 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 2: ");
Exam2Grade = grade.nextDouble();
}
else{
Exam2Grade = 0;
}
System.out.print("\nDo you know your final exam score?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nScore received on final exam: ");
finalExamGrade = grade.nextDouble();
}
else{
finalExamGrade = 0;
}
System.out.print("\nDo you know your lab average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage lab grade: ");
LabAverage = grade.nextDouble();
}
else{
LabAverage = 0;
}
System.out.print("\nDo you know your project average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage project grade: ");
ProjectsAverage = grade.nextDouble();
}
else{
ProjectsAverage = 0;
}
System.out.print("\nDo you know your quiz average?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nAverage quiz grade: ");
QuizzesAverage = grade.nextDouble();
}
else{
QuizzesAverage = 0;
}
System.out.print("\nDo you know your attendance average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage Attendance Grade: ");
AttendanceAverage = grade.nextDouble();
}
else{
AttendanceAverage = 0;
}
// The user has finished answering the questions. Now the program will automatically calculate the data based on
// what the user typed into the program.
double CurrentGrade, avgToFinalLetterGrade, WeightandGrade, finalOverallGrade;
// The doubles above need to be declared in order for the equations below to work properly.
WeightandGrade = (int)((Exam1 * Exam1Grade) + (Exam2 * Exam2Grade) + (finalExam * finalExamGrade) + (Labs * LabAverage) + (Projects * ProjectsAverage) + (Quizzes * QuizzesAverage) + (Attendance * AttendanceAverage));
CurrentGrade = (int)((WeightandGrade) / (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance ));
knownWeight = (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance);
if (grade.equals(A)){
finalOverallGrade = 90;
}
else if (grade.equals(B)){
finalOverallGrade = 80;
}
else if (grade.equals(C)){
finalOverallGrade = 70;
}
else if (grade.equals(D)){
finalOverallGrade = 60;
}
else
finalOverallGrade = F;
avgToFinalLetterGrade = (((100-finalOverallGrade) * (WeightandGrade)) / (100 - knownWeight));
// The equations above are one of the last parts of the program. These equations are critical to determine whether or not the user received its desired letter grade.
// If the desired grade was not reached, the program will give a score that the user must consistently receive in order to possibly reach the desired letter grade.
if (finalOverallGrade >= 90){
System.out.print("Congratulations! You got an A in the class! Hooray!");
}
else if (finalOverallGrade >=80 && finalOverallGrade < 90){
System.out.print("Good job. You got a B in the class!");
}
else if (finalOverallGrade >=70 && finalOverallGrade < 80){
System.out.print("You got a C in the class.");
}
else if (finalOverallGrade >=60 && finalOverallGrade < 70){
System.out.print("You got a D in the class.");
}
else
System.out.print("I'm sorry, but you have a failing grade in the class. May your GPA have mercy on your soul.");
}
}
There are quite a lot of things wrong with this code.
Doing double A=90-100; will set A equal to -10;
However, for your current question:
You do String input = grade.nextLine();
You never change input, and so if input isn't "yes", it will just skip getting the grades for each piece.
(You might want to also consult Using scanner.nextLine() for other pitfalls with using scanner.nextLine() intermixed with scanner.nextInt or similar [in summary: if you do scanner.nextInt, this doesn't consume the newline, so scanner.nextLine() will just get that newline and not the next line after that you might be expecting to get])
input = grade.nextLine() reads the remainder of the line with the user's "percentage weights" input on it. So unless the user had a priori knowledge to enter "yes", input will be empty.
I.e., you need to update input with user input before if (input.equalsIgnoreCase("yes")) {....

I am getting 3 illegal start of expression errors? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Please help me with this. I feel like this is really simple and I am probably going to feel really stupid when its all said and done. Thank You.
I have tried multiple things but none seem to work.
Yes, I am more familiar with Visual Basic than Java, that is why I am having this problem.
import java.util.Scanner;
public class YuGiOhLifePointCounter {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
double choice_1;
System.out.print("\nEnter the starting life points for player-1: ");
choice_1 = sc.nextDouble();
double storage_1;
storage_1 = choice_1;
double choice_2;
System.out.print("\nEnter the starting life points for player-2: ");
choice_2 = sc.nextDouble();
double storage_2;
storage_2 = choice_2;
double lp;
System.out.print("\nEnter a 6 to change the life-points of either player: ");
lp = sc.nextDouble();
double display_1 = choice_1;
double display_2 = choice_2;
while (lp == 6) {
/* Starting here*/
if (display_1 <== 0) {
System.out.println("Player-2 has won the game.");
System.exit(0);
}
if (display_2 <== 0) {
System.out.println("Player-1 has won the game.");
System.exit(0);
}
if (display_1 <> 0 && display_2 <> 0) {
/* these 3 if statements above are giving me illegal import errors, I can't figure out why. Thank You.*/
double choose_1_2;
System.out.print("\nEnter a 1 to change player-1's life-points, or enter a 2 to change player-2's life-points: ");
choose_1_2 = sc.nextDouble();
if (choose_1_2 == 1) {
double ch_1;
System.out.print("\nEnter the number subtracted from or added to player-1's life-points: ");
ch_1 = sc.nextDouble();
double c_1;
System.out.print("\nEnter a 1 to subtract this number from player-1's life-points, or enter a 2 to add this number to player-1's life-points: ");
c_1 = sc.nextDouble();
if (c_1 == 1) {
display_1 = storage_1 - ch_1;
System.out.println("\nPlayer-1's life-points are currently " + display_1);
}
if (c_1 == 2) {
display_1 = storage_1 + ch_1;
System.out.println("\nPlayer-1's life-points are currently " + display_1);
}
}
if (choose_1_2 == 2) {
double ch_2;
System.out.print("\nEnter the number subtracted from or added to player-2's life-points: ");
ch_2 = sc.nextDouble();
double c_2;
System.out.print("\nEnter a 1 to subtract this number from player-2's life-points, or enter a 2 to add this number to player-1's life-points: ");
c_2 = sc.nextDouble();
if (c_2 == 1) {
display_2 = storage_1 - ch_2;
System.out.println("\nPlayer-2's life-points are currently " + display_2);
}
if (c_2 == 2) {
display_2 = storage_1 + ch_2;
System.out.println("\nPlayer-2's life-points are currently " + display_2);
}
}
}
}
}
}
if (display_1 <= = 0)
if (display_1 <> 0)
Not sure what you're trying to do exactly, but these aren't right.
If you want to check for display_1 less than 0, then you need:
if (display_1 < 0)
If you want to check for display_1 less than or equal to 0, then you need:
if (display_1 <= 0)
If you want to check for display_1 equal to 0, then you want:
if (display_1 == 0)
If you want to check for display_1 not equal to 0, then you want:
if (display_1 != 0)

Categories

Resources