我一直在尝试弄清楚如何将数组中的一个数字与数组中的另一个数字相加。我将字符串中的数字解析为整数,并按列分隔它们。然后,我将每一列添加到一个数组中。
我想要解决的是如何将一列中的所有数字相加。
这些数字来自一个文本文件。
// numbers.txt:
Bob, 100, 98, 95
Alex, 85, 90, 92
我已经使用了bufferedReader并解析了从字符串到整数的数字。
挑战是按列添加数字。
例如,如果每个数组中有3个数字,我只想将每个数组中的第一个数字相加。
Q1是100,98,95 Q2是85,90,92
加起来只有100 + 85。
下面是我到目前为止掌握的代码。任何关于如何继续的帮助都将是非常棒的!耽误您时间,实在对不起。
int Q1 = Integer.parseInt(columns[1]);
int Q2 = Integer.parseInt(columns[2]);
ArrayList<Integer> Q1list = new ArrayList<>();
Q1list.add(Q1);
Q1list.add(Q2);
double total = 0.0;
for (int i = 0; i < Q1list.size(); i++) {
total += Q1list.get(i);
}
System.out.println(total);
发布于 2015-11-18 20:02:53
通常,当你想要将数组中的数字相加成一个和时,你想迭代该数组中的所有索引。从你写的循环中,我看不到所有的数字都会以任何方式进入数组。请修改for循环的使用方法!
这里有一个很好的解释,希望能对Java: Array with loop有所帮助
发布于 2015-11-18 20:24:59
我认为你应该至少有两个列数组。
之后,不要忘记你的索引(在你的循环中)
推荐的代码:
公共静态空main(String[]参数){
int [] q1 = { 100 , 98 , 95 };
int [] q2 = { 85 , 90 , 92 };
List<Integer> sumList = new ArrayList<>();
// First solution (what you ask)
sumList.add( q1[0] + q2[0] );
System.out.println("Add Q1[0] + Q2[0]: " + sumList.get(0));
// Second solution (add all)
for( int i = 0 ; i < q1.length ; i++)
{
sumList.add(q1[i] + q2[i]);
}
// Check your result
for( int i : sumList )
System.out.println("Result: " + i);
}
结果显示:
// First solution (what you ask)
Add Q1[0] + Q2[0]: 185
// Second solution (add all)
Result: 185
Result: 185
Result: 188
Result: 187
我找到了你想要的:
// Scanner
StringTokenizer i1 = new StringTokenizer(" [100,98,95]", "[,]");
StringTokenizer i2 = new StringTokenizer(" [85,90,92]", "[,]");
List<Integer> q1List = new ArrayList<>();
List<Integer> q2List = new ArrayList<>();
while( i1.hasMoreTokens() ){
try {
Integer intRes = Integer.parseInt(i1.nextToken());
System.out.println("Test1: " + intRes);
q1List.add(intRes);
}
catch( NumberFormatException e) {}
}
while( i2.hasMoreTokens() ){
try {
Integer intRes = Integer.parseInt(i2.nextToken());
System.out.println("Test2: " + intRes);
q2List.add(intRes);
}
catch( NumberFormatException e) {}
}
// Second solution (add all)
for( int i = 0 ; i < q1List.size() ; i++)
{
sumList.add(q1List.get(i) + q2List.get(i));
}
// Check your result
for( int i : sumList )
System.out.println("Result 2 : " + i);
很抱歉很久了,但我必须在网上找到答案。
Simples逐行读取文件,并为每个新行设置新的字符串...之后,对于每个字符串,您可以使用Strink标记器,在本例中使用分隔符:",“。注意你的第一个参数应该是: null (代码) name (捕获这个字符串)其他(可能是try catch)
我在堆栈上找到了这个链接:
Using Java 8, what is the most preferred and concise way of printing all the lines in a file?
祝好运
https://stackoverflow.com/questions/33789172
复制