How to accumulate a value in java? - java

Right now, I'm learning all about class, constructors and instances. I've made a small bit of code in java and I'm stuck with this particular code.
***MY CODE OUTPUT IS SUPPOSE TO BE LIKE THIS:
OUTPUT
Enter amount:500
Do you want to enter amount again?(y/n):y
Enter amount:45
Do you want to enter amount again?(y/n):n
TOTAL:545
***BUT INSTEAD MY OUTPUT IS LIKE THIS:
OUTPUT
Enter amount:500
Do you want to enter amount again?(y/n):y
Enter amount:45
Do you want to enter amount again?(y/n):n
TOTAL:45
***It is not adding the amount that I enter throughout the loop and instead, it is giving me the very last amount that I input.
Here is the first code:
public class Test {
private double money;
public Test(){
}
public void addPoints(double money1){
money += money1;
}
public int getMoney(){
return money;
}
}
and the second code is here:
import java.util.Scanner;
public class testBody {
public static void main(String[]args){
double cashMoney;
String response = "";
Scanner hold = new Scanner(System.in);
do{
System.out.print("Enter amount:");
cashMoney = hold.nextDouble();
Test cashPlus = new Test();
cashPlus.addPoints(cashMoney);
System.out.print("Do you want to enter amount again?(y/n):");
response = hold.next();
if(response.equalsIgnoreCase("n")){
System.out.print("TOTAL: " + cashPlus.getMoney());
}
}while(response.equalsIgnoreCase("y"));
}
}

You should create the Test instance before the loop instead of in each iteration.
Test cashPlus = new Test();
do {
System.out.print("Enter amount:");
cashMoney = hold.nextDouble();
cashPlus.addPoints(cashMoney);
System.out.print("Do you want to enter amount again?(y/n):");
response = hold.next();
if(response.equalsIgnoreCase("n")){
System.out.print("TOTAL: " + cashPlus.getMoney());
}
} while(response.equalsIgnoreCase("y"));
Each time you create a new Test instance, cashMoney is initialized to 0 (since each instance has its own value of that member). When you finally print cashPlus.getMoney(), you print the value of the last instance you created, to which you only added the final amount you entered.

In the line Test cashPlus = new Test(); you are creating a new Test object every time a value is entered. This effectively resets the already existing sum, because in the new class Test.money equals 0 again.

The issue is this line being inside the do/while loop:
Test cashPlus = new Test();
The Test class object holds the variable money (which is initialized to 0) and you are creating a new instance of it with each iteration of the do/while loop, thus resetting cashPlus.money to 0.
Just move that line before of the do/while and you should be fine!

In the loop , you are creating
Test cashPlus = new Test();
with this statement every time you are creating new object and adding sum to it. In all it is added to a new value as with new object it initialized to 0.
To avoid this instantiate the
Test cashPlus = new Test();
before starting the loop.

replace
private double money;
with
private static int money;
Everytime you set the value, it becomes 0. To pertain the value make it a static variable.
Note that the return type of getMoney is int and the datatype of money is double. This has to be type-casted or changed to similar data-type.

Related

why can int not be deferenced?

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.

How to make Java ignore previous instructions if specified sum is given?

Literally started with Java today, and my professor has given my class the task of modifying some very basic code.
I want to modify the code to make it print a message if the sum of n1 and n2 is 666, but I don't want it to print the actual sum or the message that would normally go attached to it. I saw somewhere around here that a similar question was asked, but the solution doesn't seem to work for me. I have no idea why. Please help.
import java.io.Console;
import java.util.Scanner;
public class FirstProgram{
Console t = new Console();
public static void main(String[] args)
{
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
int n1, n2;
Scanner keyboard = new Scanner(System.in);
n1 = keyboard.nextInt( );
n2 = keyboard.nextInt( );
//This should print normally when the sum is anything BUT 666
System.out.println("The sum of those two numbers is");
System.out.println(n1 + n2);
//If the sum IS 666, I don't want it to print the above lines, just the one below.
if (n1 + n2 == 666);
t.println("Nice try, Satan");
}
}
It gives two major errors: the constructor Console() is not visible, and that I cannot make a static reference to a non-static field t. I have no idea what any of that means or how to fix it.
You should learn how to make conditional statements. Java will not "ignore" and pass to another thing if you don't tell it how to do that. Remeber: computer can't do anything if one do not tell it to do and how to do that.
You are not initializing n1 and n2, they should be initialized after getting the value from the input.
And as said in the comments, always wrap loops, conditional statements within curly braces{} to make sure the code that will be executed be the one inside braces.
import java.util.Scanner;
public class FirstProgramm{
public static void main(String[] args){
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
Scanner keyboard = new Scanner(System.in);
int n1 = keyboard.nextInt( );
int n2 = keyboard.nextInt( );
//See? the result is stored inside this variable
int sum = n1 + n2;
//If the sum is equal 666 then print the message
if(sum == 666) {
System.out.println("Nice try, Satan");
}else {
//Else if the sum is something else, print it
System.out.println("The sum of those two numbers is");
System.out.println(sum);
}
}
}
You can even play with the operator that the if uses to evaluates the condition:
if(sum != 666) { //If sum is `not equal to` 666... if the sum is anything else than 666, print it
System.out.println("The sum of those two numbers is");
System.out.println(sum);
}else {// But if it is 666, print what is inside the parentheses
System.out.println("Nice try, Satan");
}
I will try to help you out here.
Firstly: the constructor Console() is not visible
I think this is in reference to the fact that Console was not really meant to be accessed like that. The constructor of Console is private, meaning that outside classes cannot access it. To remedy this issue, when you want to print to the console, use System.console.
Secondly: I cannot make a static reference to a non-static field t
This one is a bit difficult to explain to someone new. Your main function is static, which means it can be accessed without having to instantiate the class that contains it. Your variable t is a instance variable, meaning that it can be accessed by every function in the class when the class has be initialized. However, because the main function is static, you cannot access a non-static variable, because it may not be initialized yet. If you want to access a instance variable in a static function, you need to make that variable static as well, making it a class variable, which will always be accessible.
Lastly
To getting your code working, you need to read up on if statements. This is a conditional statement that is basically asking if this statement is true, do this. There is an else if and else statements as well that say else if this statement is true, do this and else do this.
Example of proper if/else if/else statement:
if(iAmTrue == true)
{
//do this
}
else if(theOtherIAmTrue == true)
{
//do this
}
else
{
//do this because everything else was not true
}
So to fix your code, you would need to do this:
if(n1 + n2 == 666)
{
System.out.println("Nice try, Satan");
}
else
{
//Put your other print message(s) here.
}
I have rewritten the code for you with a few recommendations to achieve what you need.
import java.util.Scanner;
public class FirstProgram {
// I have removed the Console variable, you don't need that.
// System.out.println prints to the console.
// Use constants for any number or string used to give them meaning
private static final int DEVILS_NUMBER = 666;
public static void main(String[] args) {
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
Scanner keyboard = new Scanner(System.in);
// declare variables next to where they are used.
// additionally, never declare more than one variable per line.
// never do this: int n1, n2;
int n1 = keyboard.nextInt();
int n2 = keyboard.nextInt();
// store the sum in a variable so you can refer to it without doing the sum many times
int sum = n1 + n2;
//If the sum IS DEVILS_NUMBER, I don't want it to print the above lines, just the one below.
// always test the positive possibility first, never the negation
if (DEVILS_NUMBER == sum) {
System.out.println("Nice try, Satan");
} else {
//This should print normally when the sum is anything BUT DEVILS_NUMBER
System.out.println("The sum of those two numbers is");
System.out.println(n1 + n2);
}
}
Last but not least, have a look at Java Google Style for tips on how to properly format your code. If you are using an IDE like Eclipse, Intellij or NetBeans it can automatically format the code for you.

Difficulty exiting "user input" method called in main Java

I am trying to bring in some numerical values by way of Scanner(System.in). I am calling a class with my method from main and having a difficult time exiting the method, my questions are looping.
I am sure this is a simple issue but I am having a heck of a time finding a solution.
Here is the method:
public static Object userInput(double nutWidth, double lastFretWidth, double scaleLength, int numFrets) {
boolean dataCheck = true;
try {
while (dataCheck == true) {
System.out.println("What is the width at the nut?");
NutWidth = key.nextDouble();
System.out.println("What is the width at the last fret?");
LastFretWidth = key.nextDouble();
System.out.println("What is the scale length?");
ScaleLength = key.nextDouble();
System.out.println("How many frets will your guitar have?");
NumFrets = key.nextInt();
dataCheck = false;
}
} catch (InputMismatchException e) {
System.out.println("Enter a integer.");
key.nextInt();
}
return userInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
}
Here is my main:
public static void main(String[] args) {
FingerBoard.userInput(0, 0, 0, 0);
FingerBoard.UserData();
}
Any help is greatly appreciated-Mike
You have written an infinite recursion. The line
return userInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
will call the same method again after finishing the previous method. It looks to me like you want to store the values in a data structure and return that, which would require calling a constructor something like this:
return new UserInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
You would have to write the data structure UserInput yourself. If you haven't gotten to writing classes and data structures yet, you probably want your variables to be static fields. If you are doing that, change the return type to be void and remove the return statement entirely.
Additional comments not related to your problem. You don't need the arguments to your method. They are never used. You probably also want to put the try/catch inside of the while loop. That way an invalid input will prompt for new input, rather than setting things to 0.

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

Do While Loop skipping statements

In my do while loop, the body works fine initially, but when it loops, it prints the first two statements like it should but it does not allow me to enter the name instead it goes straight to enter pin and whatever I enter it skips the rest and asks me if I want another transaction.
I have an array object partially filed. The variables in the object are name, pin, account number and balance. When I add a new object and set the balance, the new balance I enter causes the balance for the previous objects to change as well. I think it has something to do with the balance variable being declared as static but I don't make it static, i can the error "Cannot make a static reference to the non-static method withdraw(double) from the type CustomerRecord". (SOLVED) Thank you.
public class BankCustomers
{
public static void main(String[] args)
//------------------------------------------------
//Part4: Find a customer record from anotherArray
//to do transaction(s) and update the record's balance
char repeat; // User control to repeat or quit
Scanner keyboard = new Scanner(System.in); //creating the scanner
String aName;
int aPin;
double aWithdraw;
double aDeposit;
do{
//Read customer information before search
System.out.println();
System.out.println("Lets make a transaction");
System.out.println("Enter customer full name");
aName = keyboard.nextLine( );
System.out.println("Enter Pin");
aPin = keyboard.nextInt();
//Search an Array for equal aName and aPin
for (int i = 0; i < index; i++)
{
CustomerRecord cRecord = anotherArray[i];
if((cRecord.getName().equalsIgnoreCase(aName)) && (cRecord.getPin() ==(aPin)))
{
System.out.println(cRecord);
System.out.println("Enter Withdraw Amount");
aWithdraw = keyboard.nextDouble();
CustomerRecord.withdraw(aWithdraw);
System.out.println("Enter Deposite Amount");
aDeposit = keyboard.nextDouble();
CustomerRecord.deposit(aDeposit);
System.out.println(cRecord);
}
}
System.out.println("\nAnother Transaction? (y for yes)");
repeat = keyboard.next().charAt(0);
}while(repeat == 'y' || repeat == 'Y');
//Print the records on screen
for (int i = 0; i < index; i++)
System.out.print(anotherArray[i]);
}
Remove the static from
private static double balance
and
public static void deposit(double aDeposit)
and
public static void withdraw(double aWithdraw)
you don't want them to be static as you are going to call these methods directly from the objects you created, so they will be specific to each CustomerRecord.
Then in your code, change these lines:
CustomerRecord.deposit(aDeposit);
CustomerRecord.withdraw(aDeposit);
by:
cRecord.deposit(aDeposit);
cRecord.withdraw(aDeposit);
The modifications made now will be applied to each CustomerRecord balance variable and not to a single balance variable (unique for the whole program) as it was the case when it was static.
public class CustomerRecord implements Serializable
{
private String name;
private int pin;
private int account;
private double balance;
}
public void deposit(double aDeposit)
{
balance = balance + aDeposit;
}
public void withdraw(double aWithdraw)
{
if (balance >= aWithdraw) balance = balance - aWithdraw;
else System.out.println("Withdraw cannot be negativeegative");
}
Make balance non-static, as you mentioned. This will fix the bug.
Make the CustomerRecord#deposit() and #withdraw() methods non-static as well. This will fix the compile error caused by #1.
You're correct that the problem is that you made things static. None of balance, deposit, withdraw should be static because all of them are things that apply to a particular customer record rather than to all customer records simultaneously.
The fact that your code doesn't work when you don't make them static is related to the way in which you're calling the withdraw method: CustomerRecord.withdraw(aWithdraw). Can you see what's wrong with that, now that your attention is drawn to it?
In your instance variables for CustomerRecord you have balance declared as a static variable.
This means that anytime you change balance in one instance of the class that it will change in all instances. For example, the deposit and withdraw methods.
I assume you needed to make balance static in order for these two methods to work, but you should just take the static declaration out of all three. Then, you need to change all calls from
CustomerRecord.withdraw();
CustomerRecord.deposit();
to use an instance of a class rather than just the static class. So,
// Whatever values you want here, you seem to have 4 already declared so you can use those
CustomerRecord c = new CustomerRecord("", 0, 0, 0);
c.withdraw();
c.deposit();
Your problem is twofold:
First, balance istatic, which means it is associated with the class, not any of its instances (objects), or in other terms it is shared between all instances of that class.
Second, as you pointed it out, your static method withdraw is accessing balance. The consideration about static applies here just as well -- the method is associated with the class, and cannot access memebers that are non-static.
To solve the second problem, remove static from the withdraw declaration (and remove static from balance as well. Thyis will make your code CustomerRecord.withdraw() not compile, becuase withdraw is now not associated with the class itself, but an instance of it. So you need to use an instance and call withdraw on that
cRecord.withdraw(aWithdraw);
Similarly for deposit

Categories

Resources