I have to save 10 numbers entered by a user into an array using a for loop. After that, I have to use an enhanced for loop to find the largest and smallest values in the array. I don't know how to save numbers in an array. I also have problems finding the smallest and largest values from the array and displaying them. I got an error on the for loop section where I set highestvalue and lowestvalue=inputnumber.
Here is my code:
import java.util.Scanner;
public class ArrayTester
{
public static void main(String[] args)
{
//create a scanner object
Scanner input= new Scanner (System.in);
//declare largestNumber
int largestNumber;
//declare smallestNumber
int smallestNumber;
//declare inputNumber
int inputNumber = 0;
//declare array named number and set it to 10
int[] number = new int[10];
//display message
System.out.print ("Enter an integer: ");
//column headings
for (int counter = 0; counter < number.length; counter++)
{
//set number equal to next input
inputNumber = input.nextInt();
number[inputNumber] = inputNumber;
//for (number[inputNumber]>=largestNumber && number[inputNumber]>=smallestNumber)
//{
//largestNumber=inputNumber;
//smallestNumber=inputNumber;
//}
}
System.out.printf("%s%8s\n", "index", "value");
System.out.printf("%5d%8d\n", counter, number[inputNumber]);
System.out.printf("The largest value in the array is %d\nThe smallest value in the array is %d\n", largestNumber, smallestNumber);
}
}
Replace
number[inputNumber] = inputNumber;
with
number[counter] = inputNumber;
and thats it. As for finding mix and max, use Collections.sort() on your array. First element will be min, and the last max.
Change
number[inputNumber] = inputNumber;
to
number[counter] = inputNumber;
You want to add each new number to the counter position of the array.
As for finding the minimum, maximum. The same loop that reads the inputs into the array can do that. Initialize largestNumber to Integer.MIN_VALUE and smallestNumber to Integer.MAX_VALUE. Then, each time you get a new number, compare it to both largestNumber and smallestNumber, and update them if the new number is higher/lower respectively.
assuming that you don't have to store the numbers in the same order in which they were entered by the user, you would make a sorted insert. that means, for each value entered, find the index at which this number can be inserted while maintaining a sorted array (if there exists a number at this index you have to move it move it to the right)
provided a sorted array you can find min and max in O(1):
min = number[0];
max = number[n-1];
make the following changes
//create a scanner object
Scanner input= new Scanner (System.in);
//declare largestNumber
int largestNumber;
//declare smallestNumber
int smallestNumber ;
//declare inputNumber
int inputNumber = 0;
//declare array named number and set it to 10
int[] number = new int[10];
//display message
System.out.print ("Enter an integer: ");
//column headings
for (int counter = 0; counter < number.length; counter++)
{
//set number equal to next input
inputNumber = input.nextInt();
number[counter] = inputNumber;
// for loop that will check for largest and smallest no
}
smallestNumber = number[0];
largestNumber = number[0];
for(int i=1; i< number.length; i++)
{
if(number[i] > largestNumber)
largestNumber = number[i];
else if (number[i] < smallestNumber)
smallestNumber = number[i];
}
// System.out.printf("%s%8s\n", "index", "value");
// System.out.printf("%5d%8d\n", counter, number[inputNumber]);
System.out.printf("The largest value in the array is %d\nThe smallest value in the array is %d\n", largestNumber, smallestNumber);
Also: you cannot use a for loop in this way
for (number[inputNumber]>=largestNumber && number[inputNumber]>=smallestNumber)
this is a conditional case not a loop
I would suggest you to try out this one.Let me know if it works.:-
import java.util.Scanner;
public class Practice {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int num[]=new int[10];
int max=0,min=0;
for(int i=0;i<10;i++){
System.out.println("Enter number:-");
num[i]=in.nextInt();
if(num[i]>=max)
max=num[i];
if(num[i]<=min)
min=num[i];
}
min=num[0];
for(int i=0;i<10;i++){
if(num[i]<=min)
min=num[i];
}
System.out.println("The array elements are:-");
for(int i=0;i<10;i++)
System.out.print(num[i]+" ");
System.out.println();
System.out.println("Largest is:-"+max+" "+"Smallest is:"+min);
}
}
Related
I am trying to find the largest number in an array of 10 numbers. Here is my code:
public static void getNumber() {
int NumbersArray[] = new int[11];
int num1;
int num2;
int largestNumber = 0;
Scanner scanner = new Scanner(System.in);
for(int i=1; i<11; i++){
System.out.println("Enter number " + i );
int no1 = scanner.nextInt();
NumbersArray[i] = no1;
}
scanner.close();
for(int i=1; i<11; i++)
{
System.out.println(NumbersArray[i]);
num1 = NumbersArray[i];
for(int j=10; j>0; j--)
{
num2 = NumbersArray[j];
if(num1>num2){
largestNumber = num1;
}
}
}
System.out.println("the largest number is " + largestNumber);
}
I found a real simple soultion to this here.
But the reason I am posting this is to find out what mistake have I made.
The first portion gets 10 numbers from the users and the second portion is my code to find the largest number.
Going off Pshemo's suggestion, keep a record of the largest int as the user is typing. This reduces the size of your method by half and makes it much simpler and more readable.
Program with 0-based indexing. So use int NumbersArray[] = new int[10] instead of int NumbersArray[] = new int[11]. When you declare the size of your array, simply put your desired size, you don't have to worry about 0 indexing or anything. For your for-loop, start at int i=0 and end at i<10.
public static void getNumber(){
int NumbersArray[] = new int[10];
int largestNumber = 0;
Scanner scanner = new Scanner(System.in);
for(int i=0; i<10; i++){
System.out.println("Enter number " + i );
int no1 = scanner.nextInt();
NumbersArray[i] = no1;
if(no1 > largestNumber)
largestNumber = no1;
}
scanner.close();
System.out.println("The largest number is: " + largestNumber);
}
The problem is that you are iterating through the list twice (in a nested way). Let's say you have the following numbers: [5, 7, 3, 4]. As you go through the inner loop the first time you'll end up comparing numbers against 5. Only 7 is larger so largestNumber will be set to 7. Then you'll go through again, this time comparing against 7. Nothing is larger than 7, so it'll be left alone. Next you'll compare against 3. The last comparison there is 3 vs. 4, and since 4 is larger you end up setting largestNumber to 4, which is incorrect.
These lines:
for(int i=1; i<11; i++)
{
System.out.println(NumbersArray[i]);
num1 = NumbersArray[i];
for(int j=10; j>0; j--)
{
num2 = NumbersArray[j];
if(num1>num2){
largestNumber = num1;
}
}
}
Don't search for the largest number in the array, but simply search for any value in NumbersArray a value that is bigger than the current element. Thus largestNumber isn't the largest number in the array, but the last number in NumbersArray that is larger than the last element of NumbersArray, unless the last element of NumbersArray is the biggest element, in this case the largestNumber will be the last value in NumbersArray.
A working solution would be:
int max = Integer.MIN_VALUE;
for(int i : NumbersArray)
if(max < i)
max = i;
Though the most efficient solution would be to directly keep track of the currently largest input while reading the input.
And keep in mind that java-arrays are 0-based. This means that the first element is at NumbersArray[0], not NumbersArray[1], like in your code.
As far as I know you can use Java Math max() method to get largest number.
i.e. : dataType max(int number1, int number2), Math.max(number1, number2) gets the maximum between number 1 and 2.
I also want to compare the max number but I am having problems with inserting it in an array - it gives the error:
java.lang.ArrayIndexOutOfBoundsException
Whenever I insert a value larger than 5.
import java.util.Scanner;
public class LargestValue
{
public static void main(String[] args)
{
Scanner sc= new Scanner (System.in);
int a[] = new int[5];
System.out.println ("Enter 5 numbers for comparison ");
for (int j = 0; j < a.length; j++)
{
int inputNumber = sc.nextInt();
a[inputNumber] = inputNumber;
System.out.println(inputNumber);
}
}
}
You should assign the inputs to the j'th position of the array, not to the inputNumber position :
a[j] = inputNumber;
First error is already postet a[j] = inputNumber;
To compare the array you can use Arrays.sort(a);
Arrays.sort(int): Sorts the specified array into ascending numerical order.
To get the max value you can use Arrays.stream(a).max().getAsInt();
The code below works fine for the largest value but for the smallest value it is displaying: smallest number is 0 for any 3 values I input. Would greatly appreciate any help.
import java.util.Scanner;
class MyClass{
public static void main(String[] args) {
// declare and create array object
// declare smallest and largest int variables
int[] numbers;
numbers = new int[3];
int smallest = numbers[0], largest = numbers[0];
// create Scanner object
Scanner input = new Scanner(System.in);
// prompt user
System.out.print("Please enter 3 numbers: \n");
// use for loop to obtain user input
for (int counter = 0; counter < numbers.length; counter++) {
numbers[counter] = input.nextInt();
} // end obtaining input
// for loop to find largest and smallest values
for (int i=0 ;i< numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
} // end finding smallest
if (numbers[i] > largest) {
largest = numbers[i];
} // end finding largest number
}
System.out.println("largest number is "+largest);
System.out.println("smallest number is "+smallest);
}
}
Smallest is always initialized as 0 here: int smallest = numbers[0]. Unless the user enters a value smaller than 0, smallest value will stay 0. Use Integer.MAX_VALUE (int smallest = Integer.MAX_VALUE) instead to ensure that the smallest number will actually be selected.
You're initializing smallest to 0, so if none of the numbers in the array are less than 0, you'll still get 0 as the result. Instead initialize it to Integer.MAX_VALUE, which is the highest value the integer datatype can have.
public static void getMaxMin(int a, int b, int c){
int max=a;
int min=a;
if(b>max){
max=b;
}
if(c>max){
max=c;
}
if(b<min){
min=b;
}
if(c<min){
min=c;
}
System.out.println("min="+min);
System.out.println("max="+max);
}
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
// declare and create array object
// declare smallest and largest int variables
int[] numbers;
numbers = new int[3];
// create Scanner object
Scanner input = new Scanner(System.in);
// prompt user
System.out.print("Please enter 3 numbers: \n");
// use for loop to obtain user input
for (int counter = 0; counter < numbers.length; counter++) {
numbers[counter] = input.nextInt();
} // end obtaining input
//Use in built Math.min and Math.max to get smallest and largest numbers
System.out.printf("%s: %d%n", "smallest number is ", Math.min(numbers[0], Math.min(numbers[1], numbers[2])));
System.out.printf("%s: %d%n", "largest number is ", Math.max(numbers[0], Math.max(numbers[1], numbers[2])));
}
}
I'm trying to create a code that lets the user determine the size and elements of an array and then print it out. So far I have this.
import java.util.Scanner;
public class test3 {
public static void main (String[] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
System.out.println(values[i]);
}
}
}
I don't know if it is right because when a user inputs the size and then the elements, the code is just displaying the element as the user inputs it. For example,
input how many numbers you want to find the median for
5
please enter 5 numbers
3//user input
3//what is displayed.
I want to make it so that the user inputs all of their numbers and THEN it displays the inputed numbers as an array.
We are not allowed to use the array class by the way.
import java.util.Scanner;
public class test3 {
public static void main (String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
}
for (int i = 0; i < num; i++) {
System.out.println(values[i]);
}
}
}
Your for loop will execute for as many number as the user has entered, in your test case 5. Every iteration will take a number from the keyboard input, place it into the array and display it. Since you want to capture all the numbers first and then want to display them you should remove
System.out.println(values[i]);
from the for loop and place that into another for loop to display the numbers like so
for(int x=0 ;i < num ; i++)
{
System.out.println(values[x]);
}
This way the first loop will gather all the numbers and after the numbers are collected the second loop will display the numbers one by one iterating over the array.
Hope this helps!
I am new to java and I would like to store inputted data on an array. My goal is to store the student's grades. So far, this is my code.
import java.util.Scanner;
public class GradesArray {
public static void main (String[]args){
int numStudents = 0;
double grades[]= new double[0];
double gradesStudent;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of students: ");
numStudents = in.nextInt();
for (int i = 1;i<=numStudents;i++){
System.out.print("Enter the grade of student "+i+" : ");
gradesStudent = in.nextInt();
grades[i]=gradesStudent;
}
}
}
so my problem is. I get this error.
`Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GradesArray.main(GradesArray.java:14)`
There are 2 issues here. First:
double grades[]= new double[0];
You have made the array size 0 (new double[0];). However, you ask the user what size you want it to be. So let's declare this variable when you get that first user input:
System.out.println("Enter the number of students: ");
numStudents = in.nextInt();
double grades[]= new double[numStudents];
Second your loop is wrong. Java starts it's indexes for arrays at 0 (not 1). Say you have size N array, then the indexes are 0 to N-1. Change your loop from:
for (int i = 1;i<=numStudents;i++){
//code
}
To:
for (int i = 0;i < numStudents;i++){
//code
}
You are almost there. You are creating an array of length 0 (new double[0]), you must use the inputed value numStudents to create the array:
double grades[] = new double[numStudents]; // You must specify the length inside []
Note that you will have to create the array after you have received the input in
numStudents = in.nextInt();
Also, remember that indexes in Java starts in 0, so your for loop should start with 0 and end in numStudents - 1. In other words i < numStudents:
for (int i = 0; i < numStudents; i++) {
... // modify the necessary
}
First of all, why are you doing this:
double grades[]= new double[0];
↑
This is not the default values of the array, it's its size, you should fix it to be the number of grades you want to store. You are getting the exception because your array can have only 0 elements.
Second, arrays are zero-based in Java. This line
for (int i = 1;i<=numStudents;i++){
Should be
for (int i = 0;i<numStudents;i++){
↑ ↑
The below statement is problematic and it would create an array of 0 elements :
double grades[]= new double[0];
Instead use this :
double grades[]= new double[numStudents];
Please edit your code:
double grades[]= new double[numStudents];
And change the for command to this
for (int i = 1;i < numStudents;i++){
}
loop was outofbound
Compare with your code:
int numStudents = 0;
double gradesStudent;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of students: ");
numStudents = in.nextInt();
double grades[]= new double[numStudents];
for (int i = 0;i<=numStudents-1;i++){
System.out.print("Enter the grade of student "+(i+1)+" : ");
gradesStudent = in.nextInt();
grades[i]=gradesStudent;
}
}