Using Java Arrays to get min & max - java

thank you for your help.
Here is the assignment:
Computer Technology Instructor has a small class of 10 students. The instructor evaluates the performance of students in the class by administering 2 midterm tests and a Final Exam.
Write a program that prompts the instructor to enter the 10 grades of midterm 1 and store these numbers in an array. Next prompt for the 10 grades of midterm 2 and store these numbers in a different array. Next prompt for the 10 grades of the Final Exam and store these in a different array. Next add midterm1 to midterm2 to Final and store the totals in a different array. Next, scan the array that has the totals and identify the minimum grade and maximum grade. Inform the instructor of the minimum grade and maximum grade.
The two bold phrases are where I am having problems. Everything works except for the minimum grade and maximum grade. Here is what it tells me, after I've only entered numbers between 65 and 100:
The highest test score is: 276 The lowest test score is: 249
Here is my code:
import java.util.Scanner;
public class Arrays {
public static void main(String[] args) {
// Create a scanner
Scanner input = new Scanner(System.in);
// Prompt for the 1st mid term
int [] midTerm1 = new int[10];
int [] midTerm2 = new int[10];
int [] finalExam = new int[10];
int [] grades = new int[10];
for (int i = 0; i < midTerm1.length; i++){
System.out.println("Enter the 10 Mid Term 1 grades: ");
midTerm1[i] = input.nextInt();
}
// Prompt for the 2nd mid term
for (int i = 0; i < midTerm2.length; i++){
System.out.println("Enter the 10 Mid Term 2 grades: ");
midTerm2[i] = input.nextInt();
}
// Prompt for Final grades
for (int i = 0; i < finalExam.length; i++){
System.out.println("Please enter a Final Exam grade: ");
finalExam[i] = input.nextInt();
}
for (int i = 0; i < grades.length; i++){
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]);
}
int minGrade = grades[0];
int maxGrade = grades[0];
for (int i = 0; i < grades.length; i++)
{
if (minGrade > grades[i])
minGrade = grades[i];
if (maxGrade < grades[i])
maxGrade = grades[i];
}
System.out.print("The highest test score is: " + maxGrade);
System.out.print("The lowest test score is: " + minGrade);
}
}

Edit:
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]);
Your code may in fact be correct. Since you're adding your three test scores together, expect that the grade will be not between 65 and 100 but rather between 195 and 300.
If you want a number between 65 and 100, this needs to be divided by 3:
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]) / 3;
or else find some other way to normalize the grades. For instance, if the final is 50% of the grade then you could have:
grades[i] = (25 * midTerm1[i] + 25 * midTerm2[i] + 50 * finalExam[i]) / 100;
But again your current solution may in fact be the correct one.

Related

How to enter a character to stop a loop

I need to write code that calculates the average of inputs (int) a user has entered. However, the problem is that I also have to allow the user to enter as many inputs as they want and stop when they enter a character(letter).
I can do this problem if there was a given limit I could use, but because the limit could be anything I am having trouble writing a formula that could calculate the average since the number of inputs could be different between any user.
import java.util.Scanner;
public class AvgGrades {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter as many student grades as you like. Enter a character to stop.");
float total=0, avg;
int grades = input.nextInt();
for (int i = 0; i < grades.length; i++) {
grades[i] = input.nextInt();
total = total + grades[i];
}
input.close();
avg = total/grades.length;
System.out.println("Average student grade is "+avg);
}
}
The inputs are:
30.0
45.6
23.8
78.75
90
92
67.5
10.65
88
c
The output should be:
Enter as many student grades as you like. Enter a character to stop.
Average student grade is: 58.477777777777774
My output is that the code just does not run.
Here's a sketch of the process. I'll leave for you the details of turning that into a complete program.
float total = 0;
int count = 0;
while (scanner.hasNextFloat()) {
float num = scanner.nextFloat();
total += num;
count++;
}
float average = total / count;
You don't need to store the individual numbers.

Does anyone have an idea of printing the values in reverse in this code I wrote?

Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should: output the individual digits of 3456 as 3 4 5 6 and the sum as 18, output the individual digits of 8030 as 8 0 3 0 and the sum as 11, output the individual digits of 2345526 as 2 3 4 5 5 2 6 and the sum as 27, and output the individual digits of 4000 as 4 0 0 0 and the sum as 4.
Moreover, the computer always adds the digits in the positive direction even if the user enters a negative number. For example, output the individual digits of -2345 as 2 3 4 5 and the sum as 14.
This is the question I'm having minor difficulties with, the only part I can't figure out is how can I print the single integers in the order that he wants, from what I learned so far I can only print them in reverse. Here's my code:
import java.util.*;
public class assignment2Q1ForLoop {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
int usernum, remainder;
int counter, sum=0, N;
//Asaking the user to enter a limit so we can use a counter controlled loop
System.out.println("Please enter the number of digits of the integer");
N = console.nextInt();
System.out.println("Please enter your "+N+" digit number");
usernum = console.nextInt();
System.out.println("The individual numbers are:");
for(counter=0; counter < N; counter++) {
if(usernum<0)
usernum=-usernum;
remainder = usernum%10 ;
System.out.print(remainder+" ");
sum = sum+remainder ;
usernum = usernum/10;
}
System.out.println();
System.out.println("the sum of the individual digits is:"+sum);
}
}
You have to storeremainder variables in an array and then print them in the loop from last index to first as shown in this tutorial.
You can either store digits in array and then print them, or you can try something like that:
final Scanner console = new Scanner(System.in);
System.out.println("Please enter your number");
final int un = console.nextInt();
long n = un > 0 ? un : -un;
long d = 1;
while (n > d) d *= 10;
long s = 0;
System.out.println("The individual numbers are:");
while (d > 1) {
d /= 10;
final long t = n / d;
s += t;
System.out.print(t + " ");
n %= d;
}
System.out.println();
System.out.println("the sum of the individual digits is:" + s);
An idea would be : convert int to string and write a method
getChar(int index) : String
which gives you for example 4 from 3456 with
getChar(2);
See Java - Convert integer to string
Here, I wrote a code for your problem with using a stack. If you want a simple code, you can comment my solution and I will wrote another one.
Scanner c1 = new Scanner(System.in);
System.out.print("Enter the number: ");
int numb = c1.nextInt();
numb = Math.abs(numb);
Stack<Integer> digits = new Stack<Integer>();
while(numb>0){
int n = numb%10;
digits.push(n);
numb = numb/10;
}
int sum = 0;
while(!digits.isEmpty()){
int n = digits.pop();
sum+=n;
System.out.print(n+" ");
}
System.out.print(sum);

Count numbers in a "for loop" and give back average, min, max value in java

A user should input a number "x", and then the count of "x" numbers, e.g. input = 3, then 3 random numbers like 3, 5, 7.
Afterwards the program should give an output of the average, min and max value of this "x" numbers. So it has to read the numbers, but i don't know how it can be done.
It should be done without arrays and with a for loop.
I didn't find a possible solution here, but maybe I didn't do the right search.
So here is what i got so far:
import java.util.Scanner;
public class Statistic
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
int numbers;
double averageValue;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
number1 = input.nextInt();
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
for (int count = 0; count < number1; count ++) {
System.out.println(numbers); //Just for me to see which numbers are read by the programm
}
averageValue = numbers / number1;
// Output
System.out.println("\n Biggest number: " + Math.max(numbers));
System.out.println("\n Smallest number: " + Math.min(numbers));
System.out.print("\n Average value: " + averageValue);
}
}
But it only prints out and calculates with the first number of the "numbers"-input. Further I am not sure how to use the "Math.max" for a random count of numbers.
The problem is here:
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
numbers = input.nextInt();
nextInt() only saves one int. Every subsequent number you are entering gets lost, of course.
What you need to do is to move this statement inside the for loop for your idea to work.
Also, you can't use min and max here. min and max compare two numbers and return the greater of the two. For your purpose, you'd need to check inside the loop which the greatest and smallest number is and then output it accordingly.
You will need 6 variables: min = 0, max = 0, avg, sum = 0, count, num.
(avg variable is optional)
Program flow will be:
input how many numbers you want to enter -> store in variable count
use some loop to loop count number of times and in each iteration store
users value in variable num.
Increment sum by number user entered. sum += num;
check if entered number is less than current min. If true store min as that number.
Same as min do for max variable.
When loop exit you will have min, max, sum and count variables stored. To calculate avg devide sum with count and there you go. avg = sum / count.
First your code is logically in correct. when u have to take min and max values with average u need to store the inserted elements or process each input(for time complexity this would be the best approach).
Below I have modified your code where i m using enter code hereJava Collections List to store the inputs, sort them and get the data.
After sorting first will me min and last will be max.
Math.min and Math.max only works for comparing 2 numbers not an undefined list.
Again i would say the best solution would be if u check for the number is min or max at input time.
As you are new to java you can try that out your self.
import java.util.*;
public class ZahlenStatistik
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
List<Integer> numbers = new ArrayList<Integer>(); // change it to list
double averageValue;
int sum= 0;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Bitte geben Sie eine Zahl ein: ");
number1 = input.nextInt();
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
//Define the number of times loop goes
for (int count = 0; count < number1; count ++)
{
numbers.add(input.nextInt());
}
for(Integer number:numbers)
{
sum = sum + number;
}
averageValue = sum / number1;
Collections.sort(numbers);
// Output
System.out.println("\n Die größte Zahl ist: " + numbers.get(numbers.size()-1));
System.out.println("\n Die kleinste Zahl ist: " + numbers.get(0));
System.out.print("\n Der averageValue betr\u00e4gt: " + averageValue);
}
}
Some errors that I can see
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
You need here a loop and array to read and store all elements.
To get average value you need first to sum all elements in array and then to divide by length of array.
To find min and max values in array you cannot use Math.min() and Math.max() methods because these methods get two parameters and return min/max value.
Your code should be something like this
Notes
If you cannot use Java 8 you must replace Arrays.stream(numbers).max().getAsInt(); and Arrays.stream(numbers).min().getAsInt(); with helper methods which find max/min values in an array.
If you can use Java 8 you can calculate sum int sum = Arrays.stream(numbers).reduce(0, (x, y) -> x + y); instead in for loop.
.
public class Statistic {
public static void main(String[] args) {
// Variables
Scanner input = new Scanner(System.in);
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
int number1 = input.nextInt();
System.out.println(" Pls enter " + number1 + " numbers: ");
int[] numbers = new int[number1];
for (int i = 0; i < number1; i++) {
System.out.println("Enter next number");
numbers[i] = input.nextInt();
}
// Find min and max values
int max = Arrays.stream(numbers).max().getAsInt();
int min = Arrays.stream(numbers).min().getAsInt();
System.out.println("\n Biggest number: " + max);
System.out.println("\n Smallest number: " + min);
// Get average value
int sum = 0;
for (int num : numbers) {
sum = sum + num;
}
double averageValue = (double) sum / number1;
System.out.print("\n Average value: " + averageValue);
}
}
import java.util.Scanner;
public class SumOf2
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter 2 integer values");
int m = s.nextInt();
int n = s.nextInt();
int sum=0;
int count=0;
for(int i=m ; i<=n ; i++)
{
if(count < n)
{
sum=sum+i;
count++;
}
}
System.out.println("Sum of two numbers is: "+sum);
System.out.println("Count between 2 numbers is : "+count);
}
}

Java averaging calculator with defined number of entries

I've seen several average calculators but none with this specific function.
Basically, I want it to ask "How many numbers would you like to average?" then "Enter your number" and continue to prompt "Enter your number" after each entry until the "How many numbers..." quantity is fulfilled. I know it's a count-loop (sorry if my jargon is off...I'm only in my second semester of computer programming) but I don't know how to set it up. Thanks in advance for your answers. Here's what I have so far:
import java.util.Scanner;
public class TestScoreApp
{
public static void main(String[] args)
{
// welcome the user to the program
System.out.println("Welcome to the Test Average Calculator!");
System.out.println(); // print a blank line
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println(); // print a blank line
// initialize variables and create a Scanner object
int scoreTotal;
int scoreCount;
int testScore;
Scanner sc = new Scanner(System.in);
// perform calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
// get the number of grades to be averaged from the user
System.out.print("How many scores would you like to average? ");
scoreCount = sc.nextInt();
// get the input from the user
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreTotal = scoreTotal + testScore;
}
else if (testScore >= 100)
System.out.println("Invalid entry, not counted");
// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
System.out.print("Would you like to average more grades? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
Your approach is near about right except some mistakes. You want to take input until 'n' is pressed and then the average would be shown. That means the average calculation must be done outside the loop, when taking input ends.
If you want to take input with a predefined number from input instead of 'y'/'n' approach, you can reuse your while loop:
int numOfInput = sc.nextInt(); // how many number will be entered
while(numOfInput > 0) {
// take every input and add to total
--numOfInput;
}
// average calculation
Also, a little logical mistake in input validation check.
if (testScore <= 100) // for less or equal 100
{
scoreTotal = scoreTotal + testScore;
}
else if (testScore >= 100) // for greater or equal 100
System.out.println("Invalid entry, not counted");
Both condition checks whether the number is equal to 100, which is not expected. If you allow only number less than 100, then you could write:
if (testScore < 100) {
scoreTotal += testScore;
}
else {
System.out.println("Invalid entry, not counted");
}
So you want to average scoreCount items, or keep averaging until the user has input "n" ?
If it's the first case (As you've described in your question) and you want to average for scoreCount times, you need to change the condition on your while loop.
System.out.print("How many scores would you like to average? ");
scoreCount = sc.nextInt();
scoreTotal = 0;
for(int i=0; i<scoreCount; i++){
scoreTotal += sc.nextInt();
System.out.print("Okay please enter next...");
}
System.out.print("Average is " + scoreTotal/scoreCount);
If you want to do it with a while, just keep an index, int index=0;, increment the index on each iteration and check if you've exceeded the index.
while (index < scoreCount)
scoreTotal += sc.nextInt();
index++;
System.out.print("Average is " + scoreTotal/scoreCount);
That is what you need:
for( int i = 0; i < scoreCount; i++){
System.out.print("Enter score: ");
testScore = sc.nextInt();
}
The for loop creates integer i to hold its looping index
int i;
And each loop asks is i bigger than scoreCount and if not loop again.
i < scoreCount;
And after each loop it adds one to i.
i++

Individually sum random numbers not in an array?

This is part of a school assignment which I've already turned in, I was graded down in one portion because the total sum of the random numbers was supposed to be adding the individual numbers together, not each line.
So if the lines read:
1 2 3
4 5 6
The total should be 21, not 579 as my program is doing now. I've really been struggling trying to figure this out. I tried generating a different random number object for each integer, for a total of three of them but that completely screwed up my output.
We're learning arrays next week, and after researching online I could do this easily with an array, but the assignment was to be done without arrays. How can I sum each entry individually? Thanks for any help!
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class lottery {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int gameType, gameTimes;
int randomNums, lotNum, sum = 0;
System.out.println("\t\t Welcome to\n \t\tJAVA LOTTERY!\n\n\n");
System.out.print(" Would you like to play with 3, 4, or 5 numbers? ");
gameType = input.nextInt();
System.out.println("\n\n Now think about a number with " + gameType + " digits and remember it!\n\n\n");
System.out.print(" How many games should we play? ");
gameTimes = input.nextInt();
System.out.println("\n\n We're all done! We played " + gameTimes + " games!\n\n" +
" The numbers randomly selected were: ");
for(int i = 0; i < gameTimes; i++)
{
lotNum = 0;
for(int j = 0; j < gameType; j++)
{
randomNums = (new Random()).nextInt(10);
lotNum = (lotNum * 10) + randomNums;
System.out.print(" " + randomNums);
}//end nested for loop
System.out.println();
sum += lotNum;
}//end for loop
System.out.println("\n\nThe total of all of the numbers was " + sum );
input.close();
}//end main method
}//end lottery class
Change
lotNum = (lotNum * 10) + randomNums;
to
lotNum += randomNums;

Categories

Resources