scanner类包不存在错误

时间:2015-08-22 13:00:04

标签: java

我正在尝试编译Java程序,但它产生了一个错误。

有人可以告诉我我在哪里犯了错误以及如何解决它?

import java.io.*;
import java.util.*;
class detail
{
String name;
int age;
float salary;
void getdata()
{
    Scanner sc=new Scanner(System.in);
    System.out.println("enter name: ");
    name=new sc.next();
    System.out.println("enter age: ");
    age=new sc.nextInt();
    System.out.println("enter salary: ");
    salary=new sc.nextFloat();
}

void display()
{
    System.out.println("name: "+name);
    System.out.println("age: "+age);
    System.out.println("salary: "+salary);
}
}

class person
{
    public static void main(String arr[])
    {
        detail p=new detail();
        p.getdata();
        p.display();
    }
}

4 个答案:

答案 0 :(得分:1)

你有3行包含

new sc

删除new,因为sc不是类,而是变量,您已在此行中创建了Scanner对象:

Scanner sc=new Scanner(System.in);

new关键字只允许,如果在方法引用中跟随构造函数调用或在java 8中,如果键入new sc,则不允许{<1}}。

答案 1 :(得分:1)

您无需致电new sc.nextInt()。您使用“new”来创建新对象。您的对象Scanner由变量sc创建,因此您已经可以使用他们的方法。

就像那样:

age = sc.nextInt();

答案 2 :(得分:0)

只需删除以下行中的新内容即可使用

name=new sc.next();
System.out.println("enter age: ");
age=new sc.nextInt();
System.out.println("enter salary: ");
salary=new sc.nextFloat(); 

答案 3 :(得分:0)

问题出在像name=new sc.next();这样的行上。您已使用new创建名为Scanner的{​​{1}}实例。您只需要在其上调用实例方法:

sc

您的代码确实存在一些其他问题,主要是文体:

import java.io.*;
import java.util.*;

class detail {
    String name;
    int age;
    float salary;

    void getdata() {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter name: ");
        name = sc.next();
        System.out.println("enter age: ");
        age = sc.nextInt();
        System.out.println("enter salary: ");
        salary = sc.nextFloat();
    }

    void display() {
        System.out.println("name: " + name);
        System.out.println("age: " + age);
        System.out.println("salary: " + salary);
    }
}

class person {
    public static void main(String arr[]) {
        detail p = new detail();
        p.getdata();
        p.display();
    }
}
相关问题