How to store a double in an array incrementally - java

this is my first post and I hope someone can help. I have been struggling for ages to understand the problem I have and it looks as though I have done everything right yet problem persists. I have written a simple account program and would like to store the new balance after each transaction into an array index. From printing out balance I can see that it is adding and subtracting properly, however it is updating every single array index with the new balance rather than each incremental index. Can anyone spot my mistake. Thank you for any help with this.
Richard
public class TestAppAccount {
public static void main(String args[]) {
int count = 0;
do {
AppAccount.transaction();
AppAccount.storeBalance();
AppAccount.printBalance();
count++;
//Account1.printBalance2();
} while (count <= 100);
}
public class AppAccount {
public static double[] currentBalance = new double[100];
static Scanner keyboard = new Scanner(System.in);
static double balance;
static int transaction;
public static void transaction() {
System.out.println(" Press 1 to add funds, 2 to withdraw ");
transaction = keyboard.nextInt();
if (transaction == 1) {
System.out.println("Enter an amount to add ");
double amount = keyboard.nextInt();
double newBalance = balance + amount;
balance = newBalance;
} else
{
System.out.println("Enter an amount to withdraw");
double amount = keyboard.nextInt();
double newBalance = balance - amount;
balance = newBalance;
}
}
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
public static void printBalance() {
System.out.println("Balance: " + balance);
System.out.println("Balance: " + currentBalance[3]);//testing by printing 3rd index
}
}

Your storeBalance() method is iterating through the entire array and updating the values. If you want to only update one value, you'll need to keep track of where you've written up to and only write to the location one after that.
e.g.
Instead of
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
try this:
static int lastStored = 0;
public static void storeBalance() {
currentBalance[lastStored++] = balance;
}

for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
That for loop is setting every value in the array to the value of balance. If each index is supposed to be a different account I would suggest passing an index to each function.

The problem is here:
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
That for-loop will step through every element in the array, one by one, and will overwrite each value with whatever the current balance is.
There are a couple of ways you could fix this. My first reaction would be to create a variable that tells you the next index to write to:
static int nextIndex = 0;
and then storeBalance() would look like this:
public static void storeBalance() {
currentBalance[nextIndex] = balance;
nextIndex++;
}

You issue is you do a for loop and update every single value. You just want to update once when storeBalance() is called. Keep track of i as a static variable:
static int i = 0;
Then do this:
public static void storeBalance() {
if(i >= currentbalance.length)
i = 0;//restart value so it doesnt do array out of bounds
currentbalance[i] = balance;//update a single value
i++;//increment for next call
}
Make sure you do the out of bounds check. That's what the other answers are forgetting to check. Of course this will over write old values, so you can choose to do something else (what ever seems fitting for your requirements).

Stop pretending that java is c.
Java is not c.
Java likes objects.
Use objects.
Avoid arrays.
Here is some code:
// start Main.java file
public class Main
{
public static void main(String args[])
{
int count = 0;
do
{
AppAccount.transaction();
AppAccount.storeBalance();
AppAccount.printBalance();
count += 1;
}
while (count <= 4);
}
}
// start AppAccount.java file
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AppAccount
{
private static List<Double> currentBalanceList = new ArrayList<Double>();
private static Scanner keyboard = new Scanner(System.in);
private static double runningBalance;
private static int transaction;
public static void printBalance()
{
System.out.println("Running Balance: " + runningBalance);
}
public static void storeBalance()
{
currentBalanceList.add(runningBalance);
}
public static void transaction()
{
double amount;
System.out.println(" Press 1 to add funds, 2 to withdraw ");
transaction = keyboard.nextInt();
if (transaction == 1)
{
System.out.println("Enter an amount to add ");
amount = keyboard.nextDouble();
runningBalance = runningBalance + amount;
}
else
{
System.out.println("Enter an amount to withdraw");
amount = keyboard.nextDouble();
runningBalance = runningBalance - amount;
}
}
}

Related

Vector in java always overwriting everything with the last value

I'm a beginner in java and I have the following exercise to solve:
Read a set of sports lottery bets to an unspecified number of players. After that, read the template, compare the result and display a message.
Bet Class: must contain the player's name and an integer vector with thirteen positions to store the bet: 1 – winner of team A, 2 – winner of team B, and 0 for draw. Create the necessary constructor methods and the toString method.
ReadBets Class: This class must have an attribute that is a vector of objects of the Bet class. In addition, this class must have a method to read the person's name and their sports lottery game. Create the necessary constructor methods and the toString method.
ReadTemplate Class: This class should read the correct answers from the sports lottery game and store the result in an integer vector. Create the necessary constructor methods and the toString method.
GenerateResult Class: this class must compare the players' bets with the result of the template and, if you have 6 correct answers, show the winner's name, his game and the message: “WINNER, CONGRATULATIONS”. Otherwise, show the player name and the message “Try again, this time you didn't win”.
Main Class: implement in this class the control and execution flow for this problem creating the necessary objects to solve this class.
There is a complicating factor for me which is that each object bet is composed of a string name with a vector with the bets.
I made a solution to the problem that already reads validating only the allowed values (0,1,2), reads the template and compares.
However, I noticed that the last name typed and the last bets are always being recorded in the vector. In all positions.
I'm hours assembling and disassembling the code and I can't find a way to solve it.
I read that it may have to do with the new but I didn't understand how to solve it because at each position of the vector of objects I need to give a new to create the object with the internal vector that will store that player's bets.
Below are my classes:
MAIN:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public void execute(){}
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
//ReadBet a = new ReadBet();
V_Bets a = new V_Bets();
System.out.println("Enter the total bets that will be placed");
a.totalBets(input.nextInt());
a.Data entry();
a.Data output();
ReadTemplate g = new ReadTemplate();
g.getTemplate();
GenerateResult gr = new GenerateResult();
gr.generateResult();
}
}
BETS:
import java.util.Arrays;
public class Bet {
private static String name;
public static int[] Bet vector =new int [6];
/*public String getName(){
return this.name;
}*/
public static String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
#Override
public String toString() {
return "Bet [name=" + name + ",Betvector=" + Arrays.toString(Betvector) + "]";
}
public int getBet(int i) {
return this.vector Bets[i];
}
public void setBets(int[] bets) {
this.vector Bets = bets;
}
public int[] getCloneArray() {
returnVectorBets.clone();
}
}
V_BETS
import java.util.Scanner;
public class V_Bets {
Input Scanner = new Scanner (System.in);
private int size;
public static Total BetBets[] = new Bet[100];
//total Bets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
private Bet bets = new Bet();
int i=0;
int j=0;
public void dataentry() {
for(j=0;j<size;j++) { //for external - from J that controls the total bets that will be registered
totalBets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
System.out.println("Enter the name of the Player:");
totalStakes[j].setName(input.next()); //setting the player's name
// loop to set the guesses
System.out.println("Please enter guesses for each Sports Lottery game");
System.out.println("1 - Winner Team A, 2 - Winner Team B and 0 - Tie");
for ( i=0;i<bets.vetorApostas.length;i++) // receive the bet until it reaches 6
{
System.out.println("Game "+i +":");
totalStakes[j].vectorStakes[i] = input.nextInt(); // receive the user's bets
while (totalApostas[j].vectorApostas[i] < 0 ) // if the user enters a negative number it says to try again
{
System.err.println("Negative Number, try again:");
totalBets[j].vectorBets[i]= entry.nextInt();
}
if (totalApostas[j].vetorApostas[i] > 2) // if the number is greater than 2 it says to try again
{
while (totalBets[j].vectorBets[i] > 2 ) {
System.err.println("Please enter numbers between 0 and 2");
totalBets[j].vectorBets[i]= entry.nextInt();
}
}
}
}
}
/*public void dataoutput() {
//System.out.println("The player's name is:"+total Bets[i].getName());
System.out.println("Your Bet:");
for ( i=0;i < Bet.vectorBeats.length; i++){
System.out.print(+TotalStakes[i].vectorStakes[i].getStakes(i)+ " ");
}
}
public void dataoutput() {
System.out.println("Your Bet::");
for (j=0; j<totalBets[i].vectorBets.length; j++) {
System.err.print("Player "+Total Bets[j].getName()+" ");
for (i = 0; i < totalBets[i].vectorBets.length; i++) {
System.err.print(total Bets[j].vector Bets[i] + " ");
}
}
}*/
public void totalOfBets(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
TEMPLATE:
public class Template {
//private String name;
public static int[]vectorTemplate =new int [6];
public int getBet(int i) {
return this.vectorTemplate[i];
}
public void setBets(int[] bets) {
this.vectorTemplate = bets;
}
public int getTemplate(int i) {
return this.vectorTemplate[i];
}
public void setTemplate(int[] bets) {
this.vectorTemplate = bets;
}
}
READ TEMPLATE:
import java.util.Arrays;
import java.util.Scanner;
public class ReadTemplate {
private Template template = new Template();
Input Scanner = new Scanner (System.in);
int guesses;
int counter=0;
int j;
int x;
int i;
public void getTemplate() {
System.out.println(" ");
for ( j=0;j<6;j++) // Receive numbers until it reaches 6
{
System.out.println("Now Enter Game Template: "+j);
template.vectorTemplate[j]= entry.nextInt(); // Receive user numbers
while (template.vetorTemplate[j] < 0 ) // If you enter a negative number, ask the user to type again
{
System.err.println("Negative Number, try again:");
template.vectorTemplate[j]=input.nextInt();
}
if (template.vectorTemplate[j] > 2) // if the number is greater than 2 ask again
{
while (template.vectorTemplate[j] > 2 )
{
System.err.println("Please enter numbers between 0 and 2");
template.vectorTemplate[j]=input.nextInt();
}
}
}
//printing the template
System.out.println("Template:");
for (i = 0; i < template.vectorTemplate.length; i++) {
System.out.print(template.vectorTemplate[i] + " ");
}
}
}
GENERATE RESULTS:
public class GenerateResult extends ReadTemplate {
private Bet bets = new Bet();
private Template template = new Template();
//private v_bets v_bets = new v_bets();
private int size;
public void generateResult() {
//Checking if it's right
int x;
V_Bets a = new V_Bets();
for(j=0;j<2;j++) {
int i=0;
int counter=0;
for (x = 0; x < template.vectorTemplate.length; x++) {
if (a.totalStakes[j].vectorStakes[i] == template.vectorTemplate[x]) {
counter++;
}
i++;
}
System.out.println(" ");
System.out.println("Counter of Equals! "+counter);
if (counter <= 5){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("Try again, this time you won");
}
else if (counter == 6){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("WINNER,CONGRATULATIONS!");
}
}
}
public void totalOfBets(int size) {
this.size = size;
}
}
I am immensely grateful to anyone who can help understand where I went wrong and how to evolve.

How do I override an abstract method in java?

The purpose of this code is to find the amount of items one wishes to buy, the price of those items, and what the sale currently is. For a buy three get one free sale, it would look something like
1 items at 5.0; discount is 0
2 items at 5.0; discount is 0
3 items at 5.0; discount is 5.0
4 items at 5.0; discount is 5.0
The class extends an abstract class whose abstract method is computeDiscount()
However, I have no idea how to make this method function, because it won't except it as static, but if the method isn't static then I can't use it in my code!
I have no idea what to do, and I desperately need help
package homeFolder;
import java.util.Scanner;
public class BuyNItemsGetOneFree extends DiscountPolicy{
static Scanner input = new Scanner(System.in);
static double itemCost;
static int count = count();
static int n = getN();
static double discount = 0;
public static void main(String[] args) {
itemCost = itemCost();
for(int i = 1; i <= count; i ++) {
discount = computeDiscount(i, itemCost);
System.out.println(i + " items at " + itemCost +
"; discount is " + discount);
}
}
public static double itemCost() {
System.out.print("Enter the cost of the item: ");
itemCost = input.nextDouble();
return itemCost;
}
public static int count() {
System.out.print("How many items are you going to buy: ");
count = input.nextInt();
return count;
}
public static int getN() {
System.out.print("How many items must you buy till you got one free? ");
n = input.nextInt();
return n;
}
public double computeDiscount(int count, double itemCost) {
double discount = 0;
if((count % n) == 0)
discount += itemCost;
return discount;
}
}
If you want to do anything with abstraction, you can't be using static methods. Here, it's best to use instance variables combined with a factory method to do all the initilization action.
package homeFolder;
import java.util.Scanner;
public class BuyNItemsGetOneFree extends DiscountPolicy {
// Below are your fields, or instance variables. Notice the lack of static.
final double itemCost;
final int count;
final int n;
public static void main(String[] args) {
// Now you have an instance to work with.
BuyNItemsGetOneFree sale = newInstance();
for(int i = 1; i <= sale.count; i ++) {
double discount = sale.computeDiscount(i, itemCost);
System.out.println(i + " items at " + sale.itemCost +
"; discount is " + discount);
}
}
// Only the factory method can access this.
private BuyNItemsGetOneFree (double itemCost, int count, int n) {
this.itemCost = itemCost;
this.count = count;
this.n = n;
}
public static BuyNItemsGetOneFree newInstance() {
// The scanner really only needs to be used here.
Scanner input = new Scanner(System.in);
// Initilizes itemCost
System.out.print("Enter the cost of the item: ");
double itemCost = input.nextDouble();
// Initilizes count
System.out.print("How many items are you going to buy: ");
int count = input.nextInt();
// Initilizes n
System.out.print("How many items must you buy till you got one free? ");
int n = input.nextInt();
// Constructs and returns
return new BuyNItemsGetOneFree(itemCost, count, n);
}
#Override // Always add this when overriding a method.
public double computeDiscount(int count, double itemCost) {
double discount = 0;
if((count % n) == 0)
discount += itemCost;
return discount;
}
}
If you want to go a step further, there is no need for the parameters in computeDiscount as they are (from what I see) just going to reference fields already able to be used.
Spencer make all your methods static and also your main method is missing static.
it should be something like this public static void main(String [] args)

Meaning and how to get and work with a return value from a user input in a method in java

I am trying to write a java program which have two classes. The second class will have the main method and for checking the balance of the account and. The first class will have three methods one for opening an bank account, one for deposit and one for withdrawal. All input needs to be given by user. I am new to java and stuck after at one point any help would be appreciated.
import java.util.Scanner;
class Balance {
static int account()
{ Scanner minimumAmount = new Scanner(System.in);
int openingAmount = minimumAmount.nextInt();
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account:" + openingAmount);
if (openingAmount > 1000)
{
System.out.println("Your Bank account has opened successfully");
int ac = minimumAmount.nextInt();
System.out.println("Enter your account number" + ac);
}
}
static int withdrawal() {
Scanner withdrawalAmount = new Scanner(System.in);
int w = withdrawalAmount.nextInt();
System.out.println("Withdrawal Amount is :" + w);
int b = openingAmount - w;
if (b < 100) {
System.out.println("Unable to process your request");
}
}
void deposit() {
Scanner depositAmount = new Scanner(System.in);
int d = depositAmount.nextInt();
System.out.println("Deposited amount is :" + d);
int b = openingAmount + d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
}
}
i) Is there a way where an user input variable declared under one method can be used in another method to declare another variable?
ii) ow to return a value from a method so that the value received works in different method while declaring a variable?
Is there a way where an user input variable declared under one method
can be used in another method to declare another variable?
You can declare your attribute in your class and use constructor to initialize it for example :
class A{
private String name;
public A(String name){
this.name = name
}
public int account(){
//can use and change the name
}
public int withdrawal(){
//can use and change the name
}
public int deposit(){
//can use and change the name
}
}
Main class
public class B{
public static void main(String[] args) {
A s = new A("Hello");
//------------^^---pass your attribute in the constructor
s.account();
s.withdrawal();
s.deposit();
}
}
How to return a value from a method so that the value received works
in different method while declaring a variable?
You can use the result of each method in another method for example :
s.withdrawal(s.account());
//--------------^^-------account return a result that can be used by withdrawal
I don't know what you really want to do, but I can explain some things.
Methods account() & withdrawal() don't have to be static.
You can use instance attribute like I do to store values.
Balance & AccountBalance should be in different files.
Take a look about private & public on attribut & methods (& getter/setter)
Scanner is a little bit tricky so you should declare it once, and reuse it.
If you want to use returned value from function, change void by int (in this case) and use "return var" (var is what you want to return). So when you can call the function like this -> int value = s.account();
Try this code, it works.
Cheers !
import java.util.Scanner;
class Balance {
private Scanner scanner;
public int userAccount;
public int userAccountNumber;
public Balance() {
scanner = new Scanner(System.in);
}
public void account() {
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account : ");
int openingAmount = scanner.nextInt();
if (openingAmount > 1000) {
System.out.println("Your Bank account has opened successfully");
userAccount = openingAmount;
System.out.println("Enter your account number : ");
userAccountNumber = scanner.nextInt();
} else {
System.out.println("Not enought money");
this.account(); //Ask again for opening an account
}
}
public void withdrawal() {
System.out.println("Withdrawal Amount is : ");
int w = scanner.nextInt();
int b = userAccount - w;
if (b < 100) {
System.out.println("Unable to process your request");
} else {
userAccount = b;
}
}
public void deposit() {
System.out.println("Deposited amount is : ");
int d = scanner.nextInt();
userAccount += d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
System.out.println("Final amount is : "+s.userAccount);
}
}

Use Variable Which is in main method in Another Method

I'm trying to create a simple program to output the number of stars entered by user. I'm trying to learn how to use more than one method to do this
Here's my code
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
}
public static void Loop ()
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
The problem I'm facing is that in the Loop method, I am unable to use the variable n
Is there a way to use a variable which is in the main method, in another one?
Ty
-Pingu
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
Loop(n); //calls Loop function and passes parameter n
}
public static void Loop(int n) //this function now expects a number n
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
simply pass it as parameter:
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
Loop(n);
}
public static void Loop (int count)
{
for (int counter = 1; counter <= count; counter++)
{
System.out.println("*");
}
}
Pass it as a paramteer
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
loop(n); // added this
}
public static void loop (int n) // changed here
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
I think you should use it as a instance variable and for better understanding name your class like StarClass it can provide better understanding. Good programming practice.
But you should avoid unneccesserily making instance variable without any logic behind it.
I also think you could declare n as a public variable.
That should make it accessible throughout the code.
public int n;
But I guess that passing it as parameter is a better practice, since you don't create a deppendance inside your code. What I mean is, if something changes with the variable you break the function. It's good practice to always keep things "modular" in your code, so it makes it more resilient to changes and debugging.
It's better if you get used to it from the beggining =)
Two ways.. one has been posted already as answer and the other one would be using the variable as a field. This way you can access (and modify) it in every method without having to pass it on.
public class Alpha
{
static int n;
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter no. of stars");
n = input.nextInt();
loop();
}
public static void loop ()
{
for (int counter = 0; counter < n; counter++)
{
System.out.println("*");
}
}
}
And please start method names with lowercase and counting with 0. It's common practise and it helps a lot to use the standards right from the beginning.
Like this you can use variable from different methods in different methods
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum=0;
int a=Sum(sum);
System.out.println("The Average of the numbers is: "+a);
}
public static int Sum(int sum) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the total count of number for Average: ");
int a=sc.nextInt();
for(int i=1;i<=a;i++) {
System.out.println("Enter the"+i+"Number: ");
int b=sc.nextInt();
sum+=b;
}
int avg=sum/a;
return avg;
}

My Java Method for get total is not working in my main method

Version 2 of my monthly rainfall program, with edits and suggestions applied. Thanks so much for your help it really made me think. Wonderful thing about programming is how complete strangers can come together to solve problems.
// Rainfall Class Start
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
import java.util.Arrays;
/**
*
* #author Adrian
*/
public class Rainfall{
DecimalFormat twoDecimals = new DecimalFormat("##0.00");
private final String[] Months={"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"};;
private final double[] Rainfall;
public Rainfall() throws IOException
{
Rainfall = new double[12];
}
public double getAverageRainFall()
{
return getTotalRainFall() / 12 ;
}
public void outputToFile()throws IOException
{
try (PrintWriter outputFile = new PrintWriter("Months.txt")) {
Scanner kb=new Scanner(System.in);
System.out.println("For each month enter a rainfall amount");
for (int i=0;i<12;i++)
{
System.out.println(Months[i]+"?");
Rainfall[i]=kb.nextDouble();
outputFile.println(Months[i]+" "+Rainfall[i]);
System.out.println(Months[i]+" "+Rainfall[i]);
}
}
}
/**
*
* #return
*/
public double getTotalRainFall()
{
double total = 0.0; // Accumulator initialized to 0
// Accumulate the sum of the rain array elements.
for (int i = 0; i < Rainfall.length; i++)
total += Rainfall[i];
// Return the sum.
return total;
}
public double getLowestMonth()
{
int lowest = 0;
// Find the element with the lowest value.
for (int i = 1; i < Rainfall.length; i++)
{
if (Rainfall[i] < Rainfall[lowest])
lowest = i;
}
// Return the element number.
return lowest+1;
}
public int getHighestMonth()
{
int highest = 0;
// Find the element with the highest value.
for (int i = 1; i < Rainfall.length; i++)
{
if (Rainfall[i] > Rainfall[highest])
highest = i;
}
// Return the element number.
return highest;
}
public void displayMessage(){
System.out.println("----------------------");
System.out.println("Monthly Rainfall Totals For 2014");
System.out.println(Arrays.toString(Months));
System.out.println(Arrays.toString(Rainfall));
System.out.println("Average Rainfall = " +getAverageRainFall());
System.out.println("Total Rainfall = " +getTotalRainFall());
System.out.println("Highest Month = " +getHighestMonth());
System.out.println("Lowest Month = " +getLowestMonth());
System.out.println("----------------------");
}
public double getRainAt(int e)
{
return Rainfall[e];
}
}
/*public void inputFromFile() throws IOException
{
File myFile=new File ("Months.txt");
Scanner inputFile=new Scanner(myFile);
//loop through the file
for(int i=0;i<12;i++){
Months[12] = inputFile.nextLine();
inputFile.close();
}
}*/
// End Class
// Start of Main Method
import java.io.*;
import java.text.DecimalFormat;
public class Rainfall2{
public static void main(String[] args) throws IOException
{
// The low month
DecimalFormat twoDecimals = new DecimalFormat("##0.00");
Rainfall myData=new Rainfall();
myData.outputToFile();
myData.displayMessage();
}
}
Version 2 of my monthly rainfall program, with edits and suggestions applied. Thanks so much for your help it really made me think. Wonderful thing about programming is how complete strangers can come together to solve problems.
The compiler is actually right, You can't call a non stati method from your static main :) , call that getTotalRainFall(); on a instance of Rainfall.
Edit1: Thanks puj, fixed the error.
Edit2: Actually, your code looks a bit messed up, what is that Prices class? Should you have Rainfall there? End end up with something like:
RainFall rf=new RainFall();
rf.inputFromFile();
rf.getTotalRainFall();
rf.outputToFile();
Crystal, can i recommend you to rewrite it from scratch with the suggestions you got from these answers?
Also, you will probably want to change
for(int i=0;i<12;i++)
Months[i]=inputFile.nextLine();
inputFile.close();
to
for(int i=0;i<12;i++)
Rainfall[i]=inputFile.nextLine();
inputFile.close();
to get the correct data.
The method is part of the object, that why you need instance of the object to call his method, you can do something like this in your main:
Rainfall r = new Rainfall();
r.getTotalRainFall();
Make public double getTotalRainfall() static,
public static double getTotalRainfall(){}
so you can call it from main with double totalRain = Rainfall.getTotalRainfall();
You would have to make private double[] rainFall; also static, private static double[] rainFall;
And you should concider using another name for the array Rainfall and Months according to standard naming in Java, you should use a lower case verb to declare fields. Else it might cause problems.

Categories