Java keeping highest number - java

int number = 0;
int score = 0;
while (true) {
Scanner input=new Scanner(System.in);
System.out.println("Please enter mark :");
number = input.nextInt();
Scanner mark=new Scanner(System.in);
score = mark.nextInt();
if (number > score ) {
System.out.println("Highest mark:" + number);
}
else if (number > 100) {
System.out.println("Invalid enter number 0-100");
}
else if
(number < 0){
System.out.println("Invalid enter number 0-100");
if(input.equals("quit")){
break;
Greetings, I would like to know how to keep the highest mark and the lowest mark after the student enters the number. and only to allow to enter numbers between 0-100. Thank you

You'll need two variables to keep track of the highest and lowest marks. Since you want your marks to be between 0 and 100, you can give starting values of the two variables -1 and 101 respectively:
int max = -1;
int min = 101;
-1 is not a reachable value and is lower than all the reachable values so any value in the given range is bigger than it which makes it perfect for a starting value for the max variable. If it starts from 101, no value in the range is bigger so the variable won't change. If the variable is 50 for exmaple, the values in the range 0-50 aren't bigger than 50 and they will be missed. The same logic can be done to see why I chose the value of 101 for the min variable.
Now you can enter marks and keep track of the highest and lowest one:
Scanner sc = new Scanner(system.in);
while (true) {
int mark = sc.nextInt();
if (mark > max) {
max = mark;
}
if (mark < min) {
min = mark;
}
}
Now the highest and lowest marks will be kept in the max and min variables respectively.
To implement the exit logic you can have the user to input a value outside the range and this will exit from the loop:
if (mark < 0 || mark > 100) {
break;
}
This if statement has to be put before the checking for highest and lowest mark because you don't mant to keep trak of such values.
This is the final code:
int max = -1;
int min = 101;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a value between 0 and 100. If the number is outside this range, the entering will stop.");
int mark = sc.nextInt();
//Exit logic
if (mark < 0 || mark > 100) {
//Closing the Scanner object (Not necessary but recommended)
sc.close();
break;
}
//Comapring
if (mark > max) {
max = mark;
}
if (mark < min) {
min = mark;
}
}

To update the score you just need to update your score.
if (number > score ) {
score = number; //update your score
System.out.println("Highest mark:" + number);
}
You should be able to solve this yourself tho.

Related

How to make a number invalid

Create a new program called minusSentinel2.
Prompt the user to enter whole numbers between 1 and 100. Allow the user to enter as many numbers as desired.
If an invalid number is entered, print "Invalid entry." Prompt the user again until a valid number is entered.
Once -1 is entered, the program stops and prints the largest number entered with the text "The largest number entered is: "
I am having some trouble on the "Invalid entry." part. When I type a number greater than 100, "Invalid entry." does not get printed. How do I fix this? Thank you!
import java.util.*;
public class minusSentinel2
{
public static void main (String[] args)
{
Scanner console = new Scanner(System.in);
System.out.println("Enter a number between 1-100 (type -1 to quit):");
int number = console.nextInt();
int max = number;
if (number < 1 && number > 100)//chekcs if value is valid
{
System.out.println("Invalid entry.");
System.out.println("Enter a number between 1-100 (type -1 to quit).");
console.next();
}
while (number != -1)
{
number = console.nextInt();
if (number > max)
{
max = number;
}
}
System.out.print("The largest number entered is: " + max);
}
}
Firstly, I suggest you to don't copy and paste what we ask you to do, and just reformulates with only necessary parts for us.
For your issue, this condition is wrong:
if (number < 1 && number > 100)
It correspond to "lower than 1 and bigger than 100".
So, instead of && (and) operator, use || (or) operator like that :
if (number < 1 || number > 100) {
// it's not valid because lower than 1 or greater than 100
}
Finally, what you are doing seems to have another issue.
If you enter an invalid number, it will ask again only one time, and not same the new value. So, I suggest you to use while loop like that :
int number = 0;
while(number < 1 || number > 100) {
number = console.nextInt();
if (number < 1 || number > 100) {
System.out.println("Invalid entry.");
System.out.println("Enter a number between 1-100 (type -1 to quit).");
}
}
int max = number;
To conclude, this is the full code:
Scanner console = new Scanner(System.in); // create scanner
int number = 0; // create new variable that will be used outside of while loop
while (number < 1 || number > 100) { // while the number isn't valid
System.out.println("Enter a number between 1-100 (type -1 to quit):");
number = console.nextInt(); // wait for user input
if (number == -1) { // stop program
console.close();
return;
} else if (number < 1 || number > 100) { // number invalid
System.out.println("Invalid entry.");
}
}
System.out.println("Now enter all number that you want. End with -1.");
int max = number; // create new max value
while (number != -1) {
number = console.nextInt();
if (number < 1 || number > 100) { // number invalid
System.out.println("Invalid entry.");
} else if (number > max) { // if number is upper than current one
max = number;
// here you can do something like that:
// System.out.println("New max value: " + max);
} else {
// the value is value but not upper than current one, so we can write:
// System.out.println("This value isn't upper to " + max);
}
}
System.out.print("The largest number entered is: " + max);
console.close();

How to Pass This Test Case?

I'm creating the program that determines the largest and smallest number is a series of numbers entered by the user. I've created several tests cases for my code and they all work out, but it fails the most simple test case. When the user inputs a single number. For instance, if the user sets the terminating value to be 25, then enters -1, and finally enters the terminating the value, the output should be
Largest: -1 and Smallest: -1. However, my code will output Largest: 0 and Smallest: -1 -- I why this happens (because I initialized the max value to be 0 before running the loop), but how can I fix this?
Here's my code...
Scanner scan = new Scanner(System.in);
// Declaration variables
double min;
double max = 0;
System.out.println("Enter terminating number: ");
double terminator = scan.nextDouble();
System.out.println("Enter a number: ");
double num = scan.nextDouble();
min = num;
if (num == terminator) {
System.out.println("There must be one number in the list.");
// break;
} else {
while (num != terminator) {
System.out.println("");
num = scan.nextDouble();
if ((num < min) && (num != terminator)) {
double temp = min;
min = num;
max = temp;
} else if ((num > min) && (num != terminator)) {
max = num;
} else {
max = min;
}
}
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
}
Instead of initializing max = 0, do max = num just like you already do with min.
It's not clear why you're initializing max differently from min; when a single number has been entered, it's both the minimum and the maximum. Right now, the only code that modifies max is within the loop that reads numbers beyond the first, so the first number has no effect on it.

Printing the two highest values from user input

I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
import java.util.Scanner;
public class ToStoersteTall{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
int biggest = 0;
for (int i = 3; i <= tall; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
biggest = num1;
if(biggest < num3){
biggest = num3;
}
}
System.out.println(biggest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
A couple things:
good practice to close scanner (and IO-related resources in general)
reduced if-statement blocks bloat for easier readability
you specify 2 guaranteed numbers, so attempt to parse those before looping
can remove system.exit calls or replace system.exit and move bulk of code back into the larger if-else blocks as originally state in OP (but I refer back to the sake of readability)
added check for the first and second numbers input to make sure high1 is highest value, and high2 is second highest value.
keep order while looping and checking values (note: does not use array), if the number is a new high, replace high1 and move high1's value down to high2, or if the number is a second (new) high, replace high2. If values are equal, this logic is excluded and you may want to specify based on your own constraints
import java.io.IOException;
import java.util.Scanner;
public class ToStoersteTall {
public static void main(String[] args) throws IOException {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
int n = 0;
if (reader.hasNextInt()) {
n = reader.nextInt();
} else {
System.out.println("Vennligst oppgi et heltall større eller lik 2.");
System.exit(-1); // quits execution
}
if (n < 2) {
System.out.println("Please enter an integer equal or higher than 2.");
System.exit(-2);
}
// Since guaranteed 2 numbers, parse and assign now
int high1 = 0, high2 = 0;
System.out.println("Enter value # 1");
if (reader.hasNextInt())
high1 = reader.nextInt();
System.out.println("Enter value # 2");
if (reader.hasNextInt())
high2 = reader.nextInt();
// check to see if a switch to keep correct highest order, swap values if so
if (high1 < high2) {
int t = high2;
high2 = high1;
high1 = t;
}
// loop won't execute if only 2 numbers input, but will if 3 or more specified at start
for (int i = 2; i < n; ++i) {
System.out.println("Enter value #" + (i + 1));
if (reader.hasNextInt()) {
int t = reader.nextInt();
if (t > high1) {
high2 = high1; // throw away high2 value and replace with high1
high1 = t; // replace high1 value with new highest value
} else if (t > high2) {
high2 = t;
}
} else {
System.out.println("Please enter an interger");
}
}
reader.close();
System.out.println("The two highest numbers are: " + high1 + ", " + high2);
}
}
You're already keeping track of the biggest, so why not keep track of the second biggest? Another easy way of solving this problem is to keep all the numbers in a list, sort the list by number size, and grab the two highest entries.
I tried your code and used an array to solve the problem.
import java.util.Scanner;
public class Main {
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
public static void main(String[] args) {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
int[] array = new int[numbers];
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
array[0] = num1;
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
array[1] = num2;
int biggest = 0;
for (int i = 3; i <= numbers; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
array[i-1] = num3;
}
System.out.println("second largest number is" + secondHighest(array));
int largest = 0;
for(int i =0;i<array.length;i++) {
if(array[i] > largest) {
largest = array[i];
}
}
System.out.println("Largest number in array is : " +largest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
Test
How many numbers? (minimum 2)?:
6
Enter value #1
3
Enter value #2
4
Enter value #3
5
Enter value #4
6
Enter value #5
7
Enter value #6
8
second largest number is7
Largest number in array is : 8
There is a logic error in your program. If numbers is 2, then the for loop never gets executed, and the value of biggest remains zero because it is never updated. Change your declaration of biggest to reflect the current maximum value found so far.
int biggest = num1 > num2 ? num1 : num2;
That way if the for loop never executes then biggest will be the maximum value of the first two numbers.
As for keeping track of the second highest value, you could introduce another variable secondBiggest, initialised in a similar manner to biggest, and then write logic to update this value in your for loop. However, in my opinion, it would be much easier to change your strategy to hold the entered values into an array, then when all inputs have been entered, calculate whichever values you desire from the array. This would lead to a much cleaner solution IMO.
(I have assumed that tall in the for loop is actually meant to be numbers...)
import java.util.Scanner;
public class Foo{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if(reader.hasNextInt()){
int numbers = reader.nextInt();
if(numbers >= 2){
int[] list = new int[numbers];
for(int i = 0; i < numbers; i++){
System.out.println("Enter value #" + (i + 1));
if(reader.hasNextInt())
list[i] = reader.nextInt();
}//for
int biggest = 0;
int secondBiggest = 0;
// find the values you want
for(int i = 0; i < numbers; i++){
if(list[i] > biggest){
secondBiggest = biggest;
biggest = list[i];
}//if
else if(list[i] > secondBiggest)
secondBiggest = list[i];
}//for
// print your results
System.out.println("The biggest integer is: " + biggest);
System.out.println("The second biggest integer is: " + secondBiggest);
}//if
}//if
}//main
}//class

Java finding the minimum value from Scanner input always resulting in zero

This is my first Java program. It is supposed to allow a user to enter int grades between 0 and 100. If the user enters a negative value, data entry ceases and statistics are displayed. I cannot incorporate static methods, math, or arrays.
I am having an issue with finding the minimum grade, minGrade. Regardless of what values are entered when the program is running, minGrade always results in zero. I have been tinkering with this for a while now to no avail.
The other issue I am having is that when I run the program, and I enter a bunch of int, but then enter some alphabet letters to test the error-checking, the program parses the user twice, instead of once.
"Please enter a numeric grade between 0 and 100, inclusive, and press Enter:"
The respective code is:
import java.util.Scanner;
public class Grades {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the Course Code and and press Enter:");
String courseCode = keyboard.nextLine();
System.out.println("You entered: " + courseCode + "\n");
int grade = 0;
int numberOfGrades = 0;
int maxGrade = 0;
int minGrade =0;
double avgGrade = 0;
int sumGrades = 0;
int sentinel = 0;
do
{
**System.out.println("Please enter a numeric grade between 0 and 100, inclusive, and press Enter:");**
while(!keyboard.hasNextInt())
{
System.out.println("Please enter a numeric grade between 0 and 100, inclusive, and press Enter:");
keyboard.nextLine();
}
grade = keyboard.nextInt();
if((grade <=100) && (grade >= 0))
{
numberOfGrades++;
sumGrades += grade;
sentinel = 0;
if(maxGrade < grade)
maxGrade = grade;
**if(minGrade > grade)
minGrade= grade;**
}
else if(grade > 100)
{
System.out.println("The entered number was greater than 100. Please enter a number between 0 and 100 inclusive, "
+ "or input a negative number to exit Grade entry");
sentinel = 0;
}
else if(grade <0)
{
grade = 0;//maybe?
sentinel = -1;
}
}
while((grade >100) || (sentinel == 0));
avgGrade = (sumGrades/numberOfGrades);
System.out.println("You entered: " + "\ngrade: " + grade + "\n" + "sentinel: "+ sentinel +
"\nSum of Grades: " + sumGrades +"\nNumber of Grades: "+ numberOfGrades +"\nAverage Grades: " + avgGrade
+ "\nMaxium Grade: "+ maxGrade+"\nMinimum Grade: "+minGrade);
}
}
Any input on this, the form of my code for my first java program, or anything else would be greatly appreciated.
The last issue I am having is that the average grade always has a tenth place of zero. How can I get the tenth place to not be zero and the actual average amount?
Your problem with minGrade is that you initialize it to 0. This is already the min value, hence no other values will be less than this. (You in fact ensure this even more so by setting negative grades to 0.) Initialize it to the max value (100).
It looks like your "double prompt" issue is a common one with nextLine and nextInt. The solution seems to be using only nextLine and then parsing the return value of that for an Integer object. (And printing out your "invalid input" text on a NumberFormatException.
Finally, your avgGrade is always xx.0 as you are dividing two integers, which always gives an integer back. You need to cast one to a double to get a double back:
avgGrade = ((double)sumGrades/numberOfGrades);
minGrade will never be set to anything other than 0 because 0 will never be greater than the grade entered, so this check fails if(minGrade > grade). Try initializing minGrade to Integer.MAX_VALUE.

Java: Two Smallest numbers helo

So my code works in all test cases except for when there are only two integers.
Example if user inputs: terminating number as -1 and then inputs 1,2 and then -1 again the smallest numbers are 1,1 and not 1,2
Terminating number is just the way to end the sequence/program.
public static void main(String[] args) {
double num;
double min = 0;
double min2 = 0;
System.out.println("Enter terminating value:");
int term = IO.readInt();
System.out.println("Enter next value:");
num = IO.readDouble();
if(num == term){
IO.reportBadInput();
main(args);
}
int count = 0;
min = num;
min2 = num;
do{
num = IO.readDouble();
if(num!= term && num < min) {
min2 = min;
min = num;
}
else if (num!= term && num < min2) {
min2 = num;
}
count++;
}while (num != term);
if(count < 2){
IO.reportBadInput();
main(args);
}
else{
IO.outputDoubleAnswer(min);
IO.outputDoubleAnswer(min2);
}
}
The issue with your code lies in setting both minimal values to the number that was first entered. This is bad because if the user enters the smallest value first, both min and min2 already contain the minimum value. That means the condition input < min2 is always false, causing min2 to always contain the value the user has entered first.
To fix this, simply set the value of min2 to a value which is larger than any other value the user could enter (for example Double.MAX_VALUE or Double.POSITIVE_INFINITY).
Just as a hint concerning the error-handling part of your code: if you call main again after reminding the user that their input was invalid, make sure to add a return behind that call or the execution will continue after the called main method is finished. Something like this:
if (count < 2) {
IO.reportBadInput();
main(args);
return;
}

Categories