Reputation: 185
So i have to input 10 names and marks into two arrays, and print out the best students name and marks. I am still new to java, i can only print out the max mark from the array, but how am i going to link it to the students name?
import java.util.Scanner;
public class storeMarks {
public static void main (String[]args){
Scanner tomato = new Scanner(System.in);
double max;
double marks[];
marks= new double[10];
int i;
for(i=0; i<10; i++) {
System.out.println("Enter marks: ");
marks[i]=tomato.nextDouble();
}
max = marks[0];
for(i = 0; i < 10; i++) {
if(max < marks[i]) {
max = marks[i];
}
}
System.out.println("Highest marks:"+max);
}
}
Upvotes: 0
Views: 12699
Reputation: 144
I created a class student:
public class Student {
private double mark;
private String name;
public Student()
{
mark = 0;
name = "";
}
public Student(int mark, String name)
{
this.mark = mark;
this.name = name;
}
public double getMark()
{
return mark;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public void setMark(double mark)
{
this.mark = mark;
}
}
then I edited your code in main
public static void main(String[] args) {
// TODO code application logic here
ArrayList<Student> studs = new ArrayList<Student>();
for(int i=0; i< 3; i++)
{
studs.add(new Student());
}
Scanner tomato = new Scanner(System.in);
double max;
int i;
for(i=0; i<3; i++) {
System.out.println("Enter name of student: ");
studs.get(i).setName(tomato.nextLine());
System.out.println("Enter marks: ");
studs.get(i).setMark(tomato.nextDouble());
tomato.nextLine();
}
int position = 0;
max = studs.get(0).getMark();
for(i = 0; i < 3; i++) {
if(max < studs.get(i).getMark()) {
max = studs.get(i).getMark();
position = i;
}
}
System.out.println("Highest marks:"+studs.get(position).getMark() + " student name " + studs.get(position).getName());
}
however, it is not the simplest choice
Edit: Simplier
public static void main(String[] args) {
// TODO code application logic here
Scanner tomato = new Scanner(System.in);
double[] marks = new double[10];
String[] names = new String[10];
double max;
int i;
for(i=0; i<3; i++) {
System.out.println("Enter name of student: ");
names[i] = (tomato.nextLine());
System.out.println("Enter marks: ");
marks[i] = tomato.nextDouble();
tomato.nextLine();
}
int position = 0;
max = marks[i];
for(i = 0; i < 3; i++) {
if(max < marks[i]) {
max = marks[i];
position = i;
}
}
System.out.println("Highest marks:"+ marks[position] + " student name " + names[position]);
}
Upvotes: 2