I'm trying to find the largest and smallest number in my array however, it only seems to print out the largest and not the smallest, I'm fairly new so all help is appreciated, thank you.
import java.util.Scanner;
public class Ex1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[11];
int largest = numbers[0];
int smallest = numbers[0];
System.out.println("Enter 10 numbers = ");
for (int i = 1; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + i + " = " + numbers[i]);
for (int y = 1; y < numbers.length; y++) {
if (numbers[y] > largest)
{
largest = numbers[y];
}
}
for (int x = 1; x < numbers.length; x++)
{
if (numbers[x] < smallest)
{
smallest = numbers[x];
}
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
} // main
} // class
It doesn't print out the smallest number because you set it in the beginning to 0, set it to Integer.MAX_VALUE instead.
Also to make sure your program works for negative numbers, set the value of largest to Integer.MIN_VALUE.
int smallest = numbers[0];
This is creating problem. This assigns value 0 in the beginning hence you are not getting smallest number.
Also your test dataset must be containing only positive numbers.
Solution
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
There are some code issues other than correctly finding min and max of input numbers.
You don't have to write nested for loops for this. Check below code and that will simply find you min and max numbers,
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[11];
int largest = numbers[0];
int smallest = numbers[0];
System.out.println("Enter 10 numbers = ");
for (int i = 1; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + i + " = " + numbers[i]);
if (i == 1) {
largest = numbers[i];
smallest = numbers[i];
}
if (numbers[i] > largest) {
largest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
try this,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers = ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + (i + 1) + " = " + numbers[i]);
}
int largest = numbers[0];
int smallest = numbers[0];
for (int y = 0; y < numbers.length; y++) {
if (numbers[y] >= largest)
{
largest = numbers[y];
}
if (numbers[y] <= smallest)
{
smallest = numbers[y];
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
}
Related
The code displays the sum, average, and largest element. It doesn't display the smallest element as the output is always zero. How do I display the smallest element in the array?
import java.util.Scanner;
public class Average {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int length = input.nextInt();
int[] num = new int[length];
System.out.println("Enter the "+ length + " array elements:");
int sum = 0;
int large,small;
large =small = num[0];
for (int i=0; i<length;i++) {
num[i] = input.nextInt();
sum = sum+ num[i];
}
for (int i=0; i<length; ++i) {
if (num[i]<small) {
small = num[i];
}
if(num[i]> large) {
large = num[i];
}
}
double avg = sum/length;
System.out.println("The sum is "+ sum);
System.out.println("The average is "+ avg);
System.out.println("The smallest element is "+ small);
System.out.println("The largest element is "+ large);
}
}
import java.util.Scanner;
class Average {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int length = input.nextInt();
int[] num = new int[length];
System.out.println("Enter the " + length + " array elements:");
int sum = 0;
int large, small;
for (int i = 0; i < length; i++) {
num[i] = input.nextInt();
sum = sum + num[i];
}
large = small = num[0]; // small should be assigned after num is input
for (int i = 0; i < length; ++i) {
if (num[i] < small) {
small = num[i];
}
if (num[i] > large) {
large = num[i];
}
}
double avg = sum / length;
System.out.println("The sum is " + sum);
System.out.println("The average is " + avg);
System.out.println("The smallest element is " + small);
System.out.println("The largest element is " + large);
}
}
Yea, it's happening because by default your field small is equal to 0.
And now let's look step by step your if statement
if (num[i]<small) {
small = num[i];
}
example for numbers: 22,11,6,
So first step is num[0] < 0, why 0 as mention before small = 0 by default
Step two num[1] < 0, small stills stay 0
Step Three num[2] < 0, small stills stay 0.
What are you missing, you need to assign value to small at the first iteration of your for loop, for example:
for (int i=0; i<length; ++i) {
if(i == 0){
small = num[i];
}
if (num[i]<small) {
small = num[i];
}
if(num[i]> large) {
large = num[i];
}
}
Now your program should work :)
if you use java 8 or above, you can use the stream method of Arrays. it simplifies work with arrays. for more info
firstly import the Arrays as import java.util.Arrays;
System.out.println("The sum is " + Arrays.stream(num).sum());
System.out.println("The average is " + Arrays.stream(num).average());
System.out.println("The smallest element is " + Arrays.stream(num).min());
System.out.println("The largest element is " + Arrays.stream(num).max());
I have some trouble when I try to code a program.
double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0
Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.
Your initial value for minimum is zero, and I assume your data has nothing that is less than zero.
Try setting your min initial value to Double.MAX_VALUE
you Initializing max and min before entering number into the array , when tring to find the max and the min , first enter the numbers to the array then compare them with the array[0].
second thing is that you dont need to for loops to check whether you need to change max or min , you can do it in one for loop .
try this :
double array[] = new double[10];
int i;
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
double max = array[0], min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Two simple corrections:
You just have to set initialized min and max to some values in array. (e.g. array[0] for your problem)
there is no need to 3 for loops to find the min and max, just use one.
see below code:
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
System.out.println("Give the " + (1) + " number") ;
array[0] = input.nextDouble();
double max = array[0], min = array[0];
for (i = 1; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
if(array[i] > max)
max = array[i] ;
if (array[i] < min)
min = array[i];
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Your curly braces are not proper. You are ending the max loop before the SYSOUT.
double max = 0, min = 0;
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
for (i = 0; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
}
max = array[0];
min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Run this. It will give the proper result.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[]arr1 = new int[max+1];
int[]arr2 = new int[max+1];
int[]arr3 = new int[max+1];
int i = 1;
// For-loop to calculate
for (i = 1;i <= max;i++)
arr1[i] = arr1[i-1] + i;
i = 1;
// While-loop to calculate
while (i <= max) {
arr2[i] = arr2[i-1] + i;
i++;
}
i = 1;
// Do-While-loop to calculate
do
arr3[i] = arr3[i-1] + i;
while (++i <= max);
for (i = 0; i <= max; i++)
System.out.println("Arr1 " + arr1[i] + " Arr2 " + arr2[i] + " Arr3 " + arr3[i]);
System.out.println("Sum of All is " + arr1[max]);
}
I have this for doing sums but I am stuck when it comes to getting it to square
You seem to have 3 identical array objects?
Anyway, it's pretty straightforward to print the square of all numbers from 1 to max:
for (int i = 1; i <= max; i++) {
System.out.println(i + ": " + i * i);
}
There are also some fun ways to sum up the numbers from 1 to max, such as:
System.out.println(IntStream.range(1, max + 1).sum());
I'm new to Java and I'm trying to make a program that allows the user to input 100 numbers and if the user writes '0', then the program is suppose to print the smallest, largest, sum and all the numbers. I got all that to work but not to exit and print it all. My teacher said something about using a while loop, but how is that possible when you have a for loop?
Regards
public static void main(String[] args) {
int[] list = new int[100];
int min = 0;
int max = 0;
int sum = 0;
boolean first = true;
Scanner scan = new Scanner(System.in);
while(list[i] != 0) {
for (int i = 0; i < list.length; i++) {
System.out.print("Enter number (0 to exit) " + (1 + i) + ":");
list[i] = scan.nextInt();
}
for (int i = 0; i < list.length; i++) {
if (first == true) {
min = list[i];
first = false;
}
if (list[i] < min) {
min = list[i];
}
else if (list[i] > max) {
max = list[i];
}
sum = list[i] + sum;
}
if (list[i] == 0) {
System.out.print("Numbers are: " + list[0] + ", ");
for (int i = 1; i < list.length; i++)
System.out.print(list[i] + ", ");
System.out.println();
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + min);
System.out.println("Sum is: " + sum);
}
}
}
}
You only need one while loop to do this and additionally a for loop just to print the array if you want:
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int maxValue = Integer.MIN_VALUE;
int[] history = new int[100];
System.out.println("INPUT:");
int option = scan.nextInt();
while (option != 0 && i <= 100)
{
if (option > maxValue)
maxValue=option;
sum += option;
history[i] = option;
option = scan.nextInt();
i++;
}
System.out.println("OUTPUT: \n" + "SUM: " + sum + "\n MAX VALUE: " + maxValue);
for (int x : history)
System.out.print(x + "");
Here's the body of the method which will do what you've been asked. I have not used a while loop (but in fact, a for-loop is a kind of a while-loop internally).
int size = 100; // Set the number of numbers to input.
int[] list = new int[size]; // Create an array with 'size' elements.
int min = Integer.MAX_VALUE; // Set the highest possible integer as start value.
int max = 0; // Set the minimum to zero, assuming that the user won't input negative numbers.
int sum = 0; // Initialize the sum of the numbers in the list.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < size; i++) { // Run 'size' times the process of inputting a number.
System.out.print("Enter number (0 to exit) " + (i + 1) + ": ");
int number = scan.nextInt();
if (number == 0) { // Quit program if input equals '0'
System.out.println("Exiting...");
break;
}
list[i] = number; // Add the current number to the list
sum += number; // Add the number to the total
if (number < min) { // If the number is smaller than the previous one, set this number as the smallest
min = number;
}
if (number > max) { // If the number is greater than the previous smallest number, set this number as the greatest
max = number;
}
}
// Output all numbers in the list
for (int i = 0; i < list.length; i++) {
if (list[i] != 0) {
System.out.print((i == 0 ? "" : ", ") + list[i]);
}
}
// You see the snippet (i == 0 ? "" : ", ")
// That is a shorthand if-else statement:
// If i equals 0, then "" (empty string), else ", " (comma and space).
// The statement
// System.out.print((i == 0 ? "" : ", ") + list[i])
// is the same as
// if (i == 0) {
// System.out.println("") + list[i];
// }
// else {
// System.out.println(", ") + list[i];
// }
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + max);
System.out.println("Sum is: " + sum);
You have muddled code. Better to use a pattern like this:
while (true) {
// read next
if (input == 0)
break;
}
Doing a rather large assignment for my java class. I've written the entire program, but I've run into one last problem, there needs to be a check on the user input into the array to make sure it is an integer that the user is inputting, and not junk(a, Z, 2.0, #%&##%*#%^, etc.) and if that error happens, it has to loop back, reallowing the input with an error message until they comply.
I've heard of using try/catch to try as a solution, and I've also thought of maybe a while loop, but still not sure on how to go about it. Any tips?
import java.util.Scanner;
import java.util.Arrays;
public class Assignment6 {
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
public static double average(int[] array) {
double sum = 0, average = 0;
for (int i = 0; i < array.length; i++) {
sum = sum + array[i];
average = sum / array.length;
}
return average;
}
public static double Median(int[] array) {
int Median = array.length / 2;
if (array.length % 2 == 1) {
return array[Median];
} else {
return (array[Median - 1] + array[Median]) / 2.0;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter size of array: ");
int[] array = new int[input.nextInt()];
for (int i = 0; i < array.length; i++) {
System.out.print("Enter value #" + (i + 1) + ": ");
array[i] = input.nextInt();
}
System.out.println("\nYour data is:");
for (int i : array)
System.out.print(i + "\n");
System.out.println();
System.out.println("Average is : " + average(array));
System.out.println("Smallest value is: " + getMinValue(array));
System.out.println("Largest value is: " + getMaxValue(array));
System.out.println("\nYour sorted data is: ");
Arrays.sort(array);
for (int i = 0; i < array.length; i++)
System.out.println(array[i]);
double Median = Assignment6.Median(array);
System.out.println("\nThe median is: " + Median);
int Range = Assignment6.getMaxValue(array) - Assignment6.getMinValue(array);
System.out.println("\nThe range is: " + Range);
double midRange = (Assignment6.getMaxValue(array) + Assignment6.getMinValue(array)) / 2.0;
System.out.println("\nThe Midrange is: " + midRange);
}
}
Since you used Scanner.nextInt(), it is not possible that non-integer input was added to the array. Additionally, it is not possible that a non-integer value got into your int[]. The program would likely not compile, and even if it did, would throw a run-time exception.
However, if the user inputs a non-integer, your program will crash. It doesn't really have anything to do with an array, but I'm guessing this is what you meant by your question. The correct way to safely read only integer input from the user with a Scanner would be:
for (int i = 0; i < array.length; i++) {
System.out.print("Enter value #" + (i + 1) + ": ");
while (!input.hasNextInt()) { // <-- 'peeks' at next token
System.out.println("Please enter an integer!");
input.next(); // <-- skips over invalid token
}
array[i] = input.nextInt();
}
You can also use Integer.parseInt(yourString) and it will throw a NumberFormatException if the String is not a valid