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)]
Related
I am creating a student grade book that allows a user to input their students names and 4 grades, then have options to calculate student and class averages, as shown in the pic below.
With the code below, I am receiving the student average as "0.0%" and no errors. Am I correctly instructing the program to see if the students name matches the appropriate element in the two-dimensional array?
I have all the other parts of the program working.
private String[][] grades = new String[16][5];
//Declare Variables
String firstName, lastName, name;
String test1, test2, test3, test4;
test1 = t1Input.getText();
test2 = t2Input.getText();
test3 = t3Input.getText();
test4 = t4Input.getText();
firstName = firstInput.getText();
lastName = lastInput.getText();
name = firstName + " " + lastName + ": ";
grades[students][0] = name;
grades[students][1] = test1;
grades[students][2] = test2;
grades[students][3] = test3;
grades[students][4] = test4;
students++;
private void sAvgInputActionPerformed(java.awt.event.ActionEvent evt) {
String firstName = firstInput.getText();
String lastName = lastInput.getText();
String name = firstName + " " + lastName + ": ";
int sum = 0;
double divide = 0;
for (int i = 0; i <= 1; i++) {
if (name.equals(grades[0][1])) {
for (int grade = 1; grade <= 4; grade++) {
sum = Integer.parseInt(grades[i][1]) + i;
}
break;
}
}
divide = sum / 4;
gradesOutput.setText(firstName + "'s grade average is " + divide + "%.");
}
Change the loop to this:
//assume it as a simple table since its 2d array
//Since you are storing the name in first(0th index) column,
//only row should be loop
for (int i = 0; grades[i][0] != null; i++) {
if (name.equals(grades[i][0])) {
for (int grade = 1; grade <= 4; grade++)
//same row,different column
sum = sum + Integer.parseInt(grades[i][grade]);
break;
}
}
I'm having trouble making option 7 work in my code (i.e. choice == 7), the one that outputs a student's set of quiz scores.
When I run the program, it simply asks for jumps back to the original set of choices.
Any help would be much appreciated.
package studentquizgrades;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class StudentQuizGrades {
public static void main(String[] args) {
Map<String, Student> map = new HashMap<>();
addStudent(map);
}
private static void addStudent(Map<String, Student> map) {
Scanner userInput = new Scanner(System.in);
boolean finish = false;
do {
System.out.println("Please choose an option: ");
System.out.println("Add student and quizzes - 1, Get all quiz scores - 2, Get highest quiz score- 3, ");
System.out.println("Get lowest quiz score - 4, Get class average - 5, View a list of all students - 6");
System.out.println("Get a student's quiz scores - 7, Quit - 8");
int choice = userInput.nextInt();
if (choice == 1) {
Set<String> keySet = map.keySet();
System.out.println("How many students would you like to add?");
int numberOfStudents = userInput.nextInt();
for (int counter = 0; counter < numberOfStudents; counter++) {
System.out.println("ENTER NAME");
Scanner addName = new Scanner(System.in);
String name = (addName.nextLine());
System.out.println("Enter First Quiz Score");
Scanner addQuiz1 = new Scanner(System.in);
int quiz1 = (addQuiz1.nextInt());
System.out.println("Enter Second Quiz Score");
Scanner addQuiz2 = new Scanner(System.in);
int quiz2 = (addQuiz2.nextInt());
System.out.println("Enter Third Quiz Score");
Scanner addQuiz3 = new Scanner(System.in);
int quiz3 = (addQuiz3.nextInt());
Student student = new Student(name, quiz1, quiz2, quiz3);
map.put(student.getKey(), student);
}
} else if (choice == 2) {
Set<String> keySet = map.keySet();
for (String currentKey : keySet) {
Student student = map.get(currentKey);
System.out.println();
System.out.println(currentKey);
System.out.println(Arrays.toString(student.getQuizGrades()));
System.out.println();
}
} else if (choice == 3) {
Set<String> keySet = map.keySet();
int max = 0;
String maxName = null;
for (String currentKey : keySet) {
Student student = map.get(currentKey);
int[] scores = student.getQuizGrades();
for (int counter = 1; counter < scores.length; counter++) {
if (scores[counter] > max) {
max = scores[counter];
maxName = currentKey;
}
}
}
System.out.println();
System.out.println("The highest quiz score was " + max + "; his/her name is " + maxName);
System.out.println();
} else if (choice == 4) {
Set<String> keySet = map.keySet();
int min = Integer.MAX_VALUE;
String minName = null;
for (String currentKey : keySet) {
Student student = map.get(currentKey);
int index = 0;
int[] scores = student.getQuizGrades();
for (int counter = 0; counter < scores.length; counter++) {
if (scores[counter] < min) {
minName = currentKey;
min = scores[counter];
}
}
}
System.out.println();
System.out.println("The lowest quiz score was " + min + "; his or her name is " + minName);
System.out.println();
} else if (choice == 5) {
Set<String> keySet = map.keySet();
int[] allGrades;
int sum = 0;
int counter2 = 0;
for (String currentKey : keySet) {
Student student = map.get(currentKey);
int[] scores = student.getQuizGrades();
for (int counter = 0; counter < scores.length; counter++) {
int j = scores[counter];
sum = sum + j;
counter2++;
}
}
int average = sum / counter2;
System.out.println("");
System.out.println("The class average is: " + average);
System.out.println("");
} else if (choice == 6) {
Set<String> keySet = map.keySet();
System.out.println("");
System.out.println("List of students: ");
for (String currentKey : keySet) {
Student student = map.get(currentKey);
System.out.println(currentKey);
}
}
else if(choice == 7){
Set<String> keySet = map.keySet();
System.out.println("");
System.out.println("Please enter a student's name: ");
String studentName = userInput.nextLine();
for (String currentKey : keySet) {
Student student = map.get(currentKey);
if(studentName == currentKey){
System.out.println(currentKey + "'s quiz scores:");
int [] quizArray = student.getQuizGrades();
for(int counter1 = 0; counter1 < quizArray.length; counter1++ ){
System.out.println(quizArray[counter1]);
}
}
}
}
else if (choice == 8) {
finish = true;
break;
}
} while (finish == false);
}
}
package studentquizgrades;
public class Student {
private String key;
private int grade1;
private int grade2;
private int grade3;
public Student(String key, int grade1, int grade2, int grade3){
this.key = key;
this.grade1 = grade1;
this.grade2 = grade2;
this.grade3 = grade3;
}
public String getKey(){
return key;
}
public int[] getQuizGrades(){
int [] anArray = {grade1, grade2, grade3};
return anArray;
}
public int getAverageScore(){
int average = (grade1 + grade2 + grade3)/3;
return average;
}
}
You mix scanner.nextInt() and scanner.nextLine().
When you call scanner.nextInt() and then you call scanner.nextLine(), scanner.nextLine() returns the remain of the current line of the input entered by scanner.nextInt(), that is an empty String. And that before you may enter anything.
That's why you loop to the original set of choices.
You should avoid to chainnext() and nextLine(). Try to use only the one or the other one.
Besides, the code in the else if(choice == 7) block compares String values with == and besides this comparison is even not required since you perform a loop on the map of students to retrieve the student while you have a Map that may retrieve the information in a straight way :
Set<String> keySet = map.keySet();
System.out.println("");
System.out.println("Please enter a student's name: ");
String studentName = userInput.next();
for (String currentKey : keySet) {
Student student = map.get(currentKey);
if(studentName == currentKey){
System.out.println(currentKey + "'s quiz scores:");
int [] quizArray = student.getQuizGrades();
for(int counter1 = 0; counter1 < quizArray.length; counter1++ ){
System.out.println(quizArray[counter1]);
}
}
}
You could do simply :
System.out.println("");
System.out.println("Please enter a student's name: ");
String studentName = userInput.next();
Student student = map.get(studentName);
if (student!=null){
System.out.println(studentName + "'s quiz scores:");
int[] quizArray = student.getQuizGrades();
for (int counter1 = 0; counter1 < quizArray.length; counter1++) {
System.out.println(quizArray[counter1]);
}
}
Instead of if (studentName == currentKey) use if (studentName.equals(currentKey). You should always compare strings with equals(...), because == only checks the equality of references, not the objects itself. As studentName and current key are two independent instances, they are never equal in a comaprison with == as their references differ.
You should try to refactor your code, as there are multiple issues. As #markspace already pointed out, your loop is unnecessary and the critical if statement is not needed at all.
for (String currentKey : keySet) {
Student student = map.get(currentKey);
if(studentName == currentKey){
//...
}
}
This can be reduced to the following code as you deal with a map. That is the point of a map, not having to iterate through all elements, but to use a key to directly access an element.
Student student = map.get(currentKey);
if (student != null) {
// ...
}
Also, you should call nextLine(); after int choice = userInput.nextInt(); (and other next...(...); calls), because they do not consume the newline character. Otherwise studentName = userInput.nextLine(); will only contain the newline character leftover from last call to nextInt()...;.
Main.java
import java.util.*;
public class Main{
static Student[] students = new Student[10];//creates an array of 10 students to be entered
public static int inputThreshold(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Threshold: \n");
int threshold = scan.nextInt();
return Threshold();
}
public static Student inputStudent(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter students surname: \n");//instructs the user to enter a surname
String name = scan.nextLine();//allows the user to input sdtudents surname
System.out.println("Enter student score between 0 and 30: \n");
int score = scan.nextInt();//allows the user to input students score
return new Student(name, score);
}
public static void printStudent(Student student){
int percentage = student.getScore()*10/3;//retrieves the percentage of the score submitted out of 30
System.out.println("Surname: " + student.getName() + " Score: " + student.getScore() + " Percentage: " + percentage + "%");
//prints out the surname, score and percentage achieved by the student
}
public static void printThreshold(int threshold){
int percentage = student.getScore()*10/3;//retrieves the percentage of the score submitted out of 30
if (percentage < threshold){
System.out.println("Surname: " + student.getName() + " Score: " + student.getScore() + " Percentage: " + percentage + "%");
//prints out the surname, score and percentage achieved by the student
}
}
public static Student getWinner(Student[] student){
Student x = student[0];
for(int i = 1; i < 10; i++){
if(student[i].getScore() > x.getScore()){
x = student[i];
}
}
return x;
}
public static void main(String[] args){
for (int i = 0; i = 1; i++){
threshold = inputThreshold;
}
for (int i = 0; i < 10; i++){
students[i] = inputStudent();
}
for(int i = 0; i < 10; i++){
printStudent(students[i]);
}
for(int i= 0; i < 1; i++){
printThreshold(students[i]);
}
Student winrar = getWinner(students);//retrieves the winner from getWinner into a variable
System.out.println("AND WE HAVE OUR WINNER! \n" + "Name: " + winrar.getName() + " Score: " + winrar.getScore());
//prints out the highest scoring students surname, with their score
}
}
Student.java
public class Student{
private String name;//sets name to characters
private int score;//sets score to numbers
private int threshold;//sets the threshold of the score
private int max = 30;//sets max score to 30
public Student(String name, int score){
this.name = name;
if (score <= max && score >= 0) //if the score is equal to 30 or less than 0
this.score = score;//the score can be stored
else{
System.out.println("This number is too big ");//if it is larger than 30 it cannot be stored and shows errors message
System.exit(1);//this will end the program
}
}
public String getName(){
return name;
}
public int getScore(){
return score;
}
public int getThreshold(){
return threshold;
}
public void setScore(int s){
this.score = s;
}
public void setName(String n){
this.name = n;
}
public void setThreshold(int t){
this.threshold = t;
}
}
Is returns Cannot Find Symbol - method Threshold()
I'm not sure what to refer to or how to call the method to get it to run correctly. Brief: 10 users, 10 scores. There's a threshold to be achieved by each entrant. The program outputs their names, scores achieved and the percentage of their score. But it should also announce the overall winner.
Not sure here
return Threshold();
should be
return threshold;
change Threshold() to threshold.
I strongly advice you to read this article before writing another program
Objects, Instance Methods, and Instance Variables
public static int inputThreshold(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Threshold: \n");
int threshold = scan.nextInt();
return Threshold();
}
public static void main(String[] args){
for (int i = 0; i = 1; i++){
threshold = inputThreshold;
}
...rest of code in main
}
threshold is a local variable defined in inputStudent(), you can't access it in main() .Also return Threshold();, there is no Threshold() method defined in the code you've provided
How can I input a String and an int in the same line? Then I want to proceed it to get the largest number from int that I already input:
Here is the code I have written so far.
import java.util.Scanner;
public class NamaNilaiMaksimum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name[] = new String[6];
int number[] = new int[6];
int max = 0, largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
name[x] = in.nextLine();
number[x] = in.nextInt();
}
for (int x = 1; x <= as; x++) {
if (number[x] > largest) {
largest = number[x];
}
}
System.out.println("Result = " + largest);
}
}
There's an error when I input the others name and number.
I expect the output will be like this
Name & Number : John 45
Name & Number : Paul 30
Name & Number : Andy 25
Result: John 45
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String InputValue;
String name[] = new String[6];
int number[] = new int[6];
String LargeName = "";
int largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
InputValue = in.nextLine();
String[] Value = InputValue.split(" ");
name[x] = Value[0];
number[x] = Integer.parseInt(Value[1]);
}
for (int x = 1; x < number.length; x++) {
if (number[x] > largest) {
largest = number[x];
LargeName = name[x];
}
}
System.out.println("Result = " + LargeName + " " + largest);
}
Hope this works for you.
System.out.print(" Name & number : ");
/*
Get the input value "name and age" separated with space " " and splite it.
1st part is name and second part is the age as tring format!
*/
String[] Value = in.nextLine().split(" ");
name[x] = Value[0];
// Convert age with string format to int.
number[x] = Integer.parseInt(Value[1]);
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();