The purpose for the code is to prompt the user for 10 integers and then display the largest and smallest integer. I was able to ask the user for the 10 integers and display the largest number; however, the smallest number isn't shown. I believe the issue is with me setting smallest to 0.
import java.util.Scanner;
public class LargeSmall {
public static void main(String[] args) {
int counter = 1;
int largest = 0;
int smallest = 0;
int number = 0;
Scanner input= new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter number: ");
number = input.nextInt();
if (number > largest) {
largest = number;
}else if(number < smallest) {
smallest = number;
}else {
System.out.print("Number isn't distinct");
counter = counter + 1;
}
System.out.println("Largest number is: " + largest);
System.out.println("Smallest number is: " + smallest);
}
}
Initialize your values like this so we guarantee that we start with the smallest/largest possible reference for our numbers to compare against to:
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int number;
int old = Integer.MIN_VALUE;
...and then some tweaks have to be made:
Change the way you check for dupe numbers (use and old variable).
Check if every new number is smaller than smallest number always (so, in the first iteration we assign the first value to smallest and largest)
Like this:
number = input.nextInt();
if (old != number) {
old = number;
if (number > largest) {
largest = number;
}
if(number < smallest) {
smallest = number;
}
/* consider moving next line here (this will guarantee to go to the next
iteration only if the numbers are different, and get in the final messages,
valid values for `smallest` and `largest` */
// counter = counter + 1;
} else {
System.out.print("Number isn't distinct");
}
Just make > into >= and < into `<=
Since 0 < 0 evaluates to false, your code block does not run. Thus the correction.
Variable smallest is always 0 so the program never go into this block else if(number < smallest)
You should add this code before if(number < smallest)
if(smallest == 0) {
smallest = number;
}
Also your code doesn't catch the distinct numbers. To find the distinct number you should define a list List<Integer> numbers = null; at the start of the program.
Then you can check if the input is entered or not in the while loop like this:
if(numbers.contains(number))
System.out.print("Number isn't distinct");
else
numbers.add(number);
Sets the largest and smallert variables with the user's first input and then compare
import java.util.Scanner;
public class LargeSmall {
public static void main(String[] args) {
System.out.print("Enter number: ");
Scanner input= new Scanner(System.in);
int number = input.nextInt();
int counter = 1;
int largest = number;
int smallest = number;
while (counter < 10) {
System.out.print("Enter number: ");
number = input.nextInt();
if (number > largest) {
largest = number;
}else if(number < smallest) {
smallest = number;
}else
System.out.print("Number isn't distinct");
counter = counter + 1;
}
System.out.println("Largest number is: " + largest);
System.out.println("Smallest number is: " + smallest);
}
}
Related
I have received a question in my school programming assignment, which goes like this:
Enter n count of numbers and find the largest and smallest among the lot. Also find the second largest number.
Now, the main problem is the second smallest number part.. We have still not been taught arrays, so I want a solution to this question without arrays. This is what I have made till now, through this code, I am able to find the largest and the smallest number correctly, but I find the second smallest number part tough!
import java.util.*;
class SecondLargest
{
public static void main(String args[])
{
System.out.println('\u000C'); //used to clear screen
Scanner y=new Scanner(System.in);
System.out.println("Enter the number of values to be entered");
int n=y.nextInt();
System.out.println("Enter number 1");
int num=y.nextInt();
int max=num,min=num,temp=num;
for(int i=2;i<=n;i++)
{
System.out.println("Enter number "+i);
num=y.nextInt();
if(num>max)
max=num;
else if(num<min)
min=num;
}
System.out.println("The largest number is "+max);
System.out.println("The smallest number is "+min);
}
}
Just make another variable like your min and max variables.
if (num<max && num >min) {
}
Create additional variable max2 and shift previous max value when a new maximum is detected, or check if there is a value over max2:
Scanner y = new Scanner(System.in);
System.out.println("Enter the number of values to be entered");
int n = y.nextInt();
System.out.println("Enter number 1");
int num = y.nextInt();
int max = num, max2 = num, min = num;
for (int i = 2; i <= n; i++) {
System.out.println("Enter number " + i);
num = y.nextInt();
if (num < min) {
min = num;
} else if (num > max) {
max2 = max; // shift previous max to become the 2nd largest
max = num; // store max
} else if (num > max2) {
max2 = num;
}
}
System.out.println("The largest number is " + max);
System.out.println("The 2nd largest number is " + max2);
System.out.println("The smallest number is " + min);
I need to create a loop where the user can input any amount of numbers between 1-4 and then I calculate the average. Typing 0 will end the program and calculate the average. Any value greater than 4 or less than 0 should not count and ask the user to input the value again. I'm stuck on the last part. I'm not sure if the while loop is the correct loop to use either. Thanks for any help
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double count = 0;
while(input.hasNextInt()) {
int num = input.nextInt();
if (num == 0)
break;
if (num > 4)
System.out.println("Invalid number");
sum += num;
count += 1;
}
System.out.println("Average: " + sum/count);
}
You will always hit the lines:
sum += num;
count += 1;
Because the code just drops through from the second if statement.
The following would work - note the else if and else blocks will only be executed when the first if drops through:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double count = 0;
while(input.hasNextInt()) {
int num = input.nextInt();
if (num == 0) {
break;
}
else if (num > 4) {
System.out.println("Invalid number");
}
else {
sum += num;
count += 1;
}
}
System.out.println("Average: " + sum/count);
}
I have encountered some problems with the calculating of largest and smallest number... If the first number I entered is a larger number than the 2nd number input, it will not record the 1st number into the largest...
Take a look at the output, it will help elaborate better..
Calculation Error.. &
1st input problem..
Codes below!
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int largest = 0;
int number;
double totalAvg = 0;
double totalSum = 0;
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Enter few integers (Enter negative numbers to end input) :");
while (true) { //LOOP till user enter "-1"
number = kb.nextInt();
//Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
count = count + 1;
}
if (number < smallest) { //Problem 1 : If 1st input num is bigger than 2nd input num,
smallest = number; // largest num will not be recorded..
} else {
largest = number;
}
totalSum = totalSum + number;
totalAvg = (totalSum / count);
}
System.out.println("The smallest number you have entered is : " + smallest);
System.out.println("The largest number you have entered is : " + largest);
System.out.println("The total sum is : " + totalSum);
System.out.println("The total average is : " + totalAvg);
System.out.println("Count : " + count);
} // PSVM
You could build an IntStream if you are using Java 8, and extract those numbers automatically using IntSummaryStatistics. You can find the official documentation from Oracle here.
Here is the code to achieve that:
List<Integer> input = new ArrayList<>();
while (true) { // LOOP till user enter "-1"
number = kb.nextInt();
// Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
input.add(number);
}
}
IntSummaryStatistics z = input.stream() // gives Stream<Integer>
.mapToInt(Integer::intValue) // gives IntStream
.summaryStatistics(); // gives you the IntSummaryStatistics
System.out.println(z);
If you input 8 3 7 the output will be:
IntSummaryStatistics{count=3, sum=18, min=3, average=6.000000, max=8}
I hope it helps!
Do it like this:
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int largest = 0;
int number;
double totalAvg = 0;
double totalSum = 0;
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Enter few integers (Enter negative numbers to end input) :");
while (true) { //LOOP till user enter "-1"
number = kb.nextInt();
//Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
count = count + 1;
}
if (number < smallest) { //Problem 1 : If 1st input num is bigger than 2nd input num,
smallest = number; // largest num will not be recorded..
}
//REMOVED ELSE ADDED another IF
if (number > largest){
largest = number;
}
totalSum = totalSum + number;
totalAvg = (totalSum / count);
}
System.out.println("The smallest number you have entered is : " + smallest);
System.out.println("The largest number you have entered is : " + largest);
System.out.println("The total sum is : " + totalSum);
System.out.println("The total average is : " + totalAvg);
System.out.println("Count : " + count);
} // PSVM
The problem is your if statement, as the logic is flawed. If the input number is smaller than smallest, then you update the smallest number. So far all is correct. The problem occurs, because you update largest in the else part. This means, if a number is not the smallest, largest is overwritten. But if the number is greater than the smallest, it is not automatically the largest. The right way to do this, is to check if the number is larger than the largest in a new if statement and update largest only in this case.
The code compiles, but all my answers come out to be 0.
import java.util.Scanner;// use the Scanner class located in the "java.util" directory
public class Assignment2
{
public static void main(String[] args)//main method that runs the program using methods below
{
double[] numbers = new double[100];
Scanner input = new Scanner(System.in);
int count;
int c=0;
do
{
count = input.nextInt();
c++;
} while (count != 0 && c < numbers.length);
double min = findMin(numbers, numbers.length);
int countNeg = countNegative(numbers, numbers.length);
double sum = computePositiveSum(numbers, numbers.length);
System.out.println("The minimum number is " +min);
System.out.println("The sum of the positive numbers is $" +countNeg) ;
System.out.println("The total number of negative numbers is " +sum);
}
public static double findMin(double[] numbers, int count) //finds and displays the minimum input value
{
double min = numbers[0];
for(count =1; count<numbers.length; count++)
{
if(numbers[count] <min)
{
min = numbers[count];
}
}
return min;
}
public static int countNegative (double[] numbers, int count) //counts the number of times a negative number is added to the array
{
int countNeg =0;
for (count = 0; count < numbers.length; count++)
{
if(numbers[count] < 0)
{
countNeg = countNeg + 1;
}
}
return countNeg;
}
public static double computePositiveSum(double[] numbers, int count)//calculates the sum of the positive integers in the array
{
double sum = 0;
for(count=0; count<numbers.length; count++)
{
if(numbers[count] > 0)
{
sum = sum + numbers[count];
}
}
return sum;
}
}
You are not assigning the entered values to the array numbers. Add this
numbers[c] = count;
inside the do-while loop:
do {
count = input.nextInt();
numbers[c] = count;
c++;
} while (count != 0 && c < numbers.length);
Note that if you just input positive (> 0) numbers and don't fill the whole array numbers, findMin() will return 0, because it is the default value for the elements of the array.
Edit:
I would say that the print statement
System.out.println("The sum of the positive numbers is $" + countNeg);
System.out.println("The total number of negative numbers is " + sum);
are not coherent with the methods called. It should be:
System.out.println("The sum of the positive numbers is " + sum);
System.out.println("The total number of negative numbers is " + countNeg);
double[] numbers = new double[100];
Scanner input = new Scanner(System.in);
int count;
int c=0;
do
{
count = input.nextDouble();
numbers[c] = count;
c++;
} while (count != 0 && c < numbers.length);
This code should work. You have to add the numbers to the array which you are entering through stdin
double[] numbers = new double[100];
Here you are initializing the array with all 0.0 elements. You want to take input int he array from stdin?
You don't put anything into numbers array so they are all 0. The corrected code is this:
do
{
numbers[c] = input.nextDouble();
c++;
} while (numbers[c] != 0 && c < numbers.length);
I'm trying to write a class which reads 5 integers from the user and returns the highest and lowest value back. This must be done using loops and without using arrays and Integer.MIN.Value/Integer.MAX.Value. I've already succeeded writing code that gets 5 integers from the user and returns the highest value but I just can't get both the highest and the lowest value returned in the same class.
Here is the code I mentioned above:
import java.util.Scanner;
public class Ovning_321 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number;
int max = 0;
for (int x = 0; x<5; x++){
System.out.print("Give me an integer: ");
number = input.nextInt();
if (number > max){
max = number;
}
}
System.out.println("Highest value: " + max);
}
}
here you go :)
import java.util.Scanner;
public class Ovning_321 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number;
int max = 0;
int min = 0;
for (int x = 0; x<5; x++){
System.out.print("Give me an integer: ");
number = input.nextInt();
if (x == 0 || number > max){
max = number;
}
if (x == 0 || number < min){
min = number;
}
}
System.out.println("Highest value: " + max);
System.out.println("Lowest value: " + min);
}
}
Why not just repeat your max logic for min?
public class Ovning_321 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Give me an integer: ");
number = input.nextInt();
int max = number;
int min = number;
for (int x = 0; x<4; x++){
System.out.print("Give me an integer: ");
number = input.nextInt();
if (number > max){
max = number;
}
if (number < min){
min = number;
}
}
System.out.println("Highest value: " + max);
System.out.println("Lowest value: " + min);
}
}
Note that max and min are initially set to the first number that the user enters, so there will be no false 0's and no need to MAX_INT or MIN_INT. This in turn makes the loop run once less so terminate at i == 4 instead of 5.