How to connect user input to calculation java - java

I'm a BEGINNER in java. My project is a simple calorie counter.
The way it should work:
Enter calorie intake number: (user adds number)
program subtract users input by 2,000 calories
As of now, my program is subtracting the parameter for the food object from the 2,000 cal. I know this because I'VE DONE A LOT OF TESTING TRYING TO FIGURE OUT THE SOLUTION TO THIS PROBLEM MYSELF. If i had not changed the parameters for the cheesecake flavors methods to include a string and an integer, than it would have subtracted the calorie int from the last listed cake flavor(carmel) that held the variable calorie.
The problem:
I can seem to figure out how to connect the user input to the calorie calculation coded in the food class above the main. I've also tried changing the Scanner input variable to the calorie variable, but it then could not be resolved.
I'm listening my code now below. I'd be very grateful to anyone that could help me. Please remember, I'm a beginner, and read everything i've written before responding.
Thank you
int calculateCaloriesLeft() {
int caloriesLeft = 2000 - calories;
return caloriesLeft;
}
Scanner input = new Scanner(System.in);
System.out.println("Enter calorie of food: ");
int value = 0;
value = input.nextInt();
value = deserts.calculateCaloriesLeft();
System.out.println("calories left: " + value);
}
}

You are not passing the entered value into the calculateCaloriesLeft method. You would need to add a parameter and pass the users input into it.
Scanner input = new Scanner(System.in);
System.out.println("Enter calorie of food: ");
int value = 0;
value = input.nextInt();
value = deserts.calculateCaloriesLeft(value);
System.out.println("calories left: " + value);
And your method would be
int calculateCaloriesLeft(int userCalories) {
int caloriesLeft = 2000 - userCalories;
return caloriesLeft;
}

Related

I'm trying to call a method through a for loop, and the first iteration will only read the first line of code in the method

I'm trying to use an enhanced for loop to call a method many times in a row, but if I'm iterating more than once, the first iteration will only read the first line of code. Here are both of the methods I'm using:
public Account() {
this.subDetails = new HashMap<Integer, String>();
System.out.println("What is the account type? (Individual/Family)");
String planType = keyboard.nextLine();
System.out.println("Enter your card number: ");
this.cardNum = keyboard.nextLine();
System.out.println("Enter the expiration date: ");
this.cardExp = keyboard.nextLine();
if (planType.equals("Family")) {
System.out.println("How many users?");
int numUsers = keyboard.nextInt();
for (int z=0; z<numUsers; z++) {
this.addUser();
}
StreamingService.numFamUsers = StreamingService.numFamUsers + numUsers;
StreamingService.monthlyRevenue = StreamingService.monthlyRevenue + 14.99;
StreamingService.monthlyFamRevenue = StreamingService.monthlyFamRevenue + 14.99;
}
else if (planType.equals("Individual")) {
this.addUser();
StreamingService.numIndUsers++;
StreamingService.monthlyRevenue = StreamingService.monthlyRevenue + 9.99;
StreamingService.monthlyIndRevenue = StreamingService.monthlyIndRevenue + 9.99;
}
StreamingService.numAccounts++;
this.subDetails.put(i, planType);
i++;
}
public void addUser() {
System.out.println("What is the email of the next user?");
String e = keyboard.nextLine();
User y = new User(e, i);
StreamingService.userEmails.add(y);
StreamingService.numUsers++;
this.acctUsers.add(e);
}
And here is the output (Data quality is poor, just used as an example):
What is the account type? (Individual/Family)
Individual
Enter your card number:
1234123412341234
Enter the expiration date:
02/24
What is the email of the next user?
abc#def.com
What is the account type? (Individual/Family)
Family
Enter your card number:
1234123412341234
Enter the expiration date:
02/24
How many users?
3
What is the email of the next user? What is the email of the next
user?
abc#def.com
What is the email of the next user?
abc#defg.com
What is the account type? (Individual/Family)
Family
Enter your card number:
1234123412341234
Enter the expiration date:
02/24
How many users?
2
What is the email of the next user? What is the email of the next
user?
xyz#abc.com
Does anyone know how to fix this?
Scanner.nextInt does NOT consume the newline-charakter you enter after the nubmers. Because of this, any readline afterwards will consume the newline - and stop, becasue that's what it does.
Because of this, the first email prompt after entering the number of users will always return an empty string. You can see this in your output: it's the cases where the email prompt is duplicated.
To fix this, put a call to keyboard.nextLine() after all of your keyboard.nextInt() calls (and just ignore the output of that function).

Stuck While Loop (Java)

all!
I'm a university freshman computer science major taking a programming course. While doing a homework question, I got stuck on a certain part of my code. Please be kind, as this is my first semester and we've only been doing Java for 3 weeks.
For context, my assignment is:
"Create a program that will ask the user to enter their name and to enter the number of steps they walked in a day. Then ask them if they want to continue. If the answer is "yes" ask them to enter another number of steps walked. Ask them again if they want to continue. If they type anything besides "yes" you should end the program by telling them "goodbye, [NAME]" and the sum of the number of steps that they have entered."
For the life of me, I can not get the while loop to end. It's ignoring the condition that I (probably in an incorrect way) set.
Can you please help me and tell me what I'm doing wrong?
import java.util.Scanner;
public class StepCounter
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
final String SENTINEL = "No";
String userName = "";
String moreNum = "";
int numStep = 0;
int totalStep = 0;
boolean done = false;
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
// Prompt for the user's name
System.out.print("Please enter your name: ");
userName = in.nextLine();
while(!done)
{
// Prompt for the number of steps taken
System.out.print("Please enter the number of steps you have taken: ");
// Read the value for the number of steps
numStep = in.nextInt();
// Prompt the user if they want to continue
System.out.print("Would you like to continue? Type Yes/No: ");
// Read if they want to continue
moreNum = in2.nextLine();
// Check for the Sentinel
if(moreNum != SENTINEL)
{
// add the running total of steps to the new value of steps
totalStep += numStep;
}
else
{
done = true;
// display results
System.out.println("Goodbye, " + userName + ". The total number of steps you entered is + " + totalStep + ".");
}
}
}
}
To compare the contents of String objects you should use compareTo function.
moreNum.compareTo(SENTINEL) return 0 if they are equal.
== operator is used to check whether they are referring to same object or not.
one more issue with addition of steps, addition should be done in case of "No" entered also
Use
if(!moreNum.equals(SENTINEL))
Instead of
if(moreNum != SENTINEL)
Also, make sure to add: totalStep += numStep; into your else statement so your program will actually add the steps together.

Runtime Ignoring While Loops?

I am new to the forums so first of all I'd like to say "Hi"! I'm new to Java programming and am trying to make a simple payroll calculating program with three while loops.
The first while loop keeps the program going until the user enters the sentinel "stop". The second and third loops are error traps that ensure the user enters a positive number before continuing.
For some reason, the while loops are not working and I have tried every variation I can think of. The program runs just fine, it just ignores the while loops. If someone could provide some suggestions as to what I'm doing wrong, I'd really appreciate it.
I'm using NetBeans 8.0 IDE if that helps.
Here is my code:
Import java.util.*;
Import java.text.*;
public class PayrollProgramVersion2
{
//begin main program
public static void main(String[] args)
{
//declare new scanner
Scanner sc = new Scanner (System.in); // declare new scanner object
DecimalFormat Dollars = new DecimalFormat ("$0.00"); //format for dollars
String Employee; //employee's name
Double Hours, //hours worked
Rate, //pay rate
Pay; // Hours * Rate
Boolean Continue = true; // sentinel for program loop
//welcome user, prompt for employee name, and assign input to Employee
System.out.println ("Welcome to the payroll program!");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
// while loop continues program until user enters "stop"
while (Continue == true)
{
if (Employee.equalsIgnoreCase("stop"))
{
Continue = false;
} // end if
else
{
//prompt for hours worked and assign to Hours
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Hours < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
}
//prompt for pay rate and assign to Rate
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Rate < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
}
Pay = Hours * Rate; // calculate payrate
//display results
System.out.println(Employee+ "'s paycheck is " +(Dollars.format(Pay))+ ".");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
} //end else
} //end while
System.out.println ("Thank you for using the payroll program. Goodbye!");
} // end main
} // end program
From what I can see you should make your while (hours<0) to while (hours<0 || hours == null).
This is because... As far as I can see you initialise hours. But no value is input into it. So it remains as null. You could also try changing the while to an if.
Hope this helps. It may be that it does default to 0 but it may be worth for testin purposes to have a console output.
System.out.println(hours);
Befor the while loop to see what your program is reading hours as.
Hope this helps.
The error is that nextDouble does not eat the newline. It skips newlines at the beginning, so in effect only the last nextDouble is concerned.
Best to make a utility function:
Instead of
Hours = sc.nextDouble();
call your own function:
Hours = nextDouble(sc);
private static double nextDouble(Scanner sc) {
double value = -1.0;
if (sc.hasNextDouble()) {
value = sc.nextDouble();
}
sc.nextLine();
return value;
}
Use a small initial letter for field and method names.
Use double/boolean/int instead of the Double/Boolean/Integer as the latter are Object wrappers (classes); the first primitive types.
Call sc.close(); (for good order).
Aside from what has been said above:
sc.nextDouble consumes and returns the next input from the current line. It does not forward the line.
sc.nextLine consumes and returns the input from the current line and forwards to the next line
At the end of your while loop you call Employee = sc.nextLine(); If you follow your logic and only input allowed values, this will always return an empty string as it consumes the current line where your most previously removed double was stored(now empty string "")
When you do something like:
Hours = sc.nextDouble();
you trust the user to enter a double value, and in case the user entered illegal value, a String for example, this line will throw an exception.
You can solve it like this:
while (Hours < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println ("How many hours did " +Employee+ " work?");
String hours = sc.nextLine();
try {
Hours = Double.valueOf(hours);
}
catch (NumberFormatException e) {
// keep looping until we get a legal value
Hours = -1.0;
}
}

Java Loop/User Input from Scanner

Making just a simple basketball program where I ask for the home team name, how many games are in the season, and then in a loop ask for the next team game. Basically when I start the do-while loop, it works great, unless the user types in for example, "Ohio State." The out put will then go from "6 games remaining" to "4 games remaining" for example. Usually it will just ask opponent?, then decrement by one game.
How can I fix so that a 2 word basketball team name doesn't decrement twice?
import java.util.Scanner;
public class Basketball2 {
public static void main(String[] args) throws java.io.IOException {
Scanner scanInput = new Scanner(System.in);
String sHomeTeam;
String sAwayTeam;
int iNumGames;
int iGamesLeft = 0;
System.out.println("Enter home team's name: ");
sHomeTeam = scanInput.nextLine();
System.out.println(sHomeTeam);
System.out.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
System.out.println(iNumGames);
//start looping
do {
System.out.println("Enter opponent team's name: ");
sAwayTeam = scanInput.next();
System.out.println(sAwayTeam);
iGamesLeft = --iNumGames;
System.out.println("There are " + iGamesLeft + " games left in the basketball season");
}//end do
while(iGamesLeft > 0);
Replace: sAwayTeam = scanInput.next(); with sAwayTeam = scanInput.nextLine(); The reason it loops twice is because scanInput.next(); only returns one token (e.g. word) at a time. When you enter two words it doesn't need receive more input from the user before continuing a second time because it already has another word to return. Hence the double loop.
You also need to take care of the line of code that calls nextInt(). This works like the next() method, but, instead of a token (word), it scans in just one character as an int. Try this: after iNumGames = scanInput.nextInt(); put scanInput.nextLine(); This should clear scanInput of anything that is making it skip. Note: because of the way that your code is written, this will only read one character. If you need to read more than one character you should use nextLine() and assign its value to an integer.
Whatever is said in the answer given by Donny Schrimsher is correct. All that you have to do now is after getting the number of games in the home team's basketball season i.e.
System.out.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
You have to add
scanInput.nextLine();
This is because after entering the number of games you press enter key (end of line) and nextInt() method takes the number of games and not the end-of-line. This end-of-line is consumed by the nextLine() method which Donny Schrimsher mentioned in the do-while loop. SO to avoid this you add an extra nextLine() method.
Thus it has to be
System.out.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
scanInput.nextLine();
System.out.println(iNumGames);
plus the changes mentioned by Donny Schrimsher.
Thanks
try below code with all exit functionality also.
import java.util.Scanner;
public class Basketball2 {
public static void main(String[] args) throws java.io.IOException {
Scanner scanInput = new Scanner(System.in);
String sHomeTeam;
String sAwayTeam;
int iNumGames;
int iGamesLeft = 0;
System.out.println("Enter home team's name: ");
sHomeTeam = scanInput.nextLine();
System.out.println(sHomeTeam);
System.out
.println("How many games are in the home team's basketball season?");
iNumGames = scanInput.nextInt();
System.out.println(iNumGames);
// start looping
do {
System.out.println("Enter opponent team's name: ");
scanInput = new Scanner(System.in);
sAwayTeam = scanInput.nextLine();
if(!"".equals(sAwayTeam.trim()) && !"exit".equals(sAwayTeam.trim()))
{
System.out.println(sAwayTeam);
iGamesLeft = --iNumGames;
System.out.println("There are " + iGamesLeft+ " games left in the basketball season");
}
}// end do
while (iGamesLeft > 0 && !"exit".equalsIgnoreCase(sAwayTeam));
}
}
Subject: 'Java Loops' with Scanner
The simple Java program I wrote is working perfectly, you can try for yourself...and you also can convert this program easily into 'while loop', 'do - while loop' and 'for - each loop'.
Rafiq,
VA, USA,
Dated: 04/17/2015
//Examples: 'for loop' with Scanner
package com.java_basics;
import java.util.Scanner;
public class ForLoop_Examples_With_Scanner
{
public static void main(String[] args)
{
//Creating instance of Scanner to allows a user's input to read from System.in
Scanner mySC = new Scanner(System.in);
System.out.println("Please, enter the value of 'int i' between '0 and 2' : ");
int i = mySC.nextInt();
System.out.println("Please, enter the value of 'exitPoint' between '10 and 1000' :");
int exitPoint = mySC.nextInt();
System.out.println("Please, enter the value of 'increment' between '1 and 2' :");
int increment = mySC.nextInt();
mySC.close();//Releasing memory to the OS (Operating System) for reuse
System.out.println("Output:\n" + "======");
for(;i<exitPoint ; i=i+increment)//i++==>i=i+1==>i=i+increment
{
System.out.println(i);
}
}
}

Print formatting while taking user input

I have a college assignment where I need to print out items sold by a hardware store, take input from a user, perform some calculations on that input, and then print out an invoice.
I have been able to successfully print out the items sold by the hardware store, but am encountering problems with the while loop that takes the input.
The program asks the user to enter a CODE and then asks for the corresponding QUANTITY. This works fine on the first iteration of the loop, but on the second iteration the user prompts for "CODE:" and "QUANTITY:" appear on the same line, despite my use of println when prompting the user.
I would greatly appreciate a detailed response appropriate for someone new in programming.
Here's the code:
import java.util.Scanner;
class HardwareStore {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO THE HARDWARE STORE!");
System.out.println("----------------------------------------------------------------------");
String sticky = "G22";
String keyring = "K13";
String screwy = "S21";
String padlock = "I30";
int stickyprice = 10989;
int keyringprice = 5655;
int screwyprice = 1099;
int padlockprice = 4005;
System.out.println("CODE\t\tDESCRIPTION\t\t\t\t\tPRICE");
System.out.println("----\t\t-----------\t\t\t\t\t-----");
System.out.println(sticky + "\t\tSTICKY Construction Glue, Heavy Duty, \n\t\t7oz, 12 Pack \t\t\t\t\t$" + stickyprice);
System.out.println(keyring + "\t\tCAR-LO Key Ring, Quick Release, \n\t\t1 Pack\t\t\t\t\t\t$ " + keyringprice);
System.out.println(screwy + "\t\t!GREAT DEAL! SCREW-DUP Screwy Screws, \n\t\tDry Wall Screws, 3 in. Long, 50 Pack\t\t$ " + screwyprice);
System.out.println(padlock + "\t\tLET-IT-RAIN, Weather Proof Padlock, \n\t\tPortable, One Push Functionality\t\t$ " + padlockprice);
System.out.println("----------------------------------------------------------------------");
int i = 10000;
String [] usercode = new String[i];
int [] userquantity = new int[i];
System.out.println("PLEASE ENTER YOUR ORDER:");
while (true) {
System.out.println("CODE: (X to terminate)");
usercode[i] = in.nextLine();
if (usercode[i].equalsIgnoreCase("x")) {
break;
}
System.out.println("QUANTITY: ");
userquantity[i] = in.nextInt();
}
}
}
when you enter the QUANTITY you're pressing enter. That newline character isn't used by in.nextInt();, it remains in the scanner buffer, until you roll around to in.nextLine() again.
At that point in.nextLine() reads until it finds a newline character, which just happens to be the next one in the buffer. So it skips straight to QUANTITY again.

Categories

Resources