简体   繁体   English

使用Java中的扫描器类输入

[英]Input using scanner class in 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 : 我正在编写一个程序以将给定的整数减少到最简单的比率,但是在程序的子方法中通过Scanner类获取输入时发生错误,代码如下:

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<T;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<N;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<N;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. 在这里,我在主要功能中使用了2个单独的扫描仪对象sc,在比率功能中使用了sc1从控制台获取输入。 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. 但是,如果我在类范围内声明了一个公共静态类型Scanner对象,然后在整个程序中仅使用一个Scanner对象来获取输入,那么程序将按要求正常工作而不会出错。

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. 发生此错误的原因是,在扫描器上调用.close()也会关闭inputStream System.in ,但实例化新的扫描器不会重新打开它。

You need to either pass a single Scanner around in your method parameters, or make it a static global variable. 您需要在方法参数中传递单个Scanner,或者使其成为静态全局变量。

Since your main() and your ratio() method are using Scanners they throw exceptions,when an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be handled. 由于您的main()ratio()方法正在使用扫描仪,因此它们会引发异常,因此,当发生异常时,程序的正常流程将被中断,并且程序/应用程序将异常终止,因此不建议这样做,因此应处理这些异常。 An exception can occur for many different reasons, below given are some scenarios where exception occurs. 异常可能由于多种原因而发生,下面给出了发生异常的一些情况。

A user has entered invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or the JVM has run out of memory.

You can handle these exceptions by using Try/Catch blocks,or you can handle them by using the word throws after your method's definition, in your case these two approaches are going to be like this: 您可以使用Try / Catch块来处理这些异常,也可以通过在方法的定义后使用throws来处理它们,在这种情况下,这两种方法将是这样的:

With Try/Catch : 使用try / catch

  public static void main()
  {
    try{
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();// number of test cases
        sc.close();
       }
    catch(NoSuchElementException e){
    System.out.print("Exception handled" + e);
    //rest of method
    }
    static void ratio(){
    try{
    Scanner sc1=new Scanner(System.in);
    int N=sc1.nextInt();}
    catch(NoSuchElementException e){
    System.out.print("Exception handled" + e);}
    //rest of method
    }

With "throws": 与“抛出”:

  public static void main()throws Exception{

       //rest of method
     }
   static void ratio()throws Exception
   { 
    //rest of method
   }

Try this one. 试试这个。 You can pass the scanner as argument 您可以将扫描仪作为参数传递

package stack.examples;

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
    if (T < 1) {
        System.out.println("Out of range");
        System.exit(0);
    }
    for (int i = 0; i < T; i++) {
        ratio(sc);// line 19
    }
    sc.close();
}

static void ratio(Scanner sc1) {
    int N = sc1.nextInt();// line 26
    //Your Logic
}

static int gcd(int a, int b) {
    while (b > 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

} }

import java.util.*;
public class Understanding_Scanner
{
public static void main()
{
Scanner sc= new Scanner(System.in);
System.out.println("Please enter your name");
String name=sc.next();
System.out.println("Your name is:"+name);
}
}

Now to explain this thing so we have to import a scanner class from the Java Utility package so this can be achieved by the code on the first line the second line is creating a class NOTE (THE NAME OF THE CLASS NEED NOT START WITH CAPITAL) now coming to the main topic Scanner class so for this we must create a scanner class within the program with the code that's been given in the 4th line... in this statement 'sc' is an object which stores the values of the scanner class so if you want to do any operation in the scanner class you can do it via the object 'sc' *NOTE(You can name ur object as anything eg:poop,bla etc)... then we have this interesting command which says System.in now this allows users to write any statement through the keyboard or any such input devices during run time.... String name=sc.next() this line helps us to write any string that we want to write during the run time, which will b stored in the name variable 现在解释一下这一点,因此我们必须从Java Utility包中导入一个扫描器类,以便可以通过第一行中的代码来实现,第二行创建一个类。 注意 (该类的名称不必以大写字母开头)现在进入主要主题Scanner类,因此,我们必须在程序中使用第四行给出的代码创建一个扫描器类...在此语句中,“ sc”是一个对象,用于存储扫描器类的值因此,如果您想在扫描仪类中进行任何操作,都可以通过对象'sc'* NOTE(您可以将ur对象命名为任何东西,例如:poop,bla等)...那么我们就有了一个有趣的命令,它说System.in现在允许用户在运行时通过键盘或任何此类输入设备编写任何语句。...字符串名称= sc.next()此行可帮助我们编写在运行期间要编写的任何字符串时间,它将b存储在名称变量中

So that's it, this is the scanner class for u. 就是这样,这是您的扫描器类。 Hope its easy to understand. 希望它易于理解。

cheers!! 干杯!! Keep coding :-) 继续编码:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM