I don't understand why this is going out of bounds, can you help me?
What should happen:
user inputs length of list
user inputs all items in the list, only prompted until the user-inputed length of list (a) is reached.
For some reason after the first item in the list it goes out of bounds but I can't tell why.
import java.util.Scanner; //import scanner
public class project2 {
public static void main (String[] args){
Scanner input = new Scanner(System.in); //scanner for input
int a = 0;
double [] lista = new double [a]; //create array
double [] listb = new double [a]; //create array
System.out.println("How long are the lists? ");
System.out.print("(The lists should be the same length): ");
a = input.nextInt();
int count=1;
System.out.println("Enter numbers for list A:");
for(int j = 0; j < a-1 ; j++){ //user input numbers loop into array "list"
System.out.print(count + ": ");
lista[j] = input.nextDouble();
count++;
}
}
}
When you declare your lista and listb arrays, you use a as the length, but at that time, it's 0. You haven't assigned the user's value to a yet.
Create your arrays after you have the length from the input.
a = input.nextInt();
double [] lista = new double [a]; //create array
double [] listb = new double [a]; //create array
you created array with 0 element and if you enter any number for a which is greater than 1 it will attempt to look at index 1 which is out of bound
Related
I am stuck at this part right now with adding the groups together. So like, Array1 A + Array2 A
Array1 B + Array 2 B
This is my code:
import java.util.*;
import java.util.Arrays;
public class Math {
public static final int ARRAY1 = 5;
public static final int ARRAY2 = 5;
public static void main(String[] args) {
int de;
de = 1;
System.out.println("Welcome! This program will assist you in\n 1) Adding groups of numbers\n 2) and subtracting a group of numbers\nPlease enter the number of which you need help with!");
Scanner keyboard = new Scanner(System.in);
op = keyboard.nextInt();
if (op == 1) {
System.out.println("****Addition****\nAwesome! Please insert all the numbers for your first group of numbers!");
System.out.println("Enter "+ARRAY1+"");
int[] array = new int[ARRAY1];
for(int i=0;i<array.length;i++)
{
System.out.println("Enter value "+i);
array[i] = keyboard.nextInt();
}
System.out.println("Great! Now please enter your "+ARRAY2+" other group numbers!");
int[] array1 = new int[ARRAY2];
for(int i=0;i<array.length;i++) {
System.out.println("Enter value "+i);
array1[i] = keyboard.nextInt();
}
}
}
}
Initialize the array of the same size and then loop over adding the elements one by one from the 2 input arrays.
int[] sum_array = new int[ARRAY1]; // initialize the output array
for(int i=0;i<array.length;i++) {
sum_array[i] = array[i] + array1[i]; // adding the elements from two arrays
}
for(int i=0;i<array.length;i++) {
System.out.print(sum_array[i] + " ");
}
System.out.println();
The easiest way to solve this is to create another array, let's call it array3, with the same length as your 2 arrays. Then loop over the array3 and store the sum of array1[index] and array2[index] in the array3[index]
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();
For my program, i am making a 2D jagged array of integers and the length of each array inside depends on the input of the user.
Lets say for something like:
int seq [] [] = new int [M] [];
for(int i = 0; i < M; i++){
seq[i] = new int [N[i]];
The total number of arrays (M) and the N array with length for each array depends on the input by user.
Is there a way i can make this so the resultant 2D array can be used by any method inside the class?
Thanks.
You can make it array an instance variable and initialize it in some init method or constructor.
public class Test{
int[][] array;
public void initialize() {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
array = new int[m][n];
}
public void processArray() {
if(array != null) {
//process array
}
}
}
Yes it is Possible you Take The Size of the Rows and Columns of the Array at run time then Create the Array According to the Size you Provide.
int m;
int n;
System.out.println("EnTer size of Row and column");
m = input.nextInt();
n = input.nextInt();
int[] arr = new int[m][n];
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);
}
}
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;
}
}