Newbie here with 2 questions.
Question 1:
Where the program asks for the amount of calories, the operator in the "while" portion of the code is supposed to keep asking for the amount of calories until both sides of the operator is true. It is not. How do I fix that? example... If I enter fat at 20, and calories at 100, It should ask me again and again until I enter 180 or more (20 * 9).
Question 2:
I receive this error message after the getCalories function is completed:
"Exception in thread "main" java.lang.ArithmeticException: / by zero
at fatGramCalculator.main(fatGramCalculator.java:19)"
I understand you can not divide by zero but I thought when I entered fat at 20 it remained as the value of fat throughout the program?
Sorry kind of lengthy but I feel like I am very close to the working. Thank you for any and all feedback.
import java.util.Scanner;
public class fatGramCalculator{
static int fat, calorie, fatPercent;
//Module main
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
//Calls getFat function
getFat(fat);
//Calls getCalories function
getCalories(calorie);
//shows percent of fat
fatPercent = ((fat * 9) / calorie);
System.out.println("The percent of calories from fat is " + fatPercent + ".");
}
//getFat function
static int getFat(int fat){
Scanner keyboard = new Scanner(System.in);
do{
System.out.println("What is the amount of fat grams?");
fat = keyboard.nextInt();
}while (fat < 0);
return fat;
}
//getCalories function
static int getCalories(int calorie){
Scanner keyboard = new Scanner(System.in);
do{
System.out.println("What is the amount of calories?");
calorie = keyboard.nextInt();
}while ((calorie >= fat * 9) && (calorie <= 0));
return calorie;
}
}
Question 1: the calorie variable you are using in the getCalories has a method scope, so basically you need to assign the returned value from it to your static variable
In the main method :
fat = getFat();
calorie = getCalories();
And also don't pass it arguments, it seems kinda pointless because you are getting the value from keyboard input.
Question 2: global value declared as static calorie if not assigned anything will be 0, and you are not assigning it any value. Default int value is 0.
Don't worry for being newbie, keep coding :)
Related
I'm writing a while loop program and this problem keeps staying here and I'm not sure how to fix it. Keeps displaying "int cannot be dereferenced". I have done a ton of research on this problem and I don't know what am I doing wrong: read on google, read on StackOverflow and so on, but I don't know what to do. Tried the parsing technique but kept saying "scanner cannot convert string to int" Here is my code, any help would be appreciated. I could have declared the variable in the if and else if conditions, but I would like to keep track of what I am doing and I believe it's better to not repeat codes. (such as print out statement)
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner Data = new Scanner (System.in);
final int goldplated = 100, fourteen = 500, eighteen = 1000;
int total = 0, count = 1, size = 0;
String GetInfo = "";
System.out.println("How many times do you want to purchase:");
int EnterData = Data.nextInt();
while(count<=EnterData){
System.out.println("What Kind of Chain do you want to buy? Below are the list of options: \n 1 - gold plated \n 2 - 14k gold \n 3 - 18k gold");
//GetInfo = Data.next();
if (Data.equals("1")||Data.equals("gold plated")){
System.out.println("Please specify the length of the chain.");
size.nextInt();
total = size * goldplated;
}else if(Data.equals("2")||Data.equals("14k gold")){
System.out.println("Please specify the length of the chain.");
size.nextInt();
total = size * fourteen;
}else if(Data.equals("3")||Data.equals("18k gold")){
System.out.println("Please specify the length of the chain.");
size.nextInt();
total = size * eighteen;
}else{
System.out.println("Invalid operation");
} count++;
total+= size.nextInt();
System.out.println("This is your price: " + total);
}
}
}
nextInt() is a method in the Scanner class. So when you write something.nextInt(), the something part will have to be a Scanner object. And in your case, you've got a Scanner object, which you've called Data (not the best name for it, but never mind).
If you write Data.nextInt(), your program will wait for the user to type in a number, and return that number. That's what you want, but you'll want a variable to assign that number to, so that you can use it. That variable is size. So every time you've written size.nextInt(); in your program, what you actually need to write instead is size = Data.nextInt(); - that is, call the method on the Data object, and assign the result to the size variable.
I am working on this program with these instructions:
Bus Passengers: Write a program that is to be used to count how many passengers are travelling on
buses that pass a particular bus stop in a given hour. It should use a while loop to repeatedly ask the user to give the number of passengers on the bus that just passed. It should stop when the special code X is entered as the number of passengers. It should then give the number of buses and the total number of passengers counted in that hour. For example, one run might be as follows.
How many passengers were on the bus? 2
How many passengers were on the bus? 5
How many passengers were on the bus? 10
How many passengers were on the bus? 3
How many passengers were on the bus? 12
How many passengers were on the bus? 1
How many passengers were on the bus? 0
How many passengers were on the bus? X
There were a total of 33 passengers on 7 buses.
I am trying to fix an error:
Few points to note:-
You don't need System.exit()
In java variables are only accessible inside their scope i.e. the region they are created in.
I tried to rewrite code as following:-
import java.util.Scanner;
public class Bus {
int busCount =0;
int passengerCount =0;
Scanner scanner= new Scanner(System.in);
public static void main(String args[]){
Bus bus = new Bus();
bus.getResults();
}
private void addBusAndPassenger(String input){
try{
int a = Integer.parseInt(input);
busCount = busCount + 1;
passengerCount = passengerCount + a;
}catch(NumberFormatException e){
System.out.println("Please provide integer or X as input");
}
}
private void getResults(){
String a =null;
while (!("X".equals(a))){
System.out.print("How many passengers were on the bus? ");
a = scanner.nextLine();
if("X".equals(a))
break;
addBusAndPassenger(a);
}
System.out.println("There were a total of " + passengerCount + " passengers on " + busCount + " buses.");
}
}
A few things here. Other people pointed this out, but you need to pass parameters to your method. The method signature is there for a reason - your method calls must match the method signature you define.
Also, busInformation is supposed to return an int, but it returns nothing.
Also, this line:
Integer.parseInt(a);
does nothing - you throw away the result immediately. It won't modify the string in place or anything like that. (Well, I suppose that it'll throw an exception if they enter something other than an integer, but that doesn't seem to be what you're trying to do with this line).
At an absolute minimum, you should change the return type of your method to int and the change this line to return Integer.parseInt(a);.
(You also shouldn't be creating a new scanner every time like this - you should just re-use the same one).
Unfortunately, I can't attach my overall program (as it is not finished yet and still remains to be edited), so I will try my best to articulate my question.
Basically, I'm trying to take an integer inputted by the user to be saved and then added to the next integer inputted by the user (in a loop).
So far, I've tried just writing formulas to see how that would work, but that was a dead end. I need something that can "save" the integer entered by the user when it loops around again and that can be used in calculations.
Here is a breakdown of what I'm trying to make happen:
User inputs an integer (e.g. 3)
The integer is saved (I don't know how to do so and with what) (e.g. 3 is saved)
Loop (probably while) loops around again
User inputs an integer (e.g. 5)
The previously saved integer (3) is added to this newly inputted integer (5), giving a total of (3 + 5 =) 8.
And more inputting, saving, and adding...
As you can probably tell, I'm a beginner at Java. However, I do understand how to use scanner well enough and create various types of loops (such as while). I've heard that I can try using "var" to solve my problem, but I'm not sure how to apply "var". I know about numVar, but I think that's another thing entirely. Not to mention, I'd also like to see if there are any simpler solutions to my problem?
Okay So what you want is to store a number.
So consider storing it in a variable, say loopFor.
loopFor = 3
Now we again ask the user for the input.
and we add it to the loopFor variable.
So, we take the input using a scanner maybe, Anything can be used, Scanner is a better option for reading numbers.
Scanner scanner = new Scanner(System.in);//we create a Scanner object
int numToAdd = scanner.nextInt();//We use it's method to read the number.
So Wrapping it up.
int loopFor = 0;
Scanner scanner = new Scanner(System.in);//we create a Scanner object
do {
System.out.println("Enter a Number:");
int numToAdd = scanner.nextInt();//We use it's method to read the number.
loopFor += numToAdd;
} while (loopFor != 0);
You can just have a sum variable and add to it on each iteration:
public static void main(String[] args) {
// Create scanner for input
Scanner userInput = new Scanner(System.in);
int sum = 0;
System.out.println("Please enter a number (< 0 to quit): ");
int curInput = userInput.nextInt();
while (curInput >= 0) {
sum += curInput;
System.out.println("Your total so far is " + sum);
System.out.println("Please enter a number (< 0 to quit): ");
}
}
You will want to implement a model-view-controller (mvc) pattern to handle this. Assuming that you are doing a pure Java application and not a web based application look at the Oracle Java Swing Tutorial to learn how to build your view and controller.
Your model class is very simple. I would suggest just making a property on your controller that is a Java ArrayList of integers eg at the top of your controller
private Array<Integer> numbers = new ArrayList<Integer>();
Then your controller could have a public method to add a number and calculate the total
public void addInteger(Integer i) {
numbers.addObject(i);
}
public Integer computeTotal() {
Integer total = 0;
for (Integer x : numbers) {
total += x;
}
return total;
}
// This will keep track of the sum
int sum = 0;
// This will keep track of when the loop will exit
boolean errorHappened = false;
do
{
try
{
// Created to be able to readLine() from the console.
// import java.io.* required.
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
// The new value is read. If it reads an invalid input
// it will throw an Exception
int value = Integer.parseInt(bufferReader.readLine());
// This is equivalent to sum = sum + value
sum += value;
}
// I highly discourage the use Exception but, for this case should suffice.
// As far as I can tell, only IOE and NFE should be caught here.
catch (Exception e)
{
errorHappened = true;
}
} while(!errorHappened);
My program needs to allow the user to input an employee's name and total annual sales. When the user is finished adding employees to the array, the program should determine which employee had the highest sales and which had the lowest sales. It should then print out the difference between the two numbers.
In my code below, I have a totalPay class that holds the annual sales input by the user (it includes other variables and methods from a previous assignment that are not used here). The salesPerson class holds the employee's name and totalPay object, which includes their annual sales. (I realize this is overcomplicated, but I'm modifying my previous assignment rather than starting from scratch.)
When I run this code, it allows me to enter the name and sales, but when I enter "yes or no" to add another employee, it crashes and tells me there is a NullPointerException on line 58, noted in the code.
I've ran the debugger (without any breakpoints) and it just stops at line 46, noted in the code. It doesn't give an error message, it just doesn't update that variable and my "step into" buttons for the debugger grey out and I can't click them anymore. (I'm using NetBeans, if that's relevant.)
Any ideas would be much appreciated!
EDIT: Here is the output and error message.
Name? captain America
Input annual sales: 80
Add another employee? yes or no
no
Exception in thread "main" java.lang.NullPointerException at commission.Commission.main(Commission.java:58)
package commission;
//Commicaion calulator
import java.util.Scanner;
public class Commission
{
public static void main(String args [])
{
salesPerson[] emps = new salesPerson[10]; //Employee Array
String cont = "yes";
String n="";
double s=0;
int i=0;
salesPerson high = new salesPerson();
salesPerson low = new salesPerson();
// scanner object for input
Scanner keyboard = new Scanner(System.in);
//Enter in employee name
while (cont == "yes"){
System.out.print("Name? ");
n = keyboard.nextLine();
emps[i] = new salesPerson();
emps[i].setName(n);
//Loop of yes or no entering more employees
//If yes add another name if no continue with total Commision
//Enter in the sales amount of commistion
System.out.print("Input annual sales: ");
s=keyboard.nextDouble();
emps[i].pay.annual = s;
System.out.println("Add another employee? yes or no ");
keyboard.nextLine();
cont = keyboard.next(); //Line 46: Debugger stops here.
if (cont =="yes")
i++;
if (i==9){
System.out.println("You have reached the maximum number of employees.");
cont = "no";
}
}
i=0;
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual) //Line 58: It claims the error is here.
high = emps[i];
if (emps[i].pay.annual < low.pay.annual)
low = emps[i];
}
double diff = high.pay.annual - low.pay.annual;
System.out.println("Employee "+low.getName()+" needs to earn "+diff+" more to match Employee "+high.getName());
// Output table for composation with increments of $5000
// int tempAnnual =(int) pay.annual;
// for (i=tempAnnual; i<= pay.annual; i+=5000)
// System.out.println(i+" "+ pay.getReward(i));
}
public static class totalPay
{
double salary=50000.0; //Yearly earned 50000 yr fixed income
double bonusRate1=.05; //bounus commission rate of 5% per sale
double commission; //Commission earned after a sale
double annual; //Sales inputted
double reward; // Yearly pay with bonus
double bonusRate2= bonusRate1 + 1.15 ; // Sales target starts at 80%
public double getReward(double annual)
{
double rate;
if (annual < 80000)
rate=0;
else if ((annual >= 80000) || (annual < 100000 ))
rate=bonusRate1;
else
rate=bonusRate2;
commission = annual * rate;
reward=salary + commission;
return reward;
}
}
public static class salesPerson
{
String name; //Employee Name
totalPay pay = new totalPay();
public void setName(String n) //Name
{
name=n;
}
public String getName()
{
return name;
}
}
}
You create this array of max size 10:
salesPerson[] emps = new salesPerson[10];
but only create and assign an object reference for each SalesPerson object entered. Since you only enter 1 name, only the 1st entry in the array is valid, then remaining 9 are null. You then attempt to iterate through the entire array (emps.length is 10 ):
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual)
which leads to the NPE when indexing the first null reference. You need to change your loop to something like:
int numEntered = i; //last increment
for (i=0; i< numEnetered; i++){
if (emps[i].pay.annual > high.pay.annual)
It stops the debugger because it waits for your input using the keyboard. If you type the input and hit enter, the debugger will continue from there on.
By the way, your should read up on naming conventions and coding best practices for java
Your debugger is stopped because it's blocked on input coming in from the Scanner. This is specified in the documentation:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
That aside, you're fortunate to have entered that code block at all. You're comparing Strings incorrectly, so at a glance it'd look like you wouldn't enter that loop except under certain special circumstances. This is also the reason that your NPE occurs; you're initializing elements of your array under false pretenses (== with a String), so:
You may never initialize anything
You may only initialize the first thing (if (cont =="yes"))
I've only gone over a few of the high points, but for the most part, the blocking IO is why your debugger has stopped. The other errors may become easier to see once you start using .equals, but I'd encourage you to get an in-person code review with a classmate, tutor, or TA. There are a lot of misconceptions strewn about your code here which will make it harder to debug or fix later.
This is my first post and I have been searching google and stack overflow for the past 24 hours and can not seem to pin down my problem.
I am creating a simple square root program. For the input section I start a 'while' loop. I need it to compare two conditions.
1. is the input a number
2. is the input a number over ten.
I was successful in creating the original program, however I ran into a small problem while debugging. When I put in a vary large decimal or number I would get a run time error.
I discovered that I could use BigDecimal() to solve this problem.
However I am now running into a logic error that I cannot solve no matter how many times I search the internet.
The two conditions that I use in the while loop are:
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
This will make sure that there is a BigDecimal, but will not make sure that the input number is over ten.
Here is the whole program
import java.math.BigDecimal;
import java.util.Scanner;
/**
#author Mike
*/
public class SquareRootingWithoutBigDecimal
{
public static void main( String [] args )
{
Scanner scan = new Scanner(System.in);
double inputNumber = 0.00;
double rootedNumber = inputNumber;
BigDecimal inputNumberBig = new BigDecimal(0.00);
BigDecimal SENTINAL = new BigDecimal(10.00);
String garbage;
double garbageD = 0.00;
System.out.println("Please Enter a number to be Square rooted"
+ "\nThe number must be 10 or greater ");
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
{
garbage = scan.nextLine();
System.out.println("Please Enter a number to be Square rooted"
+ "\nThe number must be 10 or greater ");
}
inputNumberBig = scan.nextBigDecimal();
inputNumber = inputNumberBig.doubleValue();
rootedNumber = inputNumber;
do
{
rootedNumber = Math.sqrt(rootedNumber);
System.out.println(rootedNumber);
} while (rootedNumber >= 1.01 );
}
Any and all help is much appreciated.
-Mike
inputNumberBig = scan.nextBigDecimal();
inputNumber = inputNumberBig.doubleValue();
These HAVE to go before you while loop for your logic to work.
Also,
while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
I could see this causing a problem. You should use && instead of ||