This is my first question ever, so please be easy on me for formatting. I tried searching a lot for the answer but couldn't get what I wanted
This is the C program and is working as desired
#include <stdio.h>
#include <stdlib.h>
int main() {
int i,n;
struct student {
char name[20];
int roll;
int age;
float marks;
};
printf("Enter number of students\n");
scanf(" %d", &n);
struct student a[n];
for(i=0;i<n;i++) {
printf("Enter details of student %d\n",(i+1));
printf("Name : ");
scanf(" %[^\n]s", &a[i].name);
printf("Roll number: ");
scanf(" %d", &a[i].roll);
printf("Age : ");
scanf(" %d", &a[i].age);
printf("Marks : ");
scanf(" %f", &a[i].marks);
}
printf("\n%-20s%-20s%-20s%-20s\n\n", "Name", "Roll no", "Age", "Marks");
for(i=0;i<n;i++)
printf("%-20s%-20d%-20d%-20.2f\n", a[i].name, a[i].roll, a[i].age, a[i].marks);
return 0;
}
To write this in Java, I created a Student class first
public class Student {
public String name;
public int roll,age;
public float marks;
}
And then a TestStructure class to make the program
import java.util.Scanner;
public class TestStructure {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i,n;
System.out.println("Enter number of students");
n=sc.nextInt();
sc.nextLine(); //To consume new line
Student[] a=new Student[n];
for(i=0;i<n;i++) {
System.out.printf("Enter details of student %d\n",(i+1));
System.out.printf("Name : ");
a[i].name=sc.nextLine();
System.out.printf("Roll number: ");
a[i].roll=sc.nextInt();
System.out.printf("Age : ");
a[i].age=sc.nextInt();
System.out.printf("Marks : ");
a[i].marks=sc.nextFloat();
sc.nextLine(); //To consume new line
}
sc.close();
System.out.printf("\n%-20s%-20s%-20s%-20s\n\n", "Name", "Roll no", "Age", "Marks");
for(i=0;i<n;i++)
System.out.printf("%-20s%-20d%-20d%-20.2f\n", a[i].name, a[i].roll, a[i].age, a[i].marks);
}
}
But I get NullPointerException as soon as I enter the first name