3
100 8
15 245
1945 54
上面的数字,首先是对的数量,然后我想逐行添加,并且已经卡住了几个小时。有人可以帮助我吗?
import java.util.Scanner;
import java.util.ArrayList;
public class sumInLoops2 {
public static void main(String[] args)
{
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Enter your variables: ");
int cases = in.nextInt();
int sum = 0;
for(int i = 0; i < cases; i++) {
list1.add(in.nextInt());
list2.add(in.nextInt());
System.out.println(list1);
System.out.println(list2);
}
答案 0 :(得分:0)
你太复杂了。如果您不需要存储读取值,只输出总和,那么您就不需要所有列表。
import java.util.Scanner;
public class sumInLoops2 {
public static void main(String[] args)
{
// ArrayList<Integer> list1 = new ArrayList<Integer>();
// ArrayList<Integer> list2 = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Enter your variables: ");
int cases = in.nextInt();
for(int i = 0; i < cases; i++) {
int val1 = in.nextInt();
int val2 = in.nextInt();
int sum = val1 + val2;
System.out.println(val1 + " + " + val2 + " = " + sum );
}
}
}
如果您需要存储结果,请创建一个包含属性LineSum
,val1
,val2
的帮助对象(例如sum
),并将其放在一个输出列表中。
答案 1 :(得分:0)
正如@thst所说,如果不需要存储用户输入的数据,不要过于复杂,只需输出你需要的结果。但是,如果您打算学习如何在这些单独的列表中输出匹配的数字对。
每当您想要访问List中的项目时,您都可以使用list get()方法返回该索引处的项目。因此,在您的情况下打印出添加在一起的匹配对。
for (int i = 0; i < cases; i++)
{
int num1 = list1.get(i);
int num2 = list2.get(i);
int sum = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + sum);
}
答案 2 :(得分:0)
使用
Java8
的快速示例(最佳方式,尝试一下):
import java.util.Arrays;
import java.util.Scanner;
public class Java8Way {
public static void main(String[] args) {
//Create a Scanner Object
Scanner in = new Scanner(System.in);
System.out.println("Enter your variables(separated by a space): ");
//what the following is doing
//Arrays.asList(in.nextLine().split(" ")->Splits the line that user gave to individual strings
//makes a list from them using method asList(..); from
//Arrays Class
//mapToInt(Integer::valueOf)-> makes a stream an map each string to and integer
//sum()->a special kind of reduce function which sums all the Integer elements
System.out.println("Your sum is...:"+Arrays.asList(in.nextLine().split(" ")).stream()
.mapToInt(Integer::valueOf)
.sum());
}
}