Java Scanner input into int and string arrays - java

If someone would be kind enough to give me a hand with this program it would be appreciated, it accepts multiple students names and grades using a Scanner and then puts them into 2 arrays, Students and Scores. Then it will print out like the following...
Max. Grade = 98 (Lauren)
Min. Grade = 50 (Joe)
Avg. Grade = 83.9
/* Chris Brocato
* 10-27-15
* This program will read the students names and scores using a Scanner and use two arrays to
* show the grade and name of the highest and lowest scoring student as well as the average grade.*/
import java.util.*;
public class StudentCenter {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter the number of students: ");
int students = console.nextInt();
String[] name = new String[students];
int[] scores = new int[students];
int min = 0; int max = 0; int sum = 0;
for (int i = 0; i < name.length; i++) {
System.out.print("Please enter student's name: ");
name[i] = console.next();
System.out.print("Now enter their score: ");
scores[i] = console.nextInt();
if (i == 0) {
min = students;
max = students;
}else {
if (students < min) min = students;
if (students > max) max = students;
}sum += students;
}
System.out.println("Min. Grade = " + min + name );
System.out.println("Max. Grade = " + max + name);
System.out.println("Average Grade = " + sum);
double avg = (double) sum / (double) students;
System.out.println("Avg = " + avg);
console.close();
}
}

You're setting min,max, and sum to the value of students, which is the number of students—not their scores. You should probably be setting them to scores[i].
if (i == 0) {
min = scores[i];
max = scores[i];
}else {
if (students < min) min = scores[i];
if (students > max) max = scores[i];
}
sum += scores[i];
I would also store the indices for minimum and maximum scores, so that you can reference their names later.
min = scores[i];
minIndex = i;
...
System.out.println("Min. Grade = " + min + name[minIndex] );

I would use the Min and Max values for constants.
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int maxValue = 0;
int minValue = 0;
String minName;
String maxName;
//then use them for comparison in the loop
if(scores[i] < min)
{
minValue = scores[i];
minName = name[i];
}
if(scores[i] > max)
{
maxValue = scores[i];
maxName = name[i];
}
That will store your max/min values with the associated name.

You are comparing min and max with incorrect values. students is the number of students you have not the grades. Also when printing tha names you are printing the whole array and not just a specific value. So my advice is that you create two variables like this:
int minInd = 0;
int maxInd = 0;
then change your if like this:
if (i == 0) {
min = scores[i];
max = scores[i];
} else {
if (scores[i] < min) {
min = scores[i];
minInd = i;
}
if (scores[i] > max) {
max = scores[i];
maxInd = i;
}
}
sum += scores[i];
And print the result like this:
System.out.println("Min. Grade = " + min + " ("+ name[minInd]+")");
System.out.println("Max. Grade = " + max + " ("+name[maxInd]+")");

Related

How to understand why this does not return the minimum value?

Please help to understand why, in the following, I didn't get output of minimum value in array. Using scanner for input value, the program should output also the minimum number.
** without using .sort.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list;
list = new int[10000];
int sum = 0;
double avr = 0;
int min = list [0];
int max = list [0];
int x = 0;
int value;
Scanner input = new Scanner(System.in);
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
while (x <= list.length && (value != -1 || x == 0)) {
list[x] = value;
x++;
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
}
for (int i = 0; i < list.length; i++) {
sum += list[i];
avr = sum / x;
if(list[i] > max)
max = list[i];
if( list[i] < min )
min = list[i];
}
System.out.println("The sum of all values are: " + sum);
System.out.println("The average value of the numbers are: " + avr);
System.out.println("The maximum value of the numbers are: " + max);
System.out.println("The minimum value of the numbers are: " + min);
}
}
I will suggest two improvements at the bare minimum.
Initialize your min to the first value. Right now you have min initialized to 0 and user never enters any number smaller than 0. That's why you keep getting 0 for min.
Don't run your loops 1000 times. Run it as many times as there are non zero elements.
See the following working snippet:
int[] list;
list = new int[10000];
int sum = 0;
double avr = 0;
int min = list [0];
int max = list [0];
int x = 0;
int value;
Scanner input = new Scanner(System.in);
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
min = value;
while (x <= list.length && (value != -1 || x == 0)) {
list[x] = value;
x++;
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
}
for (int i = 0; i < list.length && list[i] !=0; i++) {
sum += list[i];
avr = sum / x;
if(list[i] > max)
max = list[i];
if( list[i] < min )
min = list[i];
}
System.out.println("The sum of all values are: " + sum);
System.out.println("The average value of the numbers are: " + avr);
System.out.println("The maximum value of the numbers are: " + max);
System.out.println("The minimum value of the numbers are: " + min);

for loop to calculate students' average mark. my average keeps on adding up

I had this assignment which I need to use Java to create a for-loop to calculate the average of each students' score. The teacher must enter number of test score per student and the loop will then iterate for each student.
import java.util.Scanner;
public class average {
public static void main(String[] args) {
int count = 0;
int student;
int sum = 0;
int grade;
int average = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of students:");
student = keyboard.nextInt();
System.out.println("Enter number of test scores per student: ");
count = keyboard.nextInt();
for (int s = 0; s < student; s++) {
System.out.println("Student number " + (s + 1) );
for (int i = 0; i < count; i++) {
System.out.println("Enter score no." + (i + 1) + " : ");
grade = keyboard.nextInt();
sum += grade;
average = sum/count;
}
System.out.println("The average is " + average);
}
}
}
Make sum = 0 after printing average
Just shown in below loop
for (int s = 0; s < student; s++) {
System.out.println("Student number " + (s + 1));
for (int i = 0; i < count; i++) {
System.out.println("Enter score no." + (i + 1) + " : ");
grade = keyboard.nextInt();
sum += grade;
average = sum / count;
}
System.out.println("The average is " + average);
sum = 0; //THIS IS REQUIRED
}

min max in array issue

So I have a program I wrote that finds the max and min value of a five number set. It works for the most part but when I enter a set of numbers like {5,6,7,8,9} then it outputs 9 as the max, but outputs 0 for the min. Any thoughts or suggestions.
import java.util.Scanner;
public class MinMax {
public static void main (String [] args) {
#SuppressWarnings("resource")
Scanner in = new Scanner (System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
int i = 0;
double max = 0.0;
double min = 0.0;
System.out.println("Enter five numbers.");
System.out.println();
while (i < NUM_ELEMENTS) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
i++;
System.out.println();
}
for (i = 0; i < userVals.length; i++) {
if (userVals[i] > max) {
max = userVals[i];
}
else if (userVals[i] < min) {
min = userVals[i];
}
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
}
}
Default your min to a number out of range (like Double.MAX_VALUE), and max to Double.MIN_VALUE. You might also simplify your code by removing the second loop; you can perform the logic in one loop and you might use Math.max(double, double) and Math.min(double, double). Something like,
Scanner in = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
System.out.println("Enter five numbers.");
System.out.println();
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < NUM_ELEMENTS; i++) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
min = Math.min(min, userVals[i]);
max = Math.max(max, userVals[i]);
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
Intialize your min variable to non-zero max value. Means max value that you can have in your input from console.

Find largest and smallest numbers number using Arrays

Trying to let users enter number of integers so I can set array length then find the max and min value. However, I can't find max and min. Please help.
import java.util.Scanner;
import java.util.Arrays;
public class ExerciseC{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of integers you would like to enter:");
int numberEnter = keyboard.nextInt();
System.out.println("Enter some integers:");
int integers = keyboard.nextInt();
int numbers [] = new int [numberEnter];
int maxValue = numbers[0];
int minValue = numbers[0];
int max = 0;
int min = 0;
for (int index = 1; index < numbers.length; index ++) {
if (numbers[index] > maxValue) {
maxValue = numbers [index];
}
}
System.out.println("Print: " + maxValue);
System.out.println("The difference between the largest and the smallest is: ");
}
}
You don't seem to be entering more then one value (and you never store integers in your array). Also, you aren't setting the min. I think you wanted
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number of integers to enter:");
int numberEnter = keyboard.nextInt();
int numbers[] = new int[numberEnter];
int pos = 0;
do {
System.out.printf("Please enter integer #%d/%d:%n", pos, numberEnter);
numbers[pos++] = keyboard.nextInt();
} while (pos < numberEnter && keyboard.hasNextInt());
int min = numbers[0];
int max = numbers[0];
for (pos = 1; pos < numbers.length; pos++) {
if (numbers[pos] < min) { // <-- test min.
min = numbers[pos];
}
if (numbers[pos] > max) { // <-- test max.
max = numbers[pos];
}
}
// Display everything.
System.out.printf("%s Min: %d Max: %d%n", Arrays.toString(numbers),
min, max);
}
Your numbers[] is empty. The user's input is not stored into the array.
Here is your fixed code:
package com.company;
import java.util.Scanner;
public class ExerciseC{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of integers you would like to enter:");
int numberEnter = keyboard.nextInt();
int numbers [] = new int [numberEnter];
for (int i = 0; i < numberEnter; i++) {
System.out.println("Enter integer:");
numbers[i] = keyboard.nextInt();
}
int maxValue = numbers[0];
int minValue = numbers[0];
for (int index = 1; index < numbers.length; index ++) {
if (numbers[index] > maxValue) {
maxValue = numbers [index];
}
}
System.out.println("Print: " + maxValue);
System.out.println("The difference between the largest and the smallest is: ");
}
}
import java.util.Scanner;
class StdR {
public static void main(String[] args) {
// TODO Auto-generated method stub
StdR st = new StdR();
st.stdR();
//System.out.println(st.stdR();
}
void stdR()
{
char[] grade = {'A','B','C','D','E','F'};
Scanner input = new Scanner(System.in);
byte[] st = new byte[3];
double[] percentage = new double[st.length];
for(byte s = 0; s < st.length; s++){
System.out.println("\nStudent " + s);
short noOfMarks = 0;
short totalMarks = 450;
percentage[s] = 0.0;
byte[] marks = new byte[5];
for (byte i = 0; i < marks.length; i++){
System.out.println("Enter marks of Chapter "+ i + ": ");
marks[i] = input.nextByte();
noOfMarks += marks[i];
percentage[s] += (marks[i] * 100) / totalMarks;
}
System.out.print("No of marks: " + noOfMarks + "\t");
System.out.print("Percentage: " + percentage[s] + "\t");
if (percentage[s] > 79.0 && percentage[s] < 100.1)
System.out.print("Grade: " + grade[0]);
else if (percentage[s] > 69.0 && percentage[s] < 80.0)
System.out.print("Grade: " + grade[1]);
else if (percentage[s] > 59.0 && percentage[s] < 70.0)
System.out.print("Grade: " + grade[2]);
else if (percentage[s] > 49.0 && percentage[s] < 60.0)
System.out.print("Grade: " + grade[3]);
else if (percentage[s] > 39.0 && percentage[s] < 50.0)
System.out.print("Grade: " + grade[4]);
else if (percentage[s] < 40.0)
System.out.print("Grade: " + grade[5]);
}
double smallest = percentage[0] , largest= percentage[0];
for (int i=0 ;i< percentage.length; i++) {
if (percentage[i] < smallest) {
smallest = percentage[i];
} // end finding smallest
if (percentage[i] > largest) {
largest = percentage[i];
}
}
System.out.println("\n1st Position and Top percentage is " + largest);
System.out.println("\nLast Position and Least percentage is "+smallest);
}
}

How to return person with max sales in salesperson program- JAVA

Kind of confused by one part of my HW problem. It seems like it would be easy, but I can't put my finger on it. I am trying to return the salesperson with the max and min sales. I am confused on how to do that. Help would be much appreciated.
import java.util.Scanner;
public class Cray {
public static void main(String[] args){
final int SALESPEOPLE = 5;
int[] sales = new int[SALESPEOPLE];
int sum, maxperson, minperson;
int max = sales[0];
int min = sales[0];
Scanner scan = new Scanner(System.in);
//Fill the 5 element array of sales with the user's input
for (int i=0; i<sales.length; i++)
{
System.out.print("Enter sales for salesperson " + i + ": ");
sales[i] = scan.nextInt();
//Calculate the max and min sales
//How do I return the salesperson i with the the max and min sales?
if(sales[i] > max){
max= sales[i];
}
if(sales[i] < min){
min = sales [i];
}
}
System.out.println("\nSalesperson Sales");
System.out.println("--------------------");
sum = 0;
for (int i=0; i<sales.length; i++)
{
System.out.println(" " + i + " " + sales[i]);
sum += sales[i];
}
System.out.println("\nTotal sales: " + sum);
System.out.println("Average sales: " + sum/5);
//WHere I want to print the max salesperson.
System.out.println("Salesperson" + );
}
}
you can store the index count
declare and initialize two int variables before you start scanning the input:
int maxindex=Integer.MIN_VALUE,minindex=Integer.MIN_VALUE;
And then assign your array index to them like this:
if(sales[i] > max){
max= sales[i];
maxindex = i;
}
if(sales[i] < min){
min = sales [i];
minindex = i;
}
Now you can directly get the salesperson with max and min sale
System.out.println("Max sales person "+sales[maxindex]);
System.out.println("Min sales person "+sales[minindex]);
I used a very simple trick here by storing the array indexes.
This is very basic approach though there may be more optimized approach for it.
You can adjust your check for maximum
if(sales[i] > max){
max = sales[i];
maxPerson = i;
}
Define two more variables as:
int maxSalePersonIndex = 0;
int minSalePersonIndex = 0;
Update your if as:
if(sales[i] > max){
max= sales[i];
maxSalePersonIndex = i;
}
if(sales[i] < min){
min = sales [i];
minSalePersonIndex = i;
}
In the end, just print the values of maxSalePersonIndex and minSalePersonIndex
System.out.println("Salesperson index with max sale = " + maxSalePersonIndex);
System.out.println("Salesperson index with min sale = " + minSalePersonIndex);
Currently in your for-loop, you're storing the maximum and minimum sales, not the salespeople who attained those sales. Therefore, you should be storing i in max / min, as opposed to sales[i].
int max = 0, int min = 0
...
// in the for-loop
if(sales[i] > sales[max]){
max = i; // i.e. salesperson "i"
}
if(sales[i] < sales[min]){
min = i;
}
...
System.out.println("Max salesperson: " + max);
System.out.println("Min salesperson: " + min);

Categories