创建并填充两组double值,其中元素的数量和元素本身由用户指定。 迭代集合并比较值。
就本实验而言,我们会说顺序对确定这些集合是否相同很重要。
如果数组的长度和值都相同,则print set one和set two相等。否则,打印设置1和设置2不相等。这是我的代码,但是当我运行它时,我收到了这条消息:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at SetComparison.main(SetComparison.java:23)
我是编码的新手,有谁能告诉我这似乎是什么问题?
import java.util.*;
import java.lang.*;
import java.io.*;
public class SetComparison
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String[] allNums = str.split("\\s+");
int array1Length = Integer.valueOf(allNums[0]);
int array2Length = Integer.valueOf(allNums[array1Length + 1]);
double array1[] = new double[array1Length];
double array2[] = new double[array2Length];
for (int i = 0; i < array1Length; i++) {
array1[i] = Double.valueOf(allNums[i + 1]);
}
for (int i = 0; i < array2Length; i++) {
array2[i] = Double.valueOf(allNums[array1Length + i + 2]);
}
if (Arrays.equals(array1, array2)) {
System.out.println("set one and set two are equal");
} else {
System.out.println("set one and set two are not equal");
}
}
}
答案 0 :(得分:1)
使用扫描仪,您需要检查下一行是否有hasNextLine()
所以循环变为
while(scnr.hasNextLine()){
str=scnr.nextLine();
//...
}
它在EOF上返回null的读者
在这段代码中,这取决于输入是否格式正确答案 1 :(得分:0)
你正在调用nextLine(),并且当没有行时它会抛出异常。
答案 2 :(得分:0)
尝试以下修改后的代码:
package com.test;
import java.util.Arrays;
import java.util.Scanner;
public class SetComparison {
public static void main(String[] args) throws java.lang.Exception {
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String[] allNums = str.split("\\s+");
int array1Length = Integer.valueOf(allNums[0]);
int array2Length = Integer.valueOf(allNums[1]); // Modified
double array1[] = new double[array1Length];
double array2[] = new double[array2Length];
for (int i = 0; i < array1Length; i++) {
array1[i] = Double.valueOf(allNums[i + 2]); // Modified
}
print(array1);
for (int i = 0; i < array2Length; i++) {
array2[i] = Double.valueOf(allNums[array1Length + i + 2]);
}
print(array2);
if (Arrays.equals(array1, array2)) {
System.out.println("set one and set two are equal");
} else {
System.out.println("set one and set two are not equal");
}
}
private static void print(double[] array) {
for (double d : array) {
System.out.print(d + " ");
}
System.out.println();
}
}
输出:
2 2 3 4 3 4
3.0 4.0
3.0 4.0
set one and set two are equal
输出:
2 2 3 4 3 5
3.0 4.0
3.0 5.0
set one and set two are not
我刚检查过你的代码也没关系:
输出:
2 3 4 2 3 4
3.0 4.0
3.0 4.0
set one and set two are equal
2 3 4 2 3 5
3.0 4.0
3.0 5.0
set one and set two are not equal
在我的代码中:
在您的代码中:
两个看起来都很好。