Java Largest and smallest [duplicate] - java

This question already has answers here:
Java program to find the largest & smallest number in n numbers without using arrays [closed]
(8 answers)
Closed 6 years ago.
I have a slight issue with my program. I need to ask the user to input as many numbers as they want and then the program will tell them what is the smallest and largest number. My issue is when all is said and done it prints out "the largest number is 0" and "the smallest number is 0". It always says that even if i never enter 0. I was wondering what was wrong with the program. Any pointers or helpers would be fantastic. Again to repeat, the issue im having is that the smallest and largest come back as 0's no matter what.
import java.util.Scanner;
public class LargestAndSmallest {
public static void main(String[] args) {
int smallest = 0;
int large = 0;
int num;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the numer");
int n = keyboard.nextInt();
num = keyboard.nextInt();
while (n != -99) {
System.out.println("Enter more numbers, or -99 to quit");
n = keyboard.nextInt();
}
for (int i = 2; i < n; i++) {
num = keyboard.nextInt();
if (num > large) {
large = num;
System.out.println(large);
}
if (num < smallest) {
smallest = num;
}
}
System.out.println("the largest is " + large);
System.out.println("the smallest is " + smallest);
}
}
I used this code as in the first place: Java program to find the largest & smallest number in n numbers without using arrays

import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class LargestAndSmallest {
public static void main(String... args) {
final Scanner keyboard = new Scanner(System.in); //init the scanner
System.out.println("Enter a number");
final Set<Integer> ints = new HashSet<>(); //init a set to hold user input
int n; //declare a variable to hold each number
while ((n = keyboard.nextInt()) != -99) { //loop until 99 is entered
ints.add(n); //add user input to our set
System.out.println("Enter more numbers, or -99 to quit.");
}
//output aggregate info
System.out.println("the largest is " + Collections.max(ints));
System.out.println("the smallest is " + Collections.min(ints));
}
}

Related

Why is my program not considering adding up the value that the user inputs.?

I am trying to make a program, that gets an integer from the user.
Adds up all the numbers from 1 to that number, and display the total. Below is the program that I wrote and the problem is sum doesn't add the value the user inputs.
import java.util.Scanner;
public class AddingValuesForLoop
{
public static void main(String[] args)
{
int Number,Sum;
Sum=0;
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter your Number: ");
Number=keyboard.nextInt();
for (int i=1;i<=Number;i++)
{
Sum=i+Number;
System.out.println("\r"+i+"");
}
System.out.println("the total Sum = "+Sum+".");
}
}
OUTPUT:
Enter number: 5
1
2
3
4
5
The total Sum = 10.
You shall write Sum = i + Sum instead of Sum=i+Number. Here is the full code.
import java.util.Scanner;
public class AddingValuesForLoop{
public static void main(String[] args) {
int Number,Sum;
Sum=0;
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter your Number: ");
Number=keyboard.nextInt();
for (int i=1;i<=Number;i++) {
// Add i to sum until now
Sum=Sum+i;
}
System.out.println("the total Sum = "+Sum+".");
}
}
Your problem is in this line:
Sum=i+Number;
This line means that your sum will contain the last i value from the loop and the number entered by the user, it should looks like:
Sum += i;
And then add the number entered by the user to the Sum value, your code will looks like that:
import java.util.Scanner;
public class AddingValuesForLoop{
public static void main(String[] args) {
int Number,Sum;
Sum=0;
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter your Number: ");
Number=keyboard.nextInt();
for (int i=1;i<=Number;i++) {
Sum +=i;
System.out.println("\r"+i+"");
}
Sum+=Number;
System.out.println("the total Sum = "+Sum+".");
}
}
2 problems with your program.
Firstly, you are resetting the value of Sum in each iteration. So during the last iteration, the i value is 5, Number value is 5 and thus you get output as 10.
Secondly, you want to add up numbers from 1 to that Number, so it should be something like this:
sum = sum + i;
If the user enters 3
(sum = 0 + 1, sum = 1 + 2, sum = 3 + 3), thus output will be 6.
since you use
Sum=i+Number;
which in that code means get the value of i and value of number and sum them together and put it in Sum var each time that's way there is no sum happening
you should use
Sum += i+Number;
which means
Sum = Sum + (i+Number);

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 Programming Looping

Write a java programs that prompts the user to enter user's name and 4 numbers, reads them, then prints the smallest and largest of all the numbers typed in by the user. The program will continue looping if the largest number is greater or equal to 10. At the end, program will show how many times the program has looped. How can i loop and find how many times the program looped ?
import java.io.*;
import java.util.*;
class largestLoop
{
public static void main(String [] args) throws IOException
{
String name;
int[] num = new int[4]; // save 4 number in array
int smallest = num[0], largest = num[0];
do{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name : ");
name = stdin.readLine();
System.out.println(name + ", Please enter 4 numbers");
// Read for number using for loop
Scanner inData = new Scanner(System.in);
for(int i = 0; i < num.length; i++)
{
System.out.print("Enter " + (i+1) + " : "); // value i will + 1
num[i] = inData.nextInt();
}
// Find larger and smallest
for (int i : num)
{
if (i < smallest)
{
smallest = i;
} // end finding smallest
else if (i > largest)
{
largest = i;
} // end finding largest number
} // end finding largest and smallest values
System.out.println("Largest = " + largest);
System.out.println("Smallest = " + smallest);
}while(largest >= 10);
}
}
Output :
Enter your name : testing
testing, Please enter 4 numbers
Enter 1 : 2
Enter 2 : 6
Enter 3 : -5
Enter 4 : 16
Largest : 16
Smallest : 0
Enter your name : google
google, Please enter 4 numbers
Enter 1 : 5
Enter 2 : 8
Enter 3 : 1
Enter 4 : 6
Largest : 16
Smallest : 0
Enter your name : ....
The program become infinite loop. It should stop whenever user enter numbers that less than or equal to 10. The Largest and Smallest also does not right, when user enter <= 10 in next loop number. It will display a previous value or Largest. Also , the smallest keep display a 0 value.
First of all the assignment:
int smallest = num[0], largest = num[0];
is not dynamic in nature. Meaning the value of smallest and largest is not going to change everytime the value of num[0] changes. You need to do that manually everytime new values are entered.
Secondly you have not used any variable to actually count the number of loops.
Making these changes your code should look something like this:
package com.abhinav.testing;
import java.io.*;
import java.util.*;
class largestLoop
{
public static void main(String [] args) throws IOException
{
String name;
int[] num = new int[4]; // save 4 number in array
int smallest=0,largest=0;
int count=0;
do{
count++;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name : ");
name = stdin.readLine();
System.out.println(name + ", Please enter 4 numbers");
// Read for number using for loop
Scanner inData = new Scanner(System.in);
for(int i = 0; i < num.length; i++)
{
System.out.print("Enter " + (i+1) + " : "); // value i will + 1
num[i] = inData.nextInt();
}
smallest = num[0];
largest = num[0];
// Find larger and smallest
for (int i : num)
{
if (i < smallest)
{
smallest = i;
} // end finding smallest
else if (i > largest)
{
largest = i;
} // end finding largest number
} // end finding largest and smallest values
System.out.println("Largest = " + largest);
System.out.println("Smallest = " + smallest);
}while(largest >= 10);
System.out.println("Number of times the loop ran= "+count);
}
}

How to do an addition from random numbers by the user?

I am new to Java and I would like some help. I have to solve this problem and I have it almost 90% solved:
Prompt the user to enter number of students. It must be a number that is perfectly divisible by 10 i.e. (number % 10) = 0
Check user input. If user input is not divisible by 10, keep asking the user for input until he enter a right number.
Accept user input and generate that many random numbers in the range from 0 to 100.
Print a matrix of random numbers and calculate the sum and average of all these random numbers and print them to the user.
Format sum and average to three decimal points.
This is my code so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.abs(Math.random() * ( 0 - 100 ));
System.out.print(" " +dec.format(numb) + " ");
}
}
}
As you can see, I have solved until the first part of # 4. I am not sure how I could sum all those random numbers displayed on the screen after user input. Of course, we have to store them in an array but I tried to do that but couldn't. So, how could I complete step #4 and 5? I would appreciate any help. Thanks a lot guys.
Here is how you should do it:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
double sum=0;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.random() * ( 100 - 0));
System.out.print(" " + dec.format(numb) + " ");
sum += numb;
}
System.out.println("The sum is: " + dec.format(sum));
System.out.println("The average is:" + dec.format(sum/num));
}
}
Please note that I have slightly changed the way you were generating the random numbers which obviates the need to use Math.abs(). Also see the following answer to see how to generate random numbers between two different values:
Generating random numbers with Java
You do not need to store them in an array. Just declare int sum = 0 at the start and do sum += numb each time you generate a random number. Also, you are generating random numbers in a strange way. Take a look at the java.util.Random class.

JAVA - Highest and Lowest numbers [duplicate]

This question already has answers here:
How do I determine the highest and lowest value in user-entered input?
(4 answers)
Closed 9 years ago.
Please help me in finding the Highest and Lowest number.
I swear, I did read countless posts on the site about this problem before I decided to post the code here, because all of them had known numbers of input.
I have "unknown" input from the user. It could be any given positive or negative numbers. I am totally blank now after trying it for almost a day. Any helps is Greatly Appreciated.
package test;
import java.util.Scanner;
import java.lang.*;
import java.io.*;
public class Test {
public static void main(String[] args){
int highest=Integer.MIN_VALUE;
int lowest=Integer.MAX_VALUE;
Scanner in = new Scanner(System.in);
System.out.println("Enter any positive or negative number");
int n = in.nextInt();
if(n > highest){
lowest = highest;
highest = n;
}
if (n < lowest){
highest=lowest;
lowest=n;
}
System.out.println(highest);
System.out.println(lowest);
}
}
This is where your code is breaking.
highest=lowest;
lowest=n;
Now about initializing these variables.
How I, personally would start this program would be initializing both the lowest and highest with n. So you don't have to worry any bounds.
System.out.println("Enter any positive or negative number");
int n = in.nextInt();
int highest = n;
int lowest = n;
for(int i = 0; i < 9; i++){
System.out.println("Enter any positive or negative number");
n = in.nextInt();
if(n > highest){
highest = n;
}else if (n < lowest){
lowest=n;
}
}
System.out.println(highest);
System.out.println(lowest);
This asks the user to input 10 different digits. then prints out the highest and lowest values.
else if (n < lowest) this could also be a else if because if n is the highest value it cant be also the lowest value because of my initialization at the start.
Why are you saving the lowest value in the highest value?
You should define a loop
Complete code:
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
System.out.println("Enter any positive or negative number");
int n = in.nextInt();
if(n > highest){
highest = n;
}
if (n < lowest){
highest=lowest;
lowest=n;
}
}
System.out.println(highest);
System.out.println(lowest);

Categories