PRIME1-Prime生成器Java
我用JAVA编写了代码,在Eclipse中似乎工作得很好。但是当我在SPOJ(运行时错误(NZEC))中提交代码时,我得到了一个错误 有人能帮我做这个吗 以下是我迄今为止所做的尝试:PRIME1-Prime生成器Java,java,arrays,Java,Arrays,我用JAVA编写了代码,在Eclipse中似乎工作得很好。但是当我在SPOJ(运行时错误(NZEC))中提交代码时,我得到了一个错误 有人能帮我做这个吗 以下是我迄今为止所做的尝试: class Main { public static void main(String[] args) throws java.lang.Exception { Scanner n1 = new Scanner(System.in); Scanner n3 = new S
class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner n1 = new Scanner(System.in);
Scanner n3 = new Scanner(System.in);
int n2 = n1.nextInt();
int[][] n4 = new int[n2][2];
for (int i = 0; i < n2; i++) {
String[] s2 = n3.nextLine().split(" ");
for (int j = 0; j < 2; j++) {
n4[i][j] = Integer.parseInt(s2[j]);
}
}
for (int i = 0; i < n2; i++){
for(int j=n4[i][0];j<=n4[i][1];j++){
if(isPrimeNumber(j)){
System.out.println(j);
}
}
System.out.println();
}
}
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
主类{
公共静态void main(字符串[]args)引发java.lang.Exception{
扫描仪n1=新扫描仪(系统英寸);
扫描仪n3=新的扫描仪(System.in);
int n2=n1.nextInt();
int[]n4=新int[n2][2];
对于(int i=0;i 对于(int j=n4[i][0];j您需要做的第一件事是正确使用扫描仪,并去掉第二台
您使用2台扫描仪是因为只有一台不能按预期工作,为什么?
因为您忘记了该方法不会使用输入的最后一个换行符,因此在下次调用Scanner#nextLine时会使用该换行符
试试这个:
public static void main(String[] args) throws ParseException {
Scanner input = new Scanner(System.in);
int n2 = input.nextInt();
input.nextLine();
int[][] n4 = new int[n2][2];
for (int i = 0; i < n2; i++) {
String string2 = input.nextLine();
String[] s2 = string2.split(" ");
for (int j = 0; j < 2; j++) {
n4[i][j] = Integer.parseInt(s2[j]);
}
}
for (int i = 0; i < n2; i++) {
for (int j = n4[i][0]; j <= n4[i][1]; j++) {
if (isPrimeNumber(j)) {
System.out.println(j);
}
}
System.out.println();
}
}
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
publicstaticvoidmain(字符串[]args)引发异常{
扫描仪输入=新扫描仪(System.in);
int n2=input.nextInt();
input.nextLine();
int[]n4=新int[n2][2];
对于(int i=0;i 对于(int j=n4[i][0];j使用两个扫描仪的原因是什么?通常只有一个扫描仪就足够了…嗨..我尝试只使用一个扫描仪。但不知何故,当我使用.nextLine()和.nextInt()时,代码不起作用同一台扫描仪上的功能。我是新手。如果我用错了,请告诉我。先生,这很有帮助。但我似乎仍然无法理解使用扫描仪的整个概念。是否有任何文章对此进行了详细解释。非常感谢您的帮助