java 帮助Java编码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1695006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Help with java coding?
提问by cal
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:
我已经为我的 Java 编程课程设置了一个作业,但我已经到了我真的无法解决下一步的地步。我想知道是否有人可以帮助我使用此代码。任务如下:
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).
- 要求用户输入文件名。
- 从该文件中读取数据,将每个值存储在一个 Array 中。
- 遍历数组并打印出当年的总降雨量。
- 遍历数组并打印出平均每月降雨量。
- 遍历数组并打印出降雨量最少的月份以及降雨量。(打印月份名称将获得额外分数)。
- 遍历数组并打印出降雨量最多的月份以及降雨量。(再次将月份数字转换为字符串将获得额外的分数)。
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
1.80
2.70 etc meaning that the '1' will be January, the '2' will be February etc
2.70 等意味着“1”将是一月,“2”将是二月等
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!
我坚持的部分是计算总降雨量。数据是双精度值,所以我需要计算数据文件中句号后的所有整数。我不知道如何将它放入我的代码中。感谢您提前提供帮助!
回答by MagicAndi
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:
我的 Java 有点生疏,但我会使用:
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.
这是假设文件只包含十二个月的数据,这可能不是一个有效的假设。
回答by hjhill
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.
80.0, 70.0, 75.0 ... 作为几个月的降雨量。
Further, it says you should use "an Array" - I think that means double[], you are using an ArrayList.
此外,它说你应该使用“一个数组”——我认为这意味着double[],你正在使用一个ArrayList.
回答by Martin Dale Lyness
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;
}
}
回答by Carl Smotricz
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.
好的...如果所有数据在小数点后都有 2 位数字,您可以通过执行 Math.round(Math.floor(x)) 将月份提取为整数,其中 x 是您的 1.80 数字。
Then you can subtract the month from your number and multiply by 100 and apply Math.round() again to get at your rainfall.
然后,您可以从您的数字中减去月份并乘以 100,然后再次应用 Math.round() 来计算您的降雨量。
回答by Woot4Moo
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);
}
回答by Harriet
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;
}
}
}

