prog to read students particulars such as roll etc from key board using array? [closed]
import java. util.*;
class student
{
private int rollno;
private int age;
private String sex;
private float height;
private float weight;
void getinfo()
{
System.out.println("enter the roll no of the student");
Scanner obj=new Scanner(System.in);
rollno=obj.nextInt();
System.out.println("enter the age of student");
Scanner obj1=new Scanner(System.in);
age=obj1.nextInt();
System.out.println("enter the sex of the student");
Scanne开发者_JS百科r obj3=new Scanner(System.in);
sex=obj3.nextLine();
System.out.println("enter the heighrt of student ");
Scanner obj4=new Scanner(System.in);
height=obj4.nextFloat();
System.out.println("enter the weight of the student");
Scanner obj5=new Scanner(System.in);
weight=obj5.nextFloat();
}
void disinfo()
{
System.out.println(rollno);
System.out.println(age);
System.out.println(sex);
System.out.println(height);
System.out.println(weight);
}
}
public class str
{
public static void main(String[]args)
{
student object[]=new student[5];
System.out.println("enter the number of student");
int i;
int n;
Scanner obj6=new Scanner(System.in);
n=obj6.nextInt();
for(i=1;i<n;i++)
{
object[i].getinfo();
}
System.out.println("diplaying the result");
for(i=1;i<n;i++)
{
object[i].disinfo();
}
}
}
You will need to add setters and getters to the class student
. In Java, class names have the first letter in upper case. object
is a keyword, so you cannot name any variables like so. In Java, arrays are zero based, so starting a loop from 1 will skip the first array location. In this part of your code:
for(i=1;i<n;i++)
{
object[i].disinfo();
}
You are most likely to get an ArrayOutOfBoundsException
since you are creating an array of 5 locations and then, try to access a number of locations that is given by the user, and you do not make any checks either.
So basically... create setters and getters for your fields in the class named Student
. In the main class, create an array of students. Create a loop, and within the loop, ask the user to provide the information, such as age, sex, etc.
I strongly suggest you take a look at some beginner tutorials or books.
精彩评论