暂停扫描仪用户输入

时间:2018-10-18 19:05:38

标签: java java.util.scanner

真的是学习Java的早期阶段,因此我为自己的无知表示歉意,但遇到了一些困难。因此,我导入了扫描仪类,提示用户输入数字等,但是现在我似乎无法使用println命令,并且我想知道如何恢复正常,因此它不接受用户输入。这是我的代码!

import java.util.Scanner;//Setting up scanner 

public class worksheet01 {
    public static void main(String args[]) {
        int num1;//declaring variable
        Scanner in = new Scanner(System.in);//for taking user input
            System.out.println("Hello user please enter a number"); //ask user to enter number
        num1 =in.nextInt();//Storing inputed value in num1
        if (num1 % 2==0) 
            System.out.println("The number is even");//If the number is even this will print out
        else 
            System.out.println("The number is odd");//If the number is odd this will print out
        Scanner .close();

            }   

    }

1 个答案:

答案 0 :(得分:0)

Scanner.close(); 变成 in.close() 应该可以解决问题。这是因为 .close() 函数仅适用于扫描仪名称。如果您没有将扫描仪命名为 scanner,那么它将无法工作。在您的代码中,您输入:

Scanner in = new Scanner(System.in);

这表明扫描器在中被调用,因此您应该使用 in.close() 而不是 Scanner.close();

您的回答:

import java.util.Scanner;//Setting up scanner 
public class test {
  public static void main(String args[]) {
    int num1;//declaring variable
    Scanner in = new Scanner(System.in);//for taking user input
    System.out.println("Hello user please enter a number"); //ask user to enter number
    num1 = in.nextInt();//Storing inputed value in num1
    if (num1 % 2==0) {
      System.out.println("The number is even");//If the number is even this will print out
    } else {
      System.out.println("The number is odd");//If the number is odd this will print out 
    }
    in.close();
  }   
}