Java enhanced for loop picking the highest and lowest number - java

I'm working on this project, and I've been stuck for a while now.
I am what they say a "noob" in the wonderful world of Java programming..
I've managed to get the highest number working. It only prints 4 times now, but I can't get the lowest number to work.
public class MainClass {
public static void main(String[] args) {
StringConversion test = new StringConversion();
// Make our input / output object
int d1;
int d2;
int d3;
int d4;
int d5;
ConsoleIO io = new ConsoleIO();
io.writeOutput("Click below this message, type something and press ENTER");
// Tell it to read something from the
// console (the program waits for this to happen):
String input1 = io.readInput();
String input2 = io.readInput();
String input3 = io.readInput();
String input4 = io.readInput();
String input5 = io.readInput();
// etc. etc. Here you can see that the value was correctly
// stored in our local 'input' variable.
// string omzetten naar int
String i1 = input1;
String i2 = input2;
String i3 = input3;
String i4 = input4;
String i5 = input5;
d1 = Integer.parseInt(i1);
d2 = Integer.parseInt(i2);
d3 = Integer.parseInt(i3);
d4 = Integer.parseInt(i4);
d5 = Integer.parseInt(i5);
int antwoord = d1+d2+d3+d4+d5;
// totaal rekensom
System.out.println("total: ");
System.out.println(d1+d2+d3+d4+d5);
// gemiddelde som
int gemiddelde = antwoord / 5;
System.out.println("avarage: ");
System.out.println(gemiddelde);
// hoogste getal
int zeeslag[] = {d1, d2 , d3 , d4 , d5};
int max;
int min;
// het op dit moment maximum
max = zeeslag[0];
min = zeeslag[0];
//array doorlopen
for (int i: zeeslag) {
if (i > max){
max = i;
System.out.println("highest number: " + i);
}
else if(i<min){
min = i;
System.out.println("lowest number: " + i);
}
}
// laagste getal
input1 = io.readInput();
input2 = io.readInput();
input3 = io.readInput();
input4 = io.readInput();
input5 = io.readInput();
}
}

You need to print the max and min and not i. Also, they should be after the for loop because you need to compare with all the elements in the array before printing the maximum and minimum value.
for (int i : zeeslag) {
if (i > max) {
max = i;
} else if (i < min) {
min = i;
}
}
// print the max and min after the for
System.out.println("highest number: " + max); // print the max value and not i
System.out.println("lowest number: " + min); // print the min value and not i

You can make your code quite a bit shorter:
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
int[] zeeslag = new int[5];
int total = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
// Make our input / output object
Scanner sc = new Scanner(System.in);
for(int i = 0; i <5; ++i)
{
System.out.println("Enter number " + (i+1) + " of " + 5 + ":" );
zeeslag[i] = sc.nextInt();
total += zeeslag[i]; // total and average
if(zeeslag[i] < min)
min = zeeslag[i];
if(zeeslag[i] > max)
max = zeeslag[i];
}
System.out.println("total: " + total);
System.out.println("Average: " + (total/5));
System.out.println("Lowest: " + min);
System.out.println("Greatest: " + max);
}
}

Check the whole array inside the loop and then print the result.
max = zeeslag[0];
min = zeeslag[0];
for (int i: zeeslag) {
if (i > max){
max = i;
}
else if(i<min){
min = i;
}
}
System.out.println("highest number: " + max);
System.out.println("Lowest number: " + min);

Related

What's wrong with this method...?

import java.util.Scanner;
public class InputCalculator {
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
boolean first = true;
int sum = 0;
int count = 0;
int avg = 0;
while(true){
int number = scanner.nextInt();
boolean isAnInt = scanner.hasNextInt();
if(isAnInt){
sum += number;
count++;
avg = Math.round((sum)/count);
}else{
System.out.println("SUM = " + sum + " AVG = " + avg);
break;
}
scanner.nextLine();
}
scanner.close();
}
}
When input is "1, 2, 3, 4, 5, a", I think it's not reading the input 5, resulting sum = 10 and avg = 2! Why it's happening?
By the way it's just a method not whole code!
When scanner.nextInt() provides you '5', the next line 'scanner.hasNextInt() is false. Just change line order
import java.util.Scanner;
public class InputCalculator {
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
boolean first = true;
int sum = 0;
int count = 0;
int avg = 0;
while(true){
boolean isAnInt = scanner.hasNextInt();
if(isAnInt){
int number = scanner.nextInt();
sum += number;
count++;
avg = Math.round((sum)/count);
}else{
System.out.println("SUM = " + sum + " AVG = " + avg);
break;
}
scanner.nextLine();
}
scanner.close();
}
}
you can also clean the code like
import java.util.Scanner;
public class InputCalculator {
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
int sum = 0;
int count = 0;
while( scanner.hasNextInt() ){
int number = scanner.nextInt();
sum += number;
count++;
}
scanner.close();
double avg = Math.round((sum)/count);
System.out.println("SUM = " + sum + " AVG = " + avg);
}
}

Please explain that how this Java code identify maximum number from user input?

if a user 8,10,50 why this code only shows 50 why doesn't it show 8,10 as there is condition number > max. 8,10 are also > 0.
package com.Zeeshan;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scanner = new Scanner(System.in);
int max = 0;
int min = 0;
while (true ) {
System.out.println("Enter Number");
boolean isNext = scanner.hasNextInt();
if (isNext) {
int NewMax = scanner.nextInt();
if (NewMax > max) {
max = NewMax;
}
if (NewMax < min) {
min = NewMax;
}
}
else {
break;
}
scanner.nextLine();
}
System.out.println("max " + max + "min " + min);
scanner.close();
}
}
NewMax < min this condition will always false due to min = 0 at beginning.
You need to take care that your first number must set to min.
When you run your code, you should look at the first 2 numbers. You should set min to the lowest of the 2 and max to the highest. From then on, you can compare the next number with min and max.
UPDATE: try this
public static void main(String[] args) {
// write your code here
Scanner scanner = new Scanner(System.in);
// We assume there are at least 2 input numbers.
int max = 0;
int min = 0;
int first = scanner.nextInt();
int second = scanner.nextInt();
if (first > second) {
max = first;
min = second;
}
else {
max = second;
min = first;
}
while (true ) {
System.out.println("Enter Number");
boolean isNext = scanner.hasNextInt();
if (isNext) {
int NewMax = scanner.nextInt();
if (NewMax > max) {
max = NewMax;
}
if (NewMax < min) {
min = NewMax;
}
}
else {
break;
}
scanner.nextLine();
}
System.out.println("max " + max + "min " + min);
scanner.close();
}

Check if user enters negative numbers straight away?

I am trying to make a program where the user enters a number and the program computes the max and min and keeps asking untill it encounters negative.
DETAILED DESCRIPTION:-
However if the user enters a negative number at start up it should print "Max and min are undefined!" and end.
But if a positive number is entered the program prints max and min ,still keeps asking for more numbers untill a negative number is encountered ,seeing negative number it still prints max and min and then ends.
Is there a way to do this?
What i have tried is given below:-
import java.util.Scanner;
public class NegativeNum {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
double num = keys.nextInt();
double Max = num+0.5;
double Min = num-0.5;
if(num<0) {
System.out.println("Max and Min undefined");
}
while(num>0) {
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
num = keys.nextInt();
}
{
num = num*-1;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("Number is Negative! System Shutdown!");
System.exit(1);
}
}
}
Just calculate the maximum and minimum value during iteration
while(num>0) {
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
num = keys.nextInt();
if(Math.abs(num) > max) {
max = Math.abs(num);
}
if(Math.abs(num) < min) {
min = Math.abs(num);
}
}
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("Number is Negative! System Shutdown!");
System.exit(1);
import java.util.Scanner;
public class NegativeNum {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
double num = keys.nextInt();
double Max = num+0.5;
double Min = num-0.5;
if(num<0) {
System.out.println("Max and Min undefined");
System.exit(1);
}
while(true) {
double temp_num = num;
num = Math.abs(num);
Max = num+0.5;
Min = num-0.5;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
if ( temp_num < 0 )
break;
System.out.println("\nEnter another: ");
num = keys.nextInt();
}
System.out.println("Number is Negative! System Shutdown!");
}
}
import java.util.Scanner;
public class NegativeNum {
private static int entryCount = 0; // Count the Number of Entries
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
double num = keys.nextInt();
double Max = num+0.5;
double Min = num-0.5;
while(true) {
if( num < 0 && entryCount == 0) { // Make sure if it's first entry and it's negative too
System.out.println("Number is Negative! System Shutdown!");
System.exit(1);
}
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
num = keys.nextInt();
entryCount++;
}
}
}
This code successfully runs all the cases:-
import java.util.Scanner;
public class class2
{
public void positive(double num)
{
double Max = num+0.5;
double Min = num-0.5;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
}
public void negative(double num,String k)
{
double Max = num+0.5;
double Min = num-0.5;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
if(k=="terminate")
{
System.out.println("System is shutting down");
System.exit(1);
}
System.out.println("\nEnter another: ");
}
public static void main(String []args)
{
class2 obj=new class2();
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
boolean bol=true;
String k="";
double num = keys.nextInt();
int count=1;
if(num<0 && count ==1)
{
k="terminate";
count=count+1;
System.out.println("Max and Min undefined");
System.exit(1);
System.out.println("\nEnter another: ");
num = keys.nextInt();
}
while(bol==true)
{
while(num>0)
{
count=count+1;
obj.positive(num);
num = keys.nextInt();
}
while(num<0 && count!=2)
{
k="terminate";
obj.negative(num,k);
num = keys.nextInt();
}
count=count+1;
}
}
}

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..

Java entering test score validation

I am trying to output the amount of test scores between 5 and 35. I do get an invalid entry when the integer entered is below 5 or above 35, which is required. However, when I enter a number between 5 and 35, nothing happens. I get a blank line. The only way I can get "Enter Score" to show up is when I enter another number and press "Enter/Return". What am I doing wrong?
Here is my code:
============================
import java.text.NumberFormat;
import java.util.Scanner;
public class ValidatedTestScoreApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int maximumScore = 0;
int minimumScore = 100;
// get the number of scores to be entered
int amtTest = getIntWithinRange(sc,"Enter the number of test scores to be entered: ", 5, 35);
int numberOfEntries = sc.nextInt();
System.out.println();
sc.nextLine();
for (int i = 1; i <= numberOfEntries; i++)
{
int testScores = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
maximumScore = Math.max(maximumScore, testScore);
minimumScore = Math.min(minimumScore, testScore);
}
else if (testScore != 999)
{
System.out.println("Invalid entry, not counted");
i--;
}
}
// calculate the average score
double averageScore = (double) scoreTotal / (double) scoreCount;
// display the results
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + number.format(averageScore) + "\n"
+ "Minimum score: " + minimumScore + "\n"
+ "Maximum score: " + maximumScore + "\n";
System.out.println(message);
// see if the user wants to enter more test scores
System.out.print("Enter more test scores? (y/n): ");
choice = sc.next();
System.out.println();
}
}
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine();
}
return i;
}
public static int getIntWithinRange(Scanner sc, String prompt,
int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println(
"Error! Number must be greater than " + min + ".");
else if (i >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return i;
}
}
The problem is that you are trying to read the values multiple times.
int testScores = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
testScore = sc.nextInt();
Here you already got the value from the getIntWithinRangeMethod, but on the next line you are reading it again.
Also what are the amtTest and testScores variables good for? I'm not sure what you are trying to accomplish, but I guess you need to do these two changes:
// get the number of scores to be entered
// int amtTest = getIntWithinRange(sc, "Enter the number of test scores to be entered: ", 5, 35);
// int numberOfEntries = sc.nextInt();
int numberOfEntries = getInt(sc, "Enter the number of test scores to be entered: ");
// System.out.println();
// sc.nextLine();
...
// int testScores = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
testScore = getIntWithinRange(sc, "Enter score " + i + ": ", 1, 100);
After this, the programs behaves fine and I get this:
Enter the number of test scores to be entered: 2
Enter score 1: 5
Enter score 2: 6
Score count: 2
Score total: 11
Average score: 5.5
Minimum score: 5
Maximum score: 6
Enter more test scores? (y/n):

Categories