why can int not be deferenced? - java

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.

Related

How do I display calories from fat percent in Java

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 :)

Values are not initializing under try block?

trying to make program rotation of array, it was giving an Exception by user misinput so I use try block but now, under try block it is not initializing values....
Can some one tell the reason or solution for this....
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
ArrayRotation ar = new ArrayRotation();
System.out.println("Enter T : ");
int t = sc.nextInt();
sc.nextLine();
while(t!=0){
System.out.println("\nEnter N D : ");
String s = sc.nextLine();
s.trim();
String st[] = s.split(" ");
int n,d;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}catch(Exception e){ System.out.println("Exception"+e.getMessage()); }
System.out.println("Enter Element : ");
s=sc.nextLine();
st = s.split(" ");
ar.rotateArray(st,n,d);
t--;
}
}
If you need valid input and you did not get valid input, the thing to do is to try again to get valid input, after telling the user the input was invalid. Don't just proceed with the invalid data. You therefore need an inner loop:
while (t!=0) {
boolean validInput = false;
while (!validInput) {
System.out.println("\nEnter N D : ");
String s = sc.nextLine().trim();
String[] st = s.split(" ");
int n,d;
try {
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
validInput = true;
}
catch (Exception e) {
System.out.println("Invalid input");
}
}
… process n and d as before …
}
For my taste the loop to get the valid input would be better off being a subroutine in its own right - for clarity.
Variable in local scope should be initialized , that is what error , so do initialize the variables n and d to some integer value say as below
int n = 0 ,d = 0;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}
When a method throws an exception, that method never returns.
This means that if n = Integer.parseInt(st[0]); throws an exception, it does not return a value, which means n will not be assigned a value (since there is no return value to assign to it).
You are ignoring the exception and trying to continue as if nothing went wrong. But something did go wrong—n was never assigned a value. So the compiler tells you that it is not safe to use n in any subsequent code.
To solve this, you first must decide what to do if the user provides invalid input. You can’t just ignore the exception. If the input doesn’t represent two integers, you don’t have any values to work with. You can’t continue in any meaningful way.
The best course of action is to remove your try and catch. This will cause the program to terminate if Integer.parseInt fails, which is almost certainly what you want (unless your assignment requires you to do something different). Remember that it is not possible to continue in any meaningful way without values assigned to n and d.
In other words, change this:
int n,d;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}catch(Exception e){ System.out.println("Exception"+e.getMessage()); }
to this:
int n = Integer.parseInt(st[0]);
int d = Integer.parseInt(st[1]);
As a side note, this line does nothing:
s.trim();
…because Strings cannot be changed. s.trim() returns a new String which you must capture in a variable. You probably want to do this:
s = s.trim();
Your image is quite misleading and really doesn't point to the actual problem, it only points to what you perceive to be the problem. Your mistake was placing the initialization of variables n and d into a try block which takes your call to the rotateArray() method out of scope for that initialization of those variables.
The bigger problem is... What in the world are you rotating? Where is the Array to rotate? Is it actually a String Array or is it suppose to be an Integer Array? Please don't tell me it's the st[] String Array (which is what you're trying to do) because according to your code that array is used to establish the array size (n) portion to work with and the number of elements (d) the User wants to rotate by. No rocket science to rotate an Array with only two elements. Give the rotateArray() method an array to actually rotate.
Let's provide an Integer Array and a way to do this without a try/catch mechaism:
// The Array to carry out rotations on.
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
String ls = System.lineSeparator();
Scanner sc = new Scanner(System.in);
ArrayRotation ar = new ArrayRotation();
int t = 0;
String value = "";
while (value.equals("")) {
System.out.print("Enter Number of times to Rotate Array: --> ");
value = sc.nextLine().trim();
/* Make sure a String representation of a Integer value is supplied.
The regular Expression "\\d+" in the String#matches() method
ensures the a numerical integer string is supplied. */
if (!value.matches("\\d+" || value.length() > 9) {
/* Will handle situations where nothing is supplied, alpha
characters might be supplied, or the supplied numerical
value is outrageously large. */
System.out.println("Invalid integer numerical value supplied!" + ls);
value = "";
}
}
t = Integer.parseInt(value);
while (t != 0) {
System.out.println();
System.out.print("Enter the Size (portion) of the Array to consider and the" + ls
+ "number of elements to rotate (separated with a space): --> ");
String s = sc.nextLine().trim();
// Quit if anything starting with the letter "Q"
// (like "q" or "quit") is supplied.
if (s.substring(0, 1).equalsIgnoreCase("q")) {
System.out.println("\"Quit\" Supplied!");
System.exit(0);
}
String st[] = s.split(" ");
/* Make sure two values were supplied and that
they are both numerical integer strings. */
if (st.length != 2 || !st[0].matches("\\d+") || !st[1].matches("\\d+")) {
System.out.println("Invalid Input! Try again and make sure 'both' "
+ "values are numerical Integers.");
continue;
}
// Declare and initialize the n and d variables.
int n = Integer.parseInt(st[0]);
int d = Integer.parseInt(st[1]);
/* If the number of elements to rotate is greater
than the portion of array to rotate in. */
if (d >= n) {
System.out.println("Invalid Input! The size of the Array portion to rotate" + ls
+ "must be greater than the number of elements to rotate.");
}
/* If the supplied Array size to deal with is
out of bounds of the Array itself. */
else if (n < 1 || n > array.length) {
System.out.println("You have supplied an invalid Array Size! (" + n
+ ") Size must be between 1 and " + array.length + "!"
+ ls);
}
/* If the supplied number of elements to rotate
is less than 1 or greater than the total number
of elements - 1. */
else if (d < 1 || d > (array.length - 1)) {
System.out.println("You have supplied an invalid number of elements to rotate! (" + d
+ ") Value must be between 1 and " + (array.length - 1) + "!" + ls);
}
// All is good - Do the rotation.
else {
ar.rotateArray(array, n, d); // Rotate the Array
// Display the current rotation...
System.out.println("Current Rotation: --> " + Arrays.toString(array));
t--;
}
}
// Done
The error you outline in your image is a general compilation error and is relatively generic for all data types. This error occurs when you are trying to use a local variable without first initializing it. You won't get this error if you use a uninitialized class or instance variable because they are initialized with their default value (for example: Reference types are initialized with null and integer types are initialized with zero), but if you try to use an uninitialized local variable in Java, you will get this error. This is because Java has the rule to initialize the local variable before accessing or using them and this is checked at compile time. If the compiler believes that a local variable might not have been initialized before the next statement which is going to use it, you will receive this error. You of course will not get this error if you just declare the local variable but don't use it but then, why declare it in the first place.
Everyone is stating to initialize the local variables n and d because in reality, in order to successfully compile your code that is exactly what needs to be done in order for the rotateArray() method (which uses these uninitialized variables) to function. Again in reality, you do initialize them however your code does it within a try{} block which alters scope and the compiler is smart enough to know that if the initialization fails within the try{} block then the catch{} block could let that failure be ignored. In fact, if you were to place the call to the rotateArray() method within that try{} block then you would not get this compile time error since the call is within the scope of of where the variables n and d are actually initialized. You know, a decent IDE (line Eclipse, NetBeans, InteliJ, etc) should catch this error for you long before you try to compile.
According to your code, the actual intent of the try/catch blocks would be to handle the case of invalid input whereas a non-numerical integer value was supplied by the User. In this case it would be up to your catch{} block to handle that particular situation which should be to inform the User of the invalid input and then continue to re-prompt for proper input. At compile time the compiler really doesn't care about this mechanism since this would be a Runtime Error unless of course it is syntax related.
Nothing wrong with try/catch, I just like to avoid them if I can.

Java: Saving User Input to be Calculated in a Loop

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);

Debugger stops working

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.

Debugging School Project

Right, I am working on a program for school the purpose of the program is to find the minimum number of coins, I am a novice programmer and this is my first time so I dont know the thousands of other things and what not other people do. I wrote the code and it works, but I seem to have found a bug/glitch or w/e you want to call it.
my code
import java.util.Scanner;
public class Coin {
public static void main (String[] Args) {
int quarters = 25;
int dimes = 10;
int nickles = 5;
int pennies = 1;
System.out.println("Enter in a number between 1-99");
// "Input" Part of Code (Remember this and go back for reference)
Scanner Userinput = new Scanner(System.in);
int stuff = Userinput.nextInt();
int q = stuff/quarters;
String A = "Number of Quarters:" +q;
System.out.println(A);
int hold = stuff%quarters;
int d = hold/dimes;
String B = "Number of Dimes:" +d;
System.out.println(B);
int hold1 = stuff%dimes;
int n = hold1/nickles;
String C = "Number of Nickles:" +n;
System.out.println(C);
int hold2 = stuff%nickles;
int p = hold2/pennies;
String D = "Number of Pennies:" +p;
System.out.println(D);
System.out.println("Thank you for Using My Program");
}
}
Now, everything works fine I can input any number I like and get the desired result, however for some odd reason I cannot fathom I type in any number between 75-79 and there is an added Nickle for some odd reason and I have spent the better part of 2 hours trying to figure out exactly what is wrong but cannot. Hav tried dozens of toher numbers and they work fine except for that one little area.
Can someone tell me by chance what might be wrong?
Your hold = ... lines should be based on the previous hold value rather than the full amount (stuff).
int hold2 = hold%nickles;
You need to subtract off what has already been accounted for when adding previous, larger coins.
For example, if I say 77, then the program will check 77%10 and return 7. You would want to adjust your "stuff" value by any previously added coins. So in this case, after adding 3 quarters (75) we would want to set stuff = stuff - 75 (stuff -= 75).
EDIT: to be more precise, after every calculation you could run
stuff -= q * quarters;
of course, changing the variables to be appropriate for each part of your code.

Categories

Resources