如何在java中使用Scanner类时解决错误

时间:2014-02-17 05:33:11

标签: java

我创建了一个“我的”类,其中我只是使用Scanner类“

从用户那里获取输入
import java.util.Scanner;

class My
{
    public static void main(String[] args)
    {
         int val;
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter no = ");
         val= sc.nextInt();

         System.out.println("number " + val);
    }
}

但我收到以下错误:

My.java:1: cannot resolve symbolsymbol  : class Scanner
location: package util
import java.util.Scanner;

My.java:8: cannot resolve symbol
symbol  : class Scanner
location: package util
 java.util.Scanner scanner = new java.util.Scanner(System.in);

My.java:8: cannot resolve symbol
symbol  : class Scanner
location: package util
 java.util.Scanner scanner = new java.util.Scanner(System.in);

3 个答案:

答案 0 :(得分:0)

您已将Scanner个对象设为scanner,因此请将sc更改为scanner。代码将编译没有任何问题。

还有一点,而不是使用下面的代码

java.util.Scanner sc = new java.util.Scanner(System.in);

您可以直接使用Scanner sc = new Scanner(System.in),因为您已经导入了扫描仪类

import java.util.Scanner;

注意:使用java1.5及更高版本访问Scanner类

答案 1 :(得分:0)

`import java.util.Scanner;`

您可以为扫描仪保留名称sc,但更改

`java.util.Scanner` in the body of your code to `Scanner` as you don't need to call the imported package to declare the object.

更新

import java.util.Scanner;

class My
{
    public static void main(String[] args)
    {
    int val;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter no = ");
    val= sc.nextInt();

    System.out.println("number " + val);
    }
}

答案 2 :(得分:0)

包裹回文; import java.util.Scanner;

公共类Num_Palindrome {

public Num_Palindrome() {

}

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int y=sc.nextInt();
    System.out.println(y);

     int r,sum=0,number;    
      int n=895; 

      number=n;    
      while(n>0){    
       r=n%10;   
       sum=(sum*10)+r;    
       n=n/10;
      }
       if(number==sum)
           System.out.println("The Number is Palindrome = "+number);
       else
           System.out.println("The Number is not Palindrome = "+number);
       **sc.close();** 
        }

}

使用 - >>>>> sc.close();