I can collect all of the input data, but I just can't seem to do anything with it. I would like to print all of data or add or subtract the numbers, perform calculations. I am not sure how to work with nested data.
import java.util.Scanner;
public class Names {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many students do you want to enter?");
String[] names = new String[2];
for (int stnumber = 0; stnumber < 2; stnumber++) {
System.out.println("Enter the first student " + (stnumber + 1));
names[stnumber] = input.next();
String[] quiz = new String[2];
for (int qznumber = 0; qznumber < 2; qznumber++) {
System.out.println("Enter quiz mark " + (qznumber + 1));
quiz[qznumber] = input.next();
}
String[] midterm = new String[1];
for (int mtnumber = 0; mtnumber < 1; mtnumber++) {
System.out.println("Enter midterm mark " + (mtnumber + 1));
midterm[mtnumber] = input.next();
}
String[] myfinal = new String[1];
for (int fnnumber = 0; fnnumber < 1; fnnumber++) {
System.out.println("Enter final mark " + (fnnumber + 1));
myfinal[fnnumber] = input.next();
}
}
input.close();
System.out.println("The students marks are");
for (int stnumber = 0; stnumber < 2; stnumber++) {
System.out.println(names[stnumber]);
}
}
}
You should define a class to represent a Student:
public class Student {
String name;
String[] quizzes;
String[] midterms;
String[] finals;
}
Then, you will need a constructor to declare a new instance of a Student, here is an exmaple:
public Student(String name) {
this.name = name;
this.quizzes = new String[2];
this.midterms = new String[2];
this.finals = new String[1];
}
Now you can create a new student in your main method like this:
Student newStudent = new Student("put the name here");
And store the quizzes, midterms, etc in that instance of the Student:
newStudent.midterms[0] = "midterm 1 grade";
Related
Say I have 2 Scanner filled arrays, name[] and age[]. Each one filled in order. If I am to find the oldest person in the array how do I print out their name AND their age, using the arrays?
For example the largest entry in age[] was 78. Is there a way to relate it with the name[] array to print it out?.
Reference code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many entries ?");
int entries;
do {
entries = input.nextInt();
if (entries < 1) {
System.out.println("please enter a valid number!");
}
} while (entries < 1);
String[] name = new String[entries];
String[] gender = new String[entries];
int[] age = new int[entries];
for (int i = 0; i < entries; i++) {
System.out.println("Enter the name of person No" + (i + 1) + ".");
name[i] = input.next();
}
double ageSum = 0;
int max = 0;
for (int i = 0; i < entries; i++) {
System.out.println("How old is " + name[i] + " ?");
age[i] = input.nextInt();
ageSum += age[i];
max = Math.max(max, age[i]);
}
System.out.println("the oldest person is "
+ name[] + " whose " + max + " years old.");
}
Assuming that your arrays have the same size and the ages corresponding to the names then you can check for the highest age and store the indice of the element with the highest age.
Then you have your name at this indice.
int highestAgeIndice = 3; //indice of element with age 97 as example
names[highestAgeIndice] // the corresponding name
Calculating highest age and store its indice
int max = 0;
int highestInd = 0;
for (int i = 0; i < age.length; i++) {
if (age[i] > max) {
max = age[i];
highestInd = i;
}
}
System.out.println("the oldest person is " +
name[highestInd] + " whose " + max + " years old.");
The Code
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many entries ?");
int entries;
do {
entries = input.nextInt();
if (entries < 1) {
System.out.println("please enter a valid number!");
}
} while (entries < 1);
String[] name = new String[entries];
String[] gender = new String[entries];
int[] age = new int[entries];
for (int i = 0; i < entries; i++) {
System.out.println("Enter the name of person No" + (i + 1) + ".");
name[i] = input.next();
}
double ageSum = 0;
for (int i = 0; i < entries; i++) {
System.out.println("How old is " + name[i] + " ?");
age[i] = input.nextInt();
ageSum += age[i];
}
int max = 0;
int highestInd = 0;
for (int i = 0; i < age.length; i++) {
if (age[i] > max) {
max = age[i];
highestInd = i;
}
}
System.out.println("the oldest person is " +
name[highestInd] + " whose " + max + " years old.");
}
If you have two arrays name[] and age[], you can relate them by creating some class Person with fields of type the entries in these arrays, and get a list of persons List<Person>, something like this:
static class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
#Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
public static void main(String[] args) {
String[] name = {"Junior", "Senior", "Middle"};
int[] age = {25, 78, 40};
List<Person> people = IntStream.range(0, name.length)
.mapToObj(i -> new Person(name[i], age[i]))
.collect(Collectors.toList());
// sort by age in reverse order
people.sort(Comparator.comparing(
Person::getAge, Comparator.reverseOrder()));
// output
people.forEach(System.out::println);
}
Output:
Person{name='Senior', age=78}
Person{name='Middle', age=40}
Person{name='Junior', age=25}
See also: How do I sort two arrays in relation to each other?
You could use indexOf on you array age for the Max age which will tell you the index of the associated name.
names[age.indexOf(Max)]
I need to create a 2d array which can read in the student ID's of 50 students and each of their 7 subject marks. I have come up with a way to store subject marks but not sure how to store the student ID's.
Here is the code so far.
public static void main(String[] args)
{
double mark;
double[][] studs = new double[50][7];
Scanner fromKeyboard = new Scanner(System.in);
for (int studentNo = 0; studentNo < 3; studentNo++) {
System.out.println("enter student ID number for student " + studentNo);
for (int moduleNo = 0; moduleNo < 2; moduleNo++) {
System.out.println("Enter users mark for module " + moduleNo);
mark = fromKeyboard.nextDouble();
studs[studentNo][moduleNo] = mark;
}
}
}
You have only one array of a single primitive type, but you have two pieces of information.
Two simple options are
1) Use another array to store the IDs
2) (Better solution IMO) Create your own Student class, and define an array Student[] (A student should contain a field for an array of marks)
You can use array[n][0] to store student id.
This should work:
public static void main(String[] args)
{
double mark = 0d;
int id = 0;
double[][] studs = new double[50][8];
Scanner fromKeyboard = new Scanner(System.in);
for (int studentNo = 0; studentNo < 50; studentNo++) {
System.out.print("enter student ID number for student " + (studentNo + 1) + ":");
id = fromKeyboard.nextInt();
studs[studentNo][0] = id;
for (int moduleNo = 1; moduleNo < 8; moduleNo++) {
System.out.print("Enter mark of student " + id + " for module " + moduleNo);
mark = fromKeyboard.nextDouble();
studs[studentNo][moduleNo] = mark;
}
}
fromKeyboard.close();
}
NOTES:
If you cannot modify the original array or you need to store students name, for example, you can create a new array to store students id like.
String[] studentsId = new String[50];
int[] studentsId = new int[50];
remember to close resources when using it: fromKeyboard.close();
When I understood your question correct:
public static void main(String[] args)
{
double[][] studs = new double[50][8];
Scanner fromKeyboard = new Scanner(System.in);
for (int studentNo = 0; studentNo < 50; studentNo++) {
System.out.println("enter student ID number for student " + studentNo);
studs[studentNo][0] = fromKeyboard.nextDouble(); //save id
for (int moduleNo = 1; moduleNo < 8; moduleNo++) {
System.out.println("Enter users mark for module " + moduleNo);
studs[studentNo][moduleNo] = fromKeyboard.nextDouble(); // your 7 marks
}
}
}
You're on the right track.
You aren't reading the studentNo input. So you need to read that and place it in the first cell before the inner loop. Then put all the marks on the same row along side it. This is depending on the type of student ID, is it a String or number?
Also, why have 7 columns in the array and only loop twice for subject grades? Is there more to do here. If not avoid using up the space.
I am trying to figure out how to get my array to run correctly, I know I have to change the array value to an input but I cannot get the program to compile if any one can help that be great.
I am trying to have the program take input for grades and names of students and in the end output their name and grade.
Edit sorry this is my first it posting i have an error
Student.java:60: error: class, interface, or enum expected I am in java 101 so this is why it is such low level java, we only know the basics
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
and my second class is
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
} <--- error here
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
Add return statement in your multiplegradeinputs() method:
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
return null; //Add this line
}
Or change your methods to void return type if they dont return anything.
Class names have to be capitalized in java, so instead of
public class students
you should write
public class Students
Also instead of writing
keyboard.nextInt();
You should write
Integer.parseInt(keyboard.nextLine());
This is mainly because java is full of bugs and technical specifications that you won't find easily. Let me know if this fixes it for you, since you didn't post the exact error message you got.
As for the error that you pointed out, it's because your function expects a String as a return value no matter what, so either change that to void if you can or return a null string. To do that just add the following line at the very end of the method.
return null;
You should create a Student object which holds the properties of the student, e.g. Name and Grades. You should then store all the student objects in some kind of data structure such as an array list in the students class.
Adding to the answer provided by #hitz
You have a bug in the for loops:
for(int i = 1; i <multiplegradeinputs.length; i++)
for(int i = 1; i < multipleStudent.length; i++)
You will never populated multiplegradeinputs[0] and multipleStudent[0] because you start the loop at index == 1 and thus you will have only 9 student names stored instead of 10.
Change to:
for(int i = 0; i <multiplegradeinputs.length; i++)
for(int i = 0; i < multipleStudent.length; i++)
Remember even though the length in 10, the indices always start with 0 in Java and in your case will end with 9.
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public void multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
}
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
this is the 2nd class
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
You are missing a return value in the multiplegradeinputs() method.
import java.util.Scanner;
public class TestPerson
{
/**
* Creates a new instance of <code>TestPerson</code>.
*/
public TestPerson()
{
}
/**
* #param args
* the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Menus[] menu = { new Menus("Add Member") };
MemberType[] m = { new MemberType("Corporate Member"), new MemberType("VIP Member") };
Clubs[] c = { new Clubs("Yoga", "Miss AA"), new Clubs("Kick-boxing", "Mr.AA"), new Clubs("aerobics", "Mrs.Wendy") };
RegMember[] r = new RegMember[1];
Cmember cm;
Vipmember vip;
Scanner s = new Scanner(System.in);
int choice = 0;
for (int z = 0; z < menu.length; z++)
{
System.out.println((z + 1) + ". " + menu[z].toString());
}
System.out.println("\nEnter Your selection:");
int choice = s.nextInt();
while (choice == 1)
{
for (int i = 0; i < r.length; i++)
{
System.out.println("\nYour reg no is :" + (RegMember.getNextNo() + 1));
for (int a = 0; a < m.length; a++)
{
System.out.println((a + 1) + ". " + m[a].toString());
}
System.out.println("\nEnter Your selection:");
int sel = s.nextInt();
if (sel == 1)
{
s.nextLine();
System.out.println("Enter name:");
String Name = s.nextLine();
System.out.println("Enter Handphone:");
String Hpnum = s.next();
System.out.println("Enter Age:");
int age = s.nextInt();
System.out.println("Enter Company Name:");
String CompanyName = s.nextLine();
String memberType = "Corporate Member";
for (int b = 0; b < c.length; b++)
{
System.out.println((b + 1) + ". " + c[b].toString());
}
System.out.println("\nEnter Your selection:");
int sel2 = s.nextInt();
String clubs = "Yoga";
cm = new Cmember(Name, Hpnum, age, CompanyName, memberType, clubs);
r[i] = new RegMember(cm);
}
else
{
s.nextLine();
System.out.println("---You will get a free exercise class---");
System.out.println("Enter name:");
String Name = s.nextLine();
System.out.println("Enter Handphone:");
String Hpnum = s.next();
System.out.println("Enter Age:");
int age = s.nextInt();
System.out.println("Enter Email:");
String email = s.next();
String memberType = "VIP Member";
vip = new Vipmember(Name, Hpnum, age, email, memberType);
r[i] = new RegMember(vip);
}
s.nextLine();
}
}
displayInfor(r);
}
public static void displayInfor(RegMember[] r)
{
for (int i = 0; i < r.length; i++)
System.out.println(r[i].toString());
}
}
I am a beginner for java. I am facing the problem that my code is continue looping.How to solve it?? thank you.
Your choice variable is never set to not = 1. Therefore the while loop will continue to run forever.
edit: With the amount of log messages in that code you should be able to see where surely.
If you are using If statements as such why not just alter the choice variable manually.
Anyway its too vague your question specify which loop and it would be easier to help
import java.util.Scanner;
class DataInput {
String name[];
int korean[], math[], english[];
int sum[];
double average[];
int students;
int rank[];
public void save() {
Scanner sc = new Scanner(System.in);
System.out.println("Type in number of students");
students = sc.nextInt();
name = new String[students];
korean = new int[students];
math = new int[students];
english = new int[students];
sum = new int[students];
average = new double[students];
rank = new int[students];
for (int i = 0; i < students; i++) {
System.out.println("Type name");
name[i] = sc.next();
System.out.println("Type Korean score");
korean[i] = sc.nextInt();
System.out.println("Type math score");
math[i] = sc.nextInt();
System.out.println("Type English score");
english[i] = sc.nextInt();
sum[i] = korean[i] + math[i] + english[i];
average[i] = sum[i] / 3.0;
}
}
int stu() {
return students;
}
int[] sum() {
return sum;
}
}
class DataOutput {
DataInput data = new DataInput();
int sNum;
int[] rrank, sum;
DataOutput(int students, int[] sum) {
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
void ranker() {
int cnt = 1;
for (int i = 0; i < sNum; i++) {
for (int j = 0; j < sNum; j++) {
if (sum[i] < sum[j]) {
cnt++;
}
}
rrank[i] = cnt;
cnt = 1;
}
}
}
public class Score {
public static void main(String[] args) {
DataInput data = new DataInput();
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
data.save();
out.ranker();
System.out.println();
System.out.println("Name\t\tKorean math English \t sum Average Rank");
System.out
.println("-------------------------------------------------------");
for (int i = 0; i < data.stu(); i++) {
System.out.println(data.name[i] + "\t\t" + data.korean[i] + " "
+ data.math[i] + " " + data.english[i] + "\t"
+ data.sum[i] + " " + data.average[i] + " "
+ out.rrank[i]); // this is where i get an Exception
}
}
}
So, this is my program for getting ranks of students. But somehow when I run the code, I keep getting "OutOfBoundaryException". I checked my code, and realized that when I instantiate a new instance of DataOutput, it creates all new data. So I tried to fix this by setting a constructor. However I still can't solve this matter. I know that I can put the ranker method into DataInput class, and problem will be easily solved however I really want to keep DataOutput class.
Thank you for your time.
PS: Exception is thrown on line 98, out.rrank[i]
Your students field isn't set until the save() method is called. The value of sNum in main is then 0.
Change the order in main to:
DataInput data = new DataInput();
data.save();// <--
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
out.ranker();
the problem was that you initialize the rank[] before creating students, As soultion I suggest you to initialize after collection students/scores
public void init(int students, int[] sum){
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
And update main()
DataOutput out = new DataOutput();
data.save();
int sNum = data.stu();
int[] sum = data.sum();
out.init(sNum, sum);
out.ranker();