Index match max/min scores (Java) - java

I am working through a coding assignment and am close to completion save for my final print statement which needs to match names w/ scores for max and min.
I have been able to get appropriate values in two sentences using two if statements, but I am a bit stumped on how to get my indexing correct to align names to scores w/ max and min.
I am not able to use classes or additional / different methods other than arrays and indexing.
//Create method StudentMax
private static int StudentMax(int[] Scores) {
int ScoreMax = Scores[0];
for (int i = 0; i < Scores.length; i++){
if (Scores[i] > ScoreMax){
ScoreMax = Scores[i];
}
}
return ScoreMax;
}
//Create method StudentMin
private static int StudentMin(int[] Scores) {
int ScoreMin = Scores[0];
for (int i = 0; i < Scores.length; i++){
if (Scores[i] < ScoreMin) {
ScoreMin = Scores[i];
}
}
return ScoreMin;
}
public static void main(String[] args) {
//Call Scanner
Scanner scan = new Scanner(System.in);
//User Welcome
System.out.println("Welcome to the student score sorter.");
System.out.println("\nThis program will accept a number of student names and score values, then find the highest and lowest score.");
System.out.println("\nThen will return the names and max/min scores.");
//User Prompt Enter number of students
System.out.println("\nHow many students would you like to enter: ");
int StudentCount = scan.nextInt();
//Create arrays: Scores, StudentFirst, StudentLast
int [] Scores = new int[StudentCount];
String [] StudentFirst = new String [StudentCount];
String [] StudentLast = new String [StudentCount];
for (int i = 0; i < Scores.length; i++) {
System.out.println("\nStudent " + (i+1)+":");
System.out.println("\nEnter Student's name:");
StudentFirst[i] = scan.next();
StudentLast[i] = scan.next();
System.out.println("\nEnter Student's score (0-100):");
Scores[i] = scan.nextInt();
}
int max = StudentMax(Scores);
int min = StudentMin(Scores);
for (int i = 0; i < Scores.length; i++) {
System.out.println("\n"+StudentFirst[i] + " " + StudentLast[i] +": " + Scores[i]);
}
for (int i = 0; i < Scores.length; i++) {
if (Scores [i] == max) {
System.out.println("\n"+ StudentFirst[i] +" "+ StudentLast[i] + " has the highest score => " +max+ " and " + StudentFirst[i]+" " + StudentLast[i]+ " has the lowest => " +min);
}
}
//This is the sentence format that I need to make work, but I am struggling to understand how to align the index for names and scores.
//System.out.println("\n"+StudentFirst[i] +" "+ StudentLast[i]+ " has the highest score => " +max+ " and " +StudentFirst[i] +" "+ StudentLast [i]+ " has the lowest score => " +min);
//Scan Close
scan.close();
//Close Program
}
}

Pass back the index not the value
private static int StudentMin(int[] Scores) {
int ScoreMin = Scores[0];
int index = 0;
for (int i = 0; i < Scores.length; i++){
if (Scores[i] < ScoreMin) {
ScoreMin = Scores[i];
index = i;
}
}
return index;
}
Then you can use it later
int index = StudentMax(Scores);
System.out.println("\n"+ StudentFirst[index] +" "+ StudentLast[index] + " has the highest score => " +Scored[index]);
Note Please pay attention to Java naming conventions

Related

Input to array stopped by "quit " word

I need to do Football Results Generator. I created 4 arrays with 10 elements each, but I need to include a loop that allows the user to change their mind and stop input by typing "quit" after a certain number of entries. Could you please help - I am new to programming, so it must be dead simple.
import java.util.Scanner;//
public class Football_Results_Generator
{
public static void main(String[] args)
{
Scanner kbd = new Scanner (System.in);
String[] HomeTeam = new String[10];
String[] AwayTeam = new String[10];
int[] HomeScore = new int[10];
int[] AwayScore = new int[10];
int index = 0;
int sum = 0;
int sum1 = 0;
do
{
System.out.print("Enter Home Team Name: ");
HomeTeam[index] = kbd.nextLine();
System.out.print("Enter Away Team Name: ");
AwayTeam[index] = kbd.nextLine();
System.out.print("Enter Home Team Score:");
HomeScore[index] = kbd.nextInt();
System.out.print("Enter Away Team Score: ");
AwayScore[index] = kbd.nextInt();
kbd.nextLine();
} while(index < 10);
index = 0;
System.out.println();
do
{
System.out.println(HomeTeam[index] + " [" + HomeScore[index] + "]" + " | " + AwayTeam[index] + " [" + AwayScore[index] + "] ");
index = index + 1;
} while(index < 10);
kbd.close();
for(index = 0; index < 10; index++)
sum += HomeScore[index];
for(index = 0; index < 10; index++)
sum1 += AwayScore[index];
System.out.println();
System.out.println("Totals");
System.out.println("-------------------------------");
System.out.println("Total number of matches played: " + index);
System.out.println("Total of all home scores: " + sum);
System.out.println("Total of all away scores: " + sum1);
System.out.println("Total number of draws: ");
System.out.println("The highest home score: ");
System.out.println("The highest away score: ");
}
}
allow user to change his mind and stop input by typing quit after 5 tries.
Use a temp variable to capture String input:
String line;
do
{
System.out.print("Enter Home Team Name: ");
line = kbd.nextLine();
if("quit".equalsIgnoreCase(line)){
break;
}
HomeTeam[index] = line;
.....
index = index + 1; //missed
}while(index < 10);
index = 0;
Here, "quit".equalsIgnoreCase(line) will ensure that irrespctive of case of line e.g. "Quit","QUIT","quit",etc will result true
What about integer input to array?? is it same concept ??
Well, you need to handle the exception in case input is neither quit nor int:
line = kbd.nextLine();
if("quit".equalsIgnoreCase(line)){
break;
}
try{
HomeScore[index] = new Integer(line);
} catch(NumberFormatException e){
//Error conversion string to int
}

Does java have "get line"?

I am new to CS and I am doing this online java class which is a joke tbh. I say that because the books we got are $15 books, custom made that were used for a summer camp that was "taught" to kids. There is no where in the book that has actual java information, it is just a bunch of programs. I did a bit of searching around and I can't seem to find what I am looking for.
One thing we have to do is modify the program so it can display first and last name. I have looked and seen that you can do two strings to get first and last name. Is there something that will get the entire line in java?
package computegrades;
import java.util.Scanner;
public class ComputeGrades {
public static void main (String[] args) {
String[] names = getNames();
int[] scores = getScores(names);
double average = computeAverage(scores);
int highestIndex = getHighest(scores);
int lowestIndex = getLowest(scores);
System.out.format("Average = %3.2f\n", average);
System.out.println("Highest = " + names[highestIndex] + ": " + scores [highestIndex]);
System.out.println("Lowest = " + names[lowestIndex] + ": " + scores [lowestIndex]);
printLetterGrades(names, scores);
}
public static void printLetterGrades(String[] names, int[] scores) {
for (int i = 0; i < names.length; i++) {
if (scores[i] >= 90) {
System.out.println(names[i] + ": A");
} else if (scores[i] >= 80) {
System.out.println(names[i] + ": B");
} else if (scores[i] >= 70) {
System.out.println(names[i] + ": C");
} else if (scores[i] >= 60) {
System.out.println(names[i] + ": D");
} else {
System.out.println(names[i] + ": F");
}
}
}
public static String[] getNames() {
Scanner input = new Scanner(System.in);
System.out.println("How many students?");
int n = input.nextInt();
System.out.println("Please enter their first names:");
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.print("name " + (i + 1) + ": ");
names[i] = input.next();
}
System.out.println("Thank you.");
return names;
}
public static int[] getScores(String[] names) {
System.out.println("Now, please enter their scores:");
Scanner input = new Scanner(System.in);
int[] scores = new int[names.length];
for (int i = 0; i < names.length; i++) {
System.out.print(names[i] + "'s ");
System.out.print("score: ");
while(!input.hasNextInt()){
input.next();
System.out.println("Please enter an integer for the score");
System.out.print("scores: ");
}
scores[i] = input.nextInt();
}
return scores;
}
public static double computeAverage(int[] scores) {
double sum = 0;
for (int i = 0; i < scores.length; i++) {
sum += scores[i];
}
return sum / scores.length;
}
public static int getHighest(int[] scores) {
int highestIndex = Integer.MIN_VALUE;
int highestScore = Integer.MIN_VALUE;
for (int i = 0; i < scores.length; i++) {
if (scores[i] > highestScore) {
highestScore = scores[i];
highestIndex = i;
}
}
return highestIndex;
}
public static int getLowest(int[] scores) {
int lowestIndex = Integer.MAX_VALUE;
int lowestScore = Integer.MAX_VALUE;
for (int i = 0; i < scores.length; i++) {
if (scores[i] < lowestScore) {
lowestScore = scores[i];
lowestIndex = i;
}
}
return lowestIndex;
}
}
Being new to Java, one of the resources you need to have on hand is the Oracle documentation pages, for example:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
That will guide you on what a Scanner can do.
Specifically, you should look for
.nextLine()

Combine two arrays of different data type

import java.util.Scanner;
public class scores
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("\f");
int classSize, counterScore, counterName;
String name;
double score,average, sum;
System.out.print("Enter size of class: ");
classSize = input.nextInt();
int[] scoreArray = new int[classSize];
String[] nameArray = new String[classSize];
counterScore=1;
counterName = 1;
average = 0;
sum = 0;
for (int x = 0; x < classSize; x++)
{
input.nextLine();
System.out.print("Student " + counterName++ + " Name: ");
nameArray[x] = input.nextLine();
System.out.print("Student " + counterScore++ + " Score: ");
scoreArray[x] = input.nextInt();
sum = sum + scoreArray[x];
average = sum / classSize;
}
System.out.println(average);
}
}
I have to make an app that allows me to say how many people took a test and then enter their names and scores. I have used two different arrays as one is a string and one a double. My output is meant to read which names got under the average and display the name. I do not know how to combine the two arrays so that it recognizes that this score is related to this name so display that name.
I think your best option is to create a POJO with two fields (name and score) and create an array of it:
public class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
You can simply iterate through the two arrays together in a single iteration and populate an array of the custom type containing a String and double. (i.e. a Student class)
public class Student {
public String name;
public double score;
public Student(String name, double score) {
this.name = name;
this.score = score;
}
}
List<Student> students = new ArrayList<Student>();
for (int x = 0; x < classSize; x++)
{
input.nextLine();
System.out.print("Student " + counterName++ + " Name: ");
nameArray[x] = input.nextLine();
System.out.print("Student " + counterScore++ + " Score: ");
scoreArray[x] = input.nextInt();
sum = sum + scoreArray[x];
average = sum / classSize;
// populate array of student
students.add(new Student(nameArray[x], scoreArray[x]));
}
Note that in this case, you don't need to have the scoreArray and nameArray anymore for better memory utilization.
You can use (add this after your first loop):
for (int i = 0; i < classSize; i++)
{
if(scoreArray[i] < average) {
System.out.println(nameArray[i])
}
}
Or if you want it all on one line:
System.out.println("The following students are below average: ")
boolean first = true;
for (int i = 0; i < classSize; i++)
{
if(scoreArray[i] < average) {
if(!first) {
System.out.println(", ");
first = false;
}
System.out.print(nameArray[i])
}
}
Also, you should move the line average = sum / classSize; outside of your loop, there's no point in re-calculating the average each time.
To find out the highest value, keep a temporary variable for the name and another for the highest value, and loop through the students:
String highestName = "";
double highestValue = 0;
for (int i = 0; i < classSize; i++) {
if(scoreArray[i] > highestValue) {
highestName = nameArray[i];
highestValue = scoreArray[i];
}
}
System.out.println(highestName + " has the highest grade.")
Or use this to print more than one student if there's a tie:
String[] highestNames = new String[classSize];
int numHighest = 0;
double highestValue = 0;
for (int i = 0; i < classSize; i++) {
if(scoreArray[i] > highestValue) {
highestNames[0] = nameArray[i];
numHighest = 1;
highestValue = scoreArray[i];
} else if(scoreArray[i] > highestValue) {
highestNames[numHighest] = nameArray[i];
numHighest = numHighest + 1;
}
}
System.out.println("The following student(s) has/have the highest grade: ")
boolean first2 = true;
for (int i = 0; i < numHighest; i++)
{
if(!first2) {
System.out.println(", ");
first2 = false;
}
System.out.print(highestNames[i])
}
}
You can also combine the content of the loop for printing students with grades below average with the one for finding the highest grades to make your program more efficient:
String[] highestNames = new String[classSize];
int numHighest = 0;
double highestValue = 0;
System.out.println("The following students are below average: ")
boolean first = true;
for (int i = 0; i < classSize; i++)
{
if(scoreArray[i] < average) {
if(!first) {
System.out.println(", ");
first = false;
}
System.out.print(nameArray[i])
}
if(scoreArray[i] > highestValue) {
highestNames[0] = nameArray[i];
numHighest = 1;
highestValue = scoreArray[i];
} else if(scoreArray[i] > highestValue) {
highestNames[numHighest] = nameArray[i];
numHighest = numHighest + 1;
}
}

How can I get this program to print out the numbers the user entered?

Here's my code:
import java.util.*;
public class InputSum
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
while (i != -1)
{
j += i;
i = input.nextInt();
}
System.out.println("Entered Number: " + i);
System.out.println("The Sum: " + j);
}
}
As of now my output is:
Entered Number: -1
The Sum: (Sum of the numbers entered)
Print them inside the loop :
while (i != -1)
{
System.out.println("Entered Number: " + i);
j += i;
i = input.nextInt();
}
System.out.println("The Sum: " + j);
Or it you want to print them in a single line :
List numbers = new ArrayList<Integer>();
while (i != -1)
{
numbers.add(i);
j += i;
i = input.nextInt();
}
System.out.println("Entered Numbers: " + numbers);
System.out.println("\nThe Sum: " + j);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out
.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
while (i != -1) {
numbers.add(i);
j += i;
i = input.nextInt();
}
System.out.println("Entered Numbers: ");
for (int a = 0; a < numbers.size(); a++) {
System.out.print(" " + numbers.get(a));
}
System.out.println("The Sum: " + j);
}
This should work to print the numbers. You can use an arraylist to store the numbers and then if you need them for later calculations they are still stored in the arraylist.
package net.rajkannan.stackoverflow;
import java.util.*;
public class InputSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out
.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
String numbers = "";
while (i != -1) {
j += i;
numbers = numbers + i + " ";
i = input.nextInt();
}
System.out.println("Entered Numbers: " + numbers);
System.out.println("The Sum: " + j);
}
}

sorting, average and finding the lowest number from a static array Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
i'm trying to input students and input their results for course work and exams and what i'm having trouble with is finding the average total score, the lowest total score and printing all students in order of total scores highest - lowest
import java.util.*;
import java.text.*;
public class Results
{
static String[] name = new String[100];
static int[] coursework = new int[100];
static int[] exam = new int[100];
static int[] totalScore = new int[100];
static String[] totalGrade = new String[100];
static String[]examGrade = new String[100];
static int count = 0;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean flag = true;
while(flag)
{
System.out.println(
"1. Add Student\n" +
"2. List All Students\n" +
"3. List Student Grades\n" +
"4. Total Score Average\n" +
"5. Highest Total Score\n" +
"6. Lowest Total Score\n" +
"7. List all Students and Total Scores\n" +
"8. Quit\n");
System.out.print("Enter choice (1 - 8): ");
int choice = input.nextInt();
switch(choice)
{
case 1:
add();
break;
case 2:
listAll();
break;
case 3:
listGrades();
break;
case 4:
average();
break;
case 5:
highestTotal();
break;
case 6:
lowestTotal();
break;
case 7:
order();
break;
case 8:
flag = false;
break;
default:
System.out.println("\nNot an option\n");
}
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
}
System.out.println("\n\nHave a nice day");
}//end of main
static void add()
{
Scanner input = new Scanner(System.in);
System.out.println("Insert Name: ");
String names = input.nextLine();
System.out.println("Insert Coursework: ");
int courseworks = input.nextInt();
System.out.println("Insert Exam: ");
int exams = input.nextInt();
int totalscores = exams + courseworks;
name[count] = names;
coursework[count] = courseworks;
exam[count] = exams;
totalScore[count] = totalscores;
count++;
}
static void listAll()
{
for(int i=0;i<count;i++)
{
System.out.printf("%s %d %d\n", name[i], coursework[i], exam[i]);
}
}
static void listGrades()
{
for(int i=0;i<count;i++){
if(coursework[i] + exam[i] > 79)
{
System.out.println(name[i] + " HD");
}
else if(coursework[i] + exam[i] > 69)
{
System.out.println(name[i] + " DI");
}
else if(coursework[i] + exam[i] > 59)
{
System.out.println(name[i] + " CR");
}
else if(coursework[i] + exam[i] > 49)
{
System.out.println(name[i] + " PA");
}
else
{
System.out.println(name[i] + " NN");
}
}
}
static void average()
{
double sum = 0;
for(int i=0; i < count; i++)
{
sum += exam[i] + coursework[i];
}
sum = sum / count;
System.out.printf("Average Total Score : %.1f\n ", sum);
}
static void highestTotal()
{
int largest = totalScore[0];
String student = name[0];
for (int i = 0; i < exam.length; i++) {
if (totalScore[i] > largest) {
largest = totalScore[i];
student = name[i];
}
}
System.out.printf(student + ": " + largest + "\n");
}
static void lowestTotal()
{
int lowest = totalScore[0];
String student = name[0];
for (int i = 0; i > exam.length; i++) {
if (totalScore[i] < lowest) {
lowest = totalScore[i];
student = name[i];
}
}
System.out.printf(student + ": " + lowest + "\n");
}
static void order()
{
for (int i=0;i<count;i++)
{
Arrays.sort(totalScore);
System.out.printf(name[i] + "\t" + totalScore[count] + "\n");
}
}
}
static void average(){
int total = 0;
for(int i = 0; i < array.length; i++)
{
total += array[i];
}
int average = total / array.length
}
Above code you can get the Average. You did the kind of similar thing to find largest value.
to sort array just use that will solve your problem.
Arrays.sort(array);
For sorting, you can use Arrays.sort(array) (With a comparator if you need special ordering)
Once it's sorted, getting the lowest score should be easy. To get an average, add up each value and divide by the number of elements. To add them all up, use a for loop or for-each loop:
int sum = 0;
for(int i = 0; i < array.length; i++)
{
sum += array[i];
}
int average = sum / array.length
You may want to use a double instead of an int for sum.
For Average Total Score simply add the coursework and exam scores in avariable such as sum and divide by no. of students:
static void average() {
int sum = 0;
for(int i=0; i < count; i++)
{
sum += exam[i] + coursework[i];
}
sum = sum / count;
System.out.printf("Average Total Score = : " + sum + "\n");
}
For both lowest total score and largest total score your implementation of highest total is almost right. The problem is that you are not considering the coursework[i] in your largest variable. And on similar lines you can implement lowest total score
static void highestTotal() {
int largest = exam[0] + coursework[0];
String student = name[0];
for (int i = 0; i < exam.length; i++) {
if (exam[i]+coursework[i] > largest) {
largest = exam[i] + coursework[i];
student = name[i];
}
}
System.out.printf(student + ": " + largest + "\n");
}
For printing the scores in order i would suggest that you define another int array which has the sum of exam score and coursework score, sort it using any basic sorting technique and print the array. Remember while exchanging the sum during sorting also exchange the corresponding name..

Categories