How do you determine the legal index range for an array? - java

I'm learning Java and walking myself through the exercises hosted online at Towson University and I'm stumped on this exercise.
Here is the code:
import java.util.Scanner;
public class Overflow2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[]vals = new int[10];
System.out.println("how many values should be stored in the array? ");
int count = scan.nextInt();
for (int i = 0; i < count; i++) {
vals[i] = count - i ;
}
System.out.println("Which value do you wish to retrieve? ");
int which = scan.nextInt();
System.out.println("Your value is " + vals[which]);
}
}
For the line
for (int i = 0; i < count; i++) {
vals[i] = count - i ;
}
How does one determine the legal index range? I assumed that, given
int[]vals = new int[10];
the index range would be the length of the array - 1, so 9, but this doesn't seem to be correct. The format for the solution is
number -- equality operator -- i -- equality operator -- number
Thanks for any help.

I assumed that ... the index range would be the length of the array - 1, so 9, but this doesn't seem to be correct.
It is correct. The legal indices are 0 through 9, inclusive. The program will only work if the user enters 10 or less. If they enter something bigger than 10 it will crash with an ArrayIndexOutOfBoundsException.
You're only wrong if one is being pedantic about terminology: to be precise, the maximum index is 9. A range would have two endpoints. You could describe the range variously as any of these:
0-9
[0, 10)
[0, 9]
0 ≤ i ≤ 9
0 ≤ i < 10

Related

How to count inputs in an array in java

I have n inputs.
these inputs are numbers from 1 to 100.
I want to output the number that appears less than the other ones; also if there are two numbers with the same amount of appearance, I want to output the number that is less than the other one.
I wrote this code but it doesn't work!
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt(), max=0 , ans=-1;
int[] counter = new int[n];
for(int i=0; i<n; i++)
counter[scanner.nextInt()]+=1;
for(int j=1; j<=100; j++){
if(counter[j]>max)
max=counter[j];
}
for (int i=1; i<=max; i++){
if(counter[i]>0)
if(ans==-1 || counter[ans]>counter[i] || (counter[ans] == counter[i] && i<ans))
ans=i;
}
System.out.print(ans);
There’s a couple of problems with your code, but the main one is the last for loop: You are trying to find the first (ie lowest) number whose counter is equal to max, so your loop should be from 1 to n, not 1 to max.
Another problem is if you are using the number, which is in the range 1-n, as your array index, you need an array of size n+1, not n.
I pinched this from another question regarding the title of yours:
i = input.nextInt (); while (i != 0) { counts [i]++; i = input.nextInt (); } That method increments the number at the position of the user input in the counts array, that way the array holds the number of times a number occurs in a specific index, e.g. counts holds how often 3 occurs.
counter array should contain frequency values for the numbers from 1 to 100 inclusive.
That is, either a shift by 1 should be used when counting the frequency:
int[] counter = new int[100];
for (int i = 0; i < n; i++) {
counter[scanner.nextInt() - 1]++;
}
or 101 may be used as the length of counter array thus representing values in the range [0..100], without shifting by 1.
int[] counter = new int[101];
for (int i = 0; i < n; i++) {
counter[scanner.nextInt()]++;
}
The minimal least frequent number can be found in a single loop (assuming that the counter length is 101).
int minFreq = 101, answer = -1;
for(int j = 1; j <= 100; j++) {
if (counter[j] > 0 && counter[j] < minFreq) { // check valid frequency > 0
minFreq = counter[j];
answer = j;
}
}
System.out.println(answer);
For a wider range of input values (e.g. including negative values) of a relatively small count it is better to use a hashmap instead of a large sparse array.

Keep getting an error when I run this code

I am currently taking Programming 1 and learning Java. Here is my assignment...
Ask user to enter a number and then in a loop, find any 2 numbers that they are the same and next to each other. And then display the number in the loop. For example, if user enters 133455662, the program displays 356. For simplicity, assume user never will enter all three numbers the same and next to each other
Here is the code I've come up with, except I keep getting an error...
public static void main(String[] args){
String num = "";
String result = "";
System.out.println("Enter a number");
Scanner s = new Scanner(System.in);
num = s.next();
int len = num.length();
for(int n = 0;n<len;n++){
char c = num.charAt(n);
char c2 = num.charAt(n+1);
if(c == c2){
result = result + c;
}
}
System.out.println(num);
}
This is the error I get...
run: Enter a number 001123455 Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range:
9 at java.lang.String.charAt(String.java:658) at
CS120_Labs.Homework09_C.main(Homework09_C.java:18)
C:\Users\Fletcher\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1 BUILD FAILED (total time: 6 seconds)
Thanks again for anyone that can help!
Exception said that StringIndexOutOfBoundsException, so you need two changes to make it work:
Add "-1" to fix error "for (int n = 0; n < len - 1; n++) {"
And also at the end of the program you need change from "num" to "result" System.out.println(result);
public static void main(String[] args) {
String num = "";
String result = "";
System.out.println("Enter a number");
Scanner s = new Scanner(System.in);
num = s.next();
int len = num.length();
for (int n = 0; n < len - 1; n++) {
char c = num.charAt(n);
char c2 = num.charAt(n + 1);
if (c == c2) {
result = result + c;
}
}
System.out.println(result);
}
I think all you need to do is to change your for line like (updated to len-1):
for(int n = 0; n<len-1; n++){
...
}
Change your for loop as
for(int n = 0; n < len - 1; n++)
since you are looking up the character at index n and len+1 in the for-loop body, you should loop from 0 to len-1
In addition to the other answers here that just "give" you the solution, I wanted to add:
This is a common problem when you first start out using structures that are "0" indexed. For example, if we have the letters A-I:
0 1 2 3 4 5 6 7 8
A B C D E F G H I
There are 9 letters there, so length() will return 9. The problem is, the letter at the first position isn't 1, it's 0. If in a loop you count all the way up to 9, the last iteration of the loop's charAt line will say "Take the character at position 9" but 9 is out of range of available positions, hence the exception String index out of range: 9.
This can happen anytime you are referencing an object in a structure that has positional indexes. When you see an exception like this, the first thing to check is why did my code try to access an index that didn't exist. In this case, the answer is the upper bound of the for loop. There are other possibilities; for example, your index variable (in this case i) is modified inside the loop, or if the lower bound is negative.

Algorithm sometimes works

I am currently trying to set up a sorting algorithm for an array that scans for the highest and lowest number and places them into a new array, two at a time. I've noticed that it appears to work only in certain conditions. For example, I can input it as {5, 3, 10, 7} or {3, 5, 10, 7}, but {7, 3, 5, 10} produces an IndexOutOfBoundsException: index 1, size: 1;
Here's the code:
import java.util.Scanner; // program uses class Scanner
import java.util.ArrayList; //helps with arrays
public class ArrayAlg
{
// main method begins execution of Java application
public static void main( String[] args )
{
// create a Scanner to obtain input from the command window
Scanner input = new Scanner( System.in );
boolean AS = false; //array sorted.
int hi = 0; //high number
int low = 100; //set to 100 for logic reasons.
int oldhi = 0;
int oldlow = 0;
int NI = 0;
int addA = 0;
int p = 0; //places, moves right after one scan to place the next int
int n = 1; //number of times, moves left after one to place the next int
String cont = "n";
ArrayList<Integer> IParray = new ArrayList<Integer>(); //input array
ArrayList<Integer> Sarray = new ArrayList<Integer>(); //sorted array
while (cont.equals("n"))
{
System.out.print("Please enter a number for the array: ");
addA = input.nextInt();
IParray.add(addA);
NI++;
System.out.print("\n is that all? (y/n): ");
cont = input.next();
}
for (int c = 0; c < NI; c++) //adds 0 so sorting will be easier
Sarray.add(0); //matches the inputted array
System.out.print("The inputted array: ");
System.out.print(IParray);
System.out.println("");
while (AS == false){
hi = 0;
low = 100;
for (int i = 0; i < IParray.size(); i++)
{
if (IParray.get(i) < low)
low = IParray.get(i);
if (IParray.get(i) > hi)
{
//if (IParray.get(i) > hi) currently commented out, doesn't effect the logic by the looks of it.
hi = IParray.get(i);
}
}//end for
Sarray.set(p, low); //sets the number in the left most position then moves to the right
Sarray.set(Sarray.size() - n, hi); //sets the number to the rightmost position and moves left
p++; //increase place count to the right
n++; //increases the place count to the left
oldhi = IParray.indexOf(hi); //oldhi becomes the index of the recent highest number.
oldlow = IParray.indexOf(low); //oldlow becomes the index of the recent lowest number
IParray.remove(oldhi); //removes the highest number at the index
IParray.remove(oldlow); //removes the lowest number at the index, exceptions occurs right here.
System.out.print("The inputted array: ");//mostly here to see what the inputted array looks like after one iteration
System.out.print(IParray);
System.out.println("");
System.out.print("The sorted array: ");
System.out.print(Sarray);
System.out.println("");
if (IParray.isEmpty() == true) //checks to see if the input array is empty
AS = true;
else
AS = false;
}//end while
} // end method main
} // end class ArrayAlg
Can anyone give me any hints on why this might be occurring? I've been trying this out for the past hour or so. Tried Googling and searching this site for answers but no luck
You are getting the index out of bounds because it is trying to remove an index that does not exist. When it is removing indexes it removes lowest first causing the whole array index to shift downwards. It does not keep it's original index.
[0] = 7
[1] = 3
[2] = 5
[3] = 10
When removing the high number, 10, it becomes:
[0] = 7
[1] = 3
[2] = 5
When removing the low number it becomes:
[0] = 7
[1] = 5
The next loop you remove 7 first leaving only 5 at index 0 but your code is calling to remove index 1 giving you an out of bounds exception.
To fix this, let it dynamically get the index when the remove method is called.
IParray.remove(IParray.indexOf(hi)); //removes the highest number at the index
IParray.remove(IParray.indexOf(low)); //removes the lowest number at the index
You should have been able to quickly find this error by running your code in debugging mode and then stepping through the code that is throwing the exception (Line 73).
You might not be able to find a higher value and lower value comparison to previous ones. For example, input array was {7, 3, 5, 10}, now hi is 10 and low is 7, they were removed from IParray.
for (int i = 0; i < IParray.size(); i++)
{
if (IParray.get(i) < low)
low = IParray.get(i); // low becomes 3
if (IParray.get(i) > hi) //!!! never able to find a higher value than 10 !!!
{
//if (IParray.get(i) > hi) currently commented out, doesn't effect the logic by the looks of it.
hi = IParray.get(i);
}
}
In that case, low and high points to previous values, which was removed from the array since last iteration, so oldhi and oldlow would be -1, and you got the exception for IParray.remove(-1)
oldhi = IParray.indexOf(hi); // 10 is not in the array anymore, you got -1
oldlow = IParray.indexOf(low);
IParray.remove(oldhi); // you got exception here as you remove(-1)
IParray.remove(oldlow);

Why do arrays do not accept input greater than their length?

I have noticed when inputting an integer into an array that if the integer is larger than the arrays length it will throw an out of bounds exception. Why is this? Why can the array not accept any integer value? How can I correct this when I need to store integers larger than an arrays length.
Thank you!
Here is the code. When I enter an integer greater than 5 I get an out of bounds exception. If I enter integers less than 5 the code works perfectly.
public class NumOfOccur
{
static Scanner input = new Scanner(System.in);
static int[] cards = new int[5];
static int[] numOccurence = new int[5];
public static void main(String[] args)
{
System.out.println("Enter five values: ");
for (int i = 0; i < 5; i++)
{
System.out.print("Card " + (i + 1) + " : ");
cards[i] = input.nextInt();
}
containsPair(cards);
}
public static boolean containsPair(int hand[])
{
for (int i = 0; i < hand.length; i++)
numOccurence[hand[i]]++;
for (int i = 1; i < numOccurence.length; i++)
{
if (numOccurence[i] > 0)
System.out.println("The number " + i + " occurs " + numOccurence[i] + " times.");
}
return false;
}
}
What you are suggesting here is wrong. An array of integers can hold any integer. When you are storing an integer into an array (or any value for that matter) you have to make sure that the index you are inserting it into is valid.
For example
//perfectly valid
int[] foo = new int[1];
foo[0] = 500;
I suspect what you are doing is something like this.
//throws index out of bounds exception
int[] foo = new int[1];
foo[500] = 500;
Note the difference here. the number inside the [] on the left side of the assignment operator indicate the index you are working with.
Based on your now posted code, your problem is here:
for (int i = 0; i < hand.length; i++)
numOccurence[hand[i]]++;
To briefly explain what is going on.
1) you first initialize numOccurence to a length of 5 integers.
2) You are putting user input into the cards[] then you pass the cards array into into the function containsPair()
3) If the user enters a number greater than 5, lets say 7 the operation hands[i] would be 7. This would be the same as numOccurence[7] which is out of bounds
Without any code, I'm assuming you're just misunderstanding what you're doing with your array. You just have to make sure you're accessing a valid index. There's no restriction on what integer you can store in an integer array.
// Make an array of length ten
int[] myIntArray = new int[10];
System.out.println(myIntArray.length);
// Set the first value in the array to 99: perfectly legal
myIntArray[0] = 99;
System.out.println(myIntArray[0]);
// The following line throws ArrayIndexOutOfBoundsException
myIntArray[99] = 100; // The last index in the array is only 9, not 99!
System.out.println(myIntArray[99]); // This line would also crash, for the same reason
Having seen your code, I think the issue is with this:
First, your numOccurence array always has a length of 5, but in the line
numOccurence[hand[i]]++;
You will get the OutOfBoundsException if hand[i] is 5 or greater (meaning you typed in a value of 5 or greater).
To fix this you should either:
Put restrictions on what card values the user can enter
Make that line numOccurence[i]++ if you mean to keep track of the number of times each card position was drawn
Make numOccurence a longer array so it can store the number of times each possible card (e.g. 1 to 13 for Ace to King) has occured.
I'm definitely sure the question is wrong. You're saying this is not possible
int[] anArray = new int[10];
anArray[5] = 20;
Which is obviously not true.
If that's what you're saying, post your code, because you have a bug.
If you want to make your array larger or something, you should consider using an ArrayList or something similar. Post your code so we can help you.

Java: Array Index Out of Bounds Exception

System.out.print("Enter an integer: ");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int lArray = x - 2;
int[] newArray = new int[lArray];
System.out.println("Let's display all possible integers...");
for (int i = 0; i <= newArray.length; i++) {
newArray[i] = i + 2;
System.out.print(newArray[i] + " ");
}
I've just started Java recently, but I sure that if I coded similarly in another language, I would face the same problem. This is an excerpt from an application where it lists all the prime numbers up until the user's input.
The reason why x-2 is used as the definition of lArray is because the length of the array will be all the integers from 2 until the number {2, 3, 4, 5... x}.
I noticed that for the line
for (int i = 0; i <= newArray.length; i++) {
if I change i <= newArray to i < newArray, the code works without error. However, the user's input, x, is left out which is a problem if x is prime.
You should use < and not <= in:
for (int i = 0; i <= newArray.length; i++)
^^
If foo any array, valid index of foo are [0,foo.length-1]
Using foo.length as an index will cause ArrayIndexOutofBoundsException.
And also lArray which contains number of natural numbers <=x but excluding only one number 1, its value should be x-1 and not x-2.
Change the array length to (x - 1) instead, and go with the < condition, which you've already found is necessary to avoid the out-of-bounds exception.
The reason you need an array that is 1 element larger than what you're currently using is because there are (n - 1) candidates that must be considered between 2 and n , not (n - 2).
For example, there are two candidates less than or equal to three (2 and 3), both of which, coincidentally, happen to be prime.
for (int i = 0; i <= newArray.length; i++) //should be <, not <=
for (int i = 0; i < newArray.length; i++)
You need to use:
int lArray = x - 1;
And change your condition to use < instead of <=.
In Java as in C/C++, arrays are ZERO based. So your array of N values will go from index 0 to N-1.
Taking your example: {2, 3, 4, 5... x}.
You will need N-1 values to store all positive numbers but 1 in an integer array. So, if N equals to 4, your array will be:
newArray[0] = 2;
newArray[1] = 3;
newArray[2] = 4;
Hence, array lenght must be 3 (N-1).

Categories