开发者

Help with java coding?

ive been set an assignment for my java programming course and ive reached a point where i really cant work out the next step. Im wondering if anyone can help me with this code please. The assignment is as follows:

A file exists which contains the total rainfall for each month in a year, one double value on each line. Write a program which:

  • Asks the user to type in the name of the file.
  • Reads the data from that file storing each value in an Array.
  • Iterates through the Array and prints out the total rainfall for the year.
  • Iterates through the Array and prints out the average monthly rainfall.
  • Iterates through the Array and prints out the month with the minimum rainfall and how much that was. (Printing the name of the month will earn extra marks).
  • Iterates through the Array and prints out the month with the most rainfall and how much that was. (Again converting the month number to a String will earn extra marks).

So far i have done the first two steps and i almost have the code for the third step.

The data file im using looks something like this:

  1.80

  2.70

  3.75

  4.40

  5.20

  6.15

  7.30

  8.45

  9.60

  10.90

  11.85

  12.100

What i have done here is written:

1.80

2.70 etc meaning that the '1' will be January, the '2' will be February etc

So the number after the full stop is the rainfall. So i need to calculate the total of all the numbers on the right hand side of each full stop.

Then my code so far is this:

import java.util.*;
import java.io.*;

class Assignment5{
public static void main(String[] args)throws Exception{
  String data;

  ArrayList<Double>开发者_如何转开发 store = new ArrayList<Double>();
  Scanner scanner = new Scanner(System.in);

  System.out.println(" "); 
  System.out.println("Please enter the name of a file with .txt at the end.");
  System.out.println(" ");
  data = scanner.nextLine();

  File inputFile = new File(data);
  Scanner reader = new Scanner(inputFile); 

  while(reader.hasNext()){
    store.add(reader.nextDouble());
  }

  calculateSum(store);
  store.clear();

}

private static void calculateSum(ArrayList<Double> ArrayList){
  double sum = 0;
  double avg = 0;
  double total = 0;
  double totalrainfall = 0;

  Iterator<Double> iterator = ArrayList.iterator();

  while(iterator.hasNext()){
    sum += iterator.next(); 
  }

  total = ArrayList.size();
  avg = (sum / total);

  System.out.println(" ");
  System.out.println("The total rainfall is " + totalrainfall);

}   

The part im stuck on is calculating the total rainfall. The data is a double value so i need to calculate all the integers after the full stop in the data file. I cant work out how to put this into my code. Thanks for helping in advance!


Since it's an assignment, allow me some thoughts about your interpretation of it (if your tutors are as strict as mine were, every change will result in subtracted marks):

The format of your text file doesn't (in my opinion) match the textual description, I'd interpret it as description of

80.0
70.0
75.0
// ...

with 80.0, 70.0, 75.0 ... as the rainfall for the months.

Further, it says you should use "an Array" - I think that means double[], you are using an ArrayList.


I would be tempted to read each line of the file as string, split it on the '.' character, and parse the resultant substrings as integers to get the month number and the rainfall for that month.

My Java is a bit rusty, but I would use:

import java.util.;
import java.io.;

class Assignment5
{ 

    public static void main(String[] args) throws Exception 
    { 
        String data;
        int[] store = new int[12]; 
        Scanner scanner = new Scanner(System.in);

        System.out.println(" "); 
        System.out.println("Please enter the name of a file with .txt at the end."); 
        System.out.println(" "); 
        data = scanner.nextLine();

        File inputFile = new File(data); 
        Scanner reader = new Scanner(inputFile);

        while(reader.hasNext())
        { 
            String currentLine =  scanner.nextLine();
            String[] currentMonthDetails = currentLine.split(".");
            int currentMonth = Integer.parseInt(currentMonthDetails[0]);
            int currentRainfall =  Integer.parseInt(currentMonthDetails[1]);
            store[currentMonth] = currentRainfall;
        }

        calculateSum(store); 
        store = null;
    }

    private static void calculateSum(int[] aRainfallData)
    {
        int avgRainfall = 0; 
        int numberOfMonths = 0; 
        int totalRainfall = 0;

        numberOfMonths = aRainfallData.length;

        for (int index=0; index < numberOfMonths ; index++)
        {
            totalRainfall += aRainfallData[index];
        } 

        avgRainfall = (totalRainfall / numberOfMonths );

        System.out.println(" "); 
        System.out.println("The total rainfall is " + totalRainfall );
    }
}

This is assuming that the file only contains data for twelve months, which may not be a valid assumption.


Every other element in your array list is a rainfall for a month, so use a boolean to toggle true false to sum up all of these values.

double sum = 0;
boolean toggle = false;
for(Object d: arrayList) {
  [...]
  if(toggle) {
    sum += (Double)d;
    toggle = !toggle;
  }
}


It's a bit nasty that your data is in that format. Scanner is nice and easy to work with but it's hard to get your numbers back out of double format.

OK... if all data has 2 digits after the decimal, you can pull out the month as an integer by doing Math.round(Math.floor(x)), where x is your 1.80 number.

Then you can subtract the month from your number and multiply by 100 and apply Math.round() again to get at your rainfall.


I suggest the following:

//Don't use * imports it is bad practice
import java.util.*;
import java.io.*;

class Assignment5{
public static void main(String[] args)throws Exception{
  String data;

  ArrayList<Double> store = new ArrayList<Double>();
  Scanner scanner = new Scanner(System.in);

  System.out.println(" "); 
  //Files can end in things other than .txt, so if you make it say that you need
  // to do validation that data.endsWith(".txt") == true
  System.out.println("Please enter the name of a file with .txt at the end.");
  System.out.println(" ");
  //Do you use data anywhere else?  Or is this just an arbitrary string holder
  data = scanner.nextLine();

  File inputFile = new File(data);
  Scanner reader = new Scanner(inputFile); 

  while(reader.hasNext()){
    store.add(reader.nextDouble());
  }

  calculateSum(store);
  store.clear();

}

//Call it arrayList or something that isn't ArrayList I'm stunned that compiles.
private static void calculateSum(ArrayList<Double> ArrayList){
  //if you are declaring it a double sum = 0.0 <--- don't be lazy
  double sum = 0;
  double avg = 0;
  double total = 0;
  //Camel case me: totalRainfall or totalRainFall
  double totalrainfall = 0;

  //Are you still on java 1.4?  If not use a foreach loop, while less efficient at higher
  // data sets it will not be noticeable with the smaller data set
  Iterator<Double> iterator = ArrayList.iterator();

  while(iterator.hasNext()){
    sum += iterator.next(); 
  }

  total = ArrayList.size();
  //Need to do a conditional check so you dont divide by 0
  avg = (sum / total);

  System.out.println(" ");
  System.out.println("The total rainfall is " + totalrainfall);

}


package multiples;
import java.util.Scanner;
public class MulTiples{ 
   public static void main(String []args) 
   {
      int i =0;
      while(i<100)
      {
         if ( i%3==0)
         {
             System.out.println("hutt");             
         }
         if (i%7==0)         
         {
             System.out.println("hike");    
         }
         System.out.println(i);
         i = i+1;
      }
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜