“Cannot be resolved to a type” when attempting to

2020-02-02 00:41发布

问题:

when i run following code it shows error that scanner cannot be resolved to type. i checked that jre is installed and version is 1.7 what else do i need to check ? please help.

public class student { 

String name;
int rollno;
public void get(String nm, int rno) 
{ name=nm;
rollno=rno;
}
public void  display()
{  System.out.println("Name of student is :" +name);
System.out.println("Roll no of student is :" +rollno);
}  
public static void main(String args[])
{ 
int i ;
int r1;
String n1;
student obj[]= new student[10];
Scanner sc=new Scanner(System.in);
for(i=0;i<10;i++)
{
obj[i]= new student();
}

for(i=0;i<10; i++)
{  System.out.println("Enter name:");
n1=sc.next();
sc.nextLine();
System.out.println("Enter roll no :");
r1=sc.nextInt();


obj[i].get(n1,r1) ;
obj[i].display() ;
}
}
}

回答1:

You need to also import the class itself. At the very top of the file, above public class student, you need to add:

import java.util.Scanner;

In addition, I'd like to pose a few more possible corrections:

  • Class names should be PascalCase
  • Your code should have consistent indentation. Ctrl+Shift+F is your friend here.


回答2:

Just use import java.util.Scanner; or use import java.util.*;



回答3:

I tried the code myself and it works. Therefore, it is a configuration problem. Since you tried to import java.util.Scanner, as hexafraction suggested, then I suppose the JRE is not properly configured.

Try :

  • Right clicking your project name -> Click properties -> Click Java Build Path
  • Select the libraries tab
  • Click on add class folder (at the right) then select your Class.

Edit : Even tho it would not really solve the problem, copy the src folder in a new project would probably solve your issue.



回答4:

Check your code's compilation level by right click your project in eclipse and click properties.

It might point to 1.6 or lower. If it is the case point it to 1.7

This might solve your problem.

I hope it helps.



回答5:

Right click on your package > Navigate to properties > Click on java build path > Click on libraries tab > Click on add library > Select JRE System library > Click on next > Click on Finish > Click on apply and Close. enter image description here It should work.... I hope so :)