Array input only seems to take the last input [duplicate] - java

This question already has answers here:
For-each Loop in Java
(3 answers)
Initializing an array in Java using the 'advanced' for each loop [duplicate]
(5 answers)
Closed 5 years ago.
import java.util.Scanner;
import java.util.Arrays;
public class Sort_Array {
public static void main(String[] args) {
int a;
Scanner sc = new Scanner(System.in);
System.out.println(" Enter size of Array ");
int n = sc.nextInt();
int[] arr_num = new int[n];
System.out.println(" Enter the integers in the Array");
for(int i : arr_num)
{
arr_num[i] = sc.nextInt();
}
System.out.println(" Array before sorting ----\n");
for(int j : arr_num)
{
System.out.print(j+",");
}
System.out.println("\n");
Arrays.sort(arr_num);
System.out.println(" Array after sorting ----\n");
for(int k : arr_num)
{
System.out.print(k+",");
}
}
}
Output
Enter size of Array
2
Enter the integers in the Array
5
6
Array before sorting ----
6,0,
Array after sorting ----
0,6,

Change this:
for(int i : arr_num)
{
arr_num[i] = sc.nextInt();
}
To a traditional for-loop and it should work.
for (int i = 0; i < arr_num.length; i++) {
arr_num[i] = sc.nextInt();
}

You never initialize your array arr_num, so it will be full of zeros
int[] arr_num = new int[n];
....
for(int i : arr_num)
{
arr_num[i] = sc.nextInt();
}
Will then become:
// Pseudocode
for(int i : {0, 0, ... , 0} )
{
arr_num[i] = sc.nextInt();
}
So you will always write to arr_num[0]
You probably want to have this instead:
for(int i = 0; i < arr_num.length; i++)
{
arr_num[i] = sc.nextInt();
}

You are entering elements of array through foreach loop, but the correct way is:
System.out.println(" Enter the integers in the Array");
/*for(int i : arr_num)
{
arr_num[i] = sc.nextInt();
}*/
for(int i=0;i<n;i++){
arr_num[i] = sc.nextInt();
}

System.out.println(" Enter size of Array ");
int n = sc.nextInt();
int[] arr_num = new int[n];
Here you see what is really happening when you have passed the size of the array say, 2
arr_num is getting initialized with 0 value ( which is the default value for int object)
0 0
After this, you have used the for each loop.
Which basically says, When you see the colon (:) read it as “in.” So basically, you are reading each int i in array_num which are 0 0.
for(int i : arr_num)
{
arr_num[i] = sc.nextInt(); //arr_num[0] = sc.nextInt();
//again, arr_num[0] = sc.nextInt();
}
So this is the reason you are getting
6,0
because 5 which was inputted by you is now replaced by 6 again at arr_num[0]. while 2nd 0 still stays which is at arr_num[1].
As other answers suggest, use a different loop. And read more about for each loop.

Related

2D Array with user input and random numbers

I am trying to generate a program that ask the user a number "n" and displays a 2 x n array. E.g:
1 2 3 4 5 (User input)
5 8 2 1 5 (Random numbers)
I can't see to make my code to work. Here is my code:
import java.util.Scanner;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of exits: ");
int n = input.nextInt();
int [][] A = new int[2][n];
for (int i =0; i <= A[n].length; i++){
A[i][n]= (int)(Math.random()*10);
}
System.out.println(A[2][n]);
System.out.print("Distance between exit i and exit j is: " + distance());
}
public static int distance(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter exit i: ");
int i = input.nextInt();
System.out.print("Please enter exit j: ");
int j = input.nextInt();
return i + j;
}
}
I am getting this error
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
5"
How can I fix it?
And I think my Math.random is wrong. Can you guys help me with some advises or where am I doing things wrong?
Thanks.
All your errors lie within and after your for-loop:
for (int i =0; i <= A[n].length; i++){
A[i][n]= (int)(Math.random()*10);
}
If n = 5, A[5].length does not exist, because the first dimensions of your array only exist between 0 and 1. A[2] reserves space for 2 int primitives, the first is at index 0 and the last is at index 1. Even if that is changed, the i variable your for loop declares is incremented beyond 1 and so the JVM will throw a ArrayIndexOutOfBoundsException.
When declaring an array with the dimensions [2][n], (given n is an Integer, which will be provided by the user via the scanner) you cannot access arrayReference[2][x]
Arrays are based on a 0 index structure...
Consider the following:
int [][] A = new int[2][2];
You can only access A[0][0], A[0][1], A[1][0] & A[1][1].
you CANNOT access A[2][0], A[2][1] or A[2][2].
Here's what you need to do:
//A.length will give you the length of the first dimension (2)
for(int i=0; i<A.length; i++){
for(int j=0; j<n; j++){
A[i][j] = (int) (Math.random()*10);
}
}
}
System.out.println(A[1][n-1]);
System.out.print("Distance between exit i and exit j is: " + distance());

How to add last 5 integers inputted from user in java?

int sum = 0;
ArrayList<Integer> num = new ArrayList<Integer>();
for(int i=1;i<=schoolStart;i++)
{
System.out.println("Percentage of students passing in"+" "+i+" is ");
percentageOfPassingStudents = sc.nextInt();
num.add(percentageOfPassingStudents);
int count=0;
for(int j=0;;j++)
{
sum = sum+num.get(j);
}
count++;
}
I want the condition to check whether it is taking the last 5 values of array list.
Thanking in advance.
I would consider using a LinkedList and treat it like a Stack, if you only care about the last 5 integers input.
LinkedList<Integer> myList = new LinkedList<Integer>();
//Always add at the front of the list:
myList.addFirst(new Integer(2));
//asserting there are at least 5 items in the list:
for(int i = 0; i < 5; ++i) {
Integer tmp = myList.removeFirst();
//do stuff
}
Just check if the size of your arraylist is at least as big as the size of the schoolStart - 5 variable.
int sum = 0;
ArrayList<Integer> num = new ArrayList<Integer>();
for(int i=1;i<=schoolStart;i++)
{
System.out.println("Percentage of students passing in"+" "+i+" is ");
percentageOfPassingStudents = sc.nextInt();
num.add(percentageOfPassingStudents);
int count=0;
if(num.size() > schoolStart-5) {
sum = sum+num.get(i-1);
}
count++;
}
Also, I'm not sure what you're trying to do, but this doesn't look like a good solution (to anything) - see avgvstvs solution for a better alternative

Store input data on array

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;
}
}

ArrayIndexOutOfBoundsException Error in my code

Cant find the error in coins array. when i tried to initialize the array with n+10 elements it worked. but actually it should be using only the n elements. where am i getting it wrong?
import java.util.Scanner;
public class MaximumContiguousSum {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int amount, n;
System.out.print("Enter number of types of coins : ");
n = in.nextInt();
int[] coins = new int[n];
System.out.print("Enter coins values : ");
for(int i=0; i<n; i++){
coins[i] = in.nextInt();
}
System.out.print("Enter the amount : ");
amount = in.nextInt();
int[] arr = new int[amount+1];
arr[1]=1; arr[0]=0;
for(int i=2; i<=amount; i++){
arr[i]=100;
int j=0;
//Error in the following line
while(coins[j]<=i && j<n){
arr[i]=min(arr[i], 1+arr[i-coins[j]]);
j++;
}
}
System.out.println("The number of coins to be used : " + arr[amount]);
in.close();
}
private static int min(int a, int b) {
// TODO Auto-generated method stub
return (a<b)?a:b;
}
}
Output:
Enter number of types of coins : 3
Enter coins values : 1 2 7
Enter the amount : 10
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at MaximumContiguousSum.main(MaximumContiguousSum.java:22)
You have an off-by-one error. Your line:
while(coins[j]<=i && j<=n)
Will try to grab coins[n] before it quits, and the final index of your array is actually n-1
Don't check greater than or equal on the error line
change this while(coins[j]<=i && j<n){ to while(coins[j]<i && j<n){ in your code
This
int[] coins = new int[n];
declares coins to have n elements with maximum index n - 1
this
while(coins[j]<=i && j<=n){
arr[i]=min(arr[i], 1+arr[i-coins[j]]);
Will attempt to access coins[n] when j = n which is past the end
Edit: arr[i-coins[j]] is protected against.
finally this:
while(coins[j]<=i && j<n)
should be this
while(j < n && coins[j]<=i)

Java: how do I initialize an array size if it's unknown?

I'm asking the user to enter some numbers between 1 and 100 and assign them into an array. The array size is not initialized since it is dependent on the number of times the user enters a number.
How should I assign the array length?
If user enters 5 6 7 8 9 (5 numbers), then
int[] list;
becomes
int[] list = new int[5];
I'm trying to use a loop, but it won't stop.
int[] integers;
int j = 0;
do {
integers = new int[j + 1];
integers[j] = in.nextInt();
j++;
} while((integers[j-1] >= 1) ||(integers[j-1]) <= 100);
You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.
If you really can't use a List, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList.
I think you need use List or classes based on that.
For instance,
ArrayList<Integer> integers = new ArrayList<Integer>();
int j;
do{
integers.add(int.nextInt());
j++;
}while( (integers.get(j-1) >= 1) || (integers.get(j-1) <= 100) );
You could read this article for getting more information about how to use that.
I agree that a data structure like a List is the best way to go:
List<Integer> values = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values.add(value);
} while (value >= 1) && (value <= 100);
Or you can just allocate an array of a max size and load values into it:
int maxValues = 100;
int [] values = new int[maxValues];
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values[numValues++] = value;
} while (value >= 1) && (value <= 100) && (numValues < maxValues);
If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.
import java.util.Scanner;
public class ArrayModify {
public static void main(String[] args) {
int[] list;
String st;
String[] stNew;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9
st = scan.nextLine();
stNew = st.split("\\s+");
list = new int[stNew.length]; // Sets array size to 5
for (int i = 0; i < stNew.length; i++){
list[i] = Integer.parseInt(stNew[i]);
System.out.println("You Enterred: " + list[i]);
}
}
}
String line=sc.nextLine();
int counter=1;
for(int i=0;i<line.length();i++) {
if(line.charAt(i)==' ') {
counter++;
}
}
long[] numbers=new long[counter];
counter=0;
for(int i=0;i<line.length();i++){
int j=i;
while(true) {
if(j>=line.length() || line.charAt(j)==' ') {
break;
}
j++;
}
numbers[counter]=Integer.parseInt(line.substring(i,j));
i=j;
counter++;
}
for(int i=0;i<counter;i++) {
System.out.println(numbers[i]);
}
I always use this code for situations like this. beside you can recognize two or three or more digit numbers.
int i,largest = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of numbers in the list");
i = scan.nextInt();
int arr[] = new int[i];
System.out.println("Enter the list of numbers:");
for(int j=0;j<i;j++){
arr[j] = scan.nextInt();
}
The above code works well. I have taken the input of the number of elements in the list and initialized the array accordingly.
**input of list of number for array from single line.
String input = sc.nextLine();
String arr[] = input.split(" ");
int new_arr[] = new int[arr.length];
for(int i=0; i<arr.length; i++)
{
new_arr[i] = Integer.parseInt(arr[i]);
}

Categories