java扫描器,使用Java中的扫描器类输入

I was making a program to reduce given integers to their simplest ratio.But an error is occurring while taking inputs through Scanner class in a sub-method of program.Here is the code :

package CodeMania;

import java.util.Scanner;

public class Question5

{

public static void main(String args[])

{

Scanner sc=new Scanner(System.in);

int T=sc.nextInt();// number of test cases

sc.close();

if(T<1)

{

System.out.println("Out of range");

System.exit(0);

}

for(int i=0;i

{

ratio();//line 19

}

}

static void ratio()

{

Scanner sc1=new Scanner(System.in);

int N=sc1.nextInt();//line 26

if((N>500)||(N<1))

{

System.out.println("Out of range");

System.exit(0);

}

int a[]=new int[N];

for(int i=0;i

{

a[i]=sc1.nextInt();

}

int result = a[0];

for(int i = 1; i < a.length; i++)

{

result = gcd(result, a[i]);

}

for(int i=0;i

{

System.out.print((a[i]/result)+" ");

}

sc1.close();

}

static int gcd(int a, int b)

{

while (b > 0)

{

int temp = b;

b = a % b;

a = temp;

}

return a;

}

}

The error is--

Exception in thread "main" java.util.NoSuchElementException

at java.util.Scanner.throwFor(Scanner.java:862)

at java.util.Scanner.next(Scanner.java:1485)

at java.util.Scanner.nextInt(Scanner.java:2117)

at java.util.Scanner.nextInt(Scanner.java:2076)

at CodeMania.Question5.ratio(Question5.java:26)

at CodeMania.Question5.main(Question5.java:19)

Here I have used 2 seperate scanner objects sc in main function and sc1 in ratio function to take input from console.

However if I am declaring a public static type Scanner object in class scope and then using only one Scanner object throughout the program to take input then program is working as required without error.

Why this is happening...?

解决方案

The reason for this error is that calling .close() on the scanner also closes the inputStream System.in, but instantiating a new Scanner will not re-open it.

You need to either pass a single Scanner around in your method parameters, or make it a static global variable.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值