How to turn an array of Strings into an Array of Ints? - java

I'm new to Java programming, but after looking around on this site, I'm fairly certain this should work.
public static int[] ArrayStringToArrayInt(String[] arrayString) {
int[] arrayInt = new int[arrayString.length]; //Array of Ints for output
for (int i = 0; i <= arrayString.length; i++ ) { //Run through the
arrayInt[i] = Integer.parseInt(arrayString[i]); //array, Parsing each
} //item into an int
return arrayInt;
}
What I want this method to do is take an input array: ["1","2","3"] with each item being a string
and return [1,2,3] where each item is an int.
I'm calling the method with this code
int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);
In this case, toBeSorted is both being declared here and initialized at the same time.
Whenever I try to run this I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at sorter.Sorter.ArrayStringToArrayInt(Sorter.java:31)
at sorter.Sorter.main(Sorter.java:22)
Java Result: 1
Line 31 is the body of my For loop, the part that does the parsing, and line 22 is the place where the method is called.
The reason I need this is because I'm trying to take an input from the user, with the Scanner class and want them to be able to enter many numbers at the same time. I then use a delimiter pattern to turn the input into an array. While that seems fine, I could only figure out how to make the input be an array of strings, not ints, which is my problem.
So I guess what I'm asking is
1) why does my code not work?
and
2) is there an easier way to take an input from the user and turn it into an array of ints than this?
For those who would like to see my entire code, here it is
The bit in the middle with the test variable and the adding of two numbers is just a way for me to test my code and see if it worked. It should show the result of adding the first two numbers in the list that you entered
package sorter;
import java.util.Scanner;
import java.util.Arrays;
public class Sorter {
public static void main(String[] args) {
Scanner userInput = new Scanner( System.in );
System.out.println("Enter a list to be sorted, seperate numbers by commas:");
String input = userInput.nextLine(); //Gets aan input as a String
String delims = "[,]+"; //Use Comma as Delimiter
String[] inputStringArray = input.split(delims); //Parse String and creates
//an array
System.out.println(Arrays.toString(inputStringArray)); //Outputs a string of
//the given array
int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);
int test = toBeSorted[0] + toBeSorted[1];
System.out.println(test);
}
public static int[] ArrayStringToArrayInt(String[] arrayString) {
int[] arrayInt = new int[arrayString.length]; //Array of Ints for output
for (int i = 0; i <= arrayString.length; i++ ) { //Run through the
arrayInt[i] = Integer.parseInt(arrayString[i]); //array, Parsing each
} //item into an int
return arrayInt;
}
}

You got the range of the loop wrong :
for (int i = 0; i <= arrayString.length; i++ )
should be
for (int i = 0; i < arrayString.length; i++ )
The valid indices of the array are between 0 and arrayString.length - 1.
As a bonus, here's a nicer way to achieve the same with Java 8:
public static int[] ArrayStringToArrayInt(String[] arrayString)
{
return Stream.of(arrayString).mapToInt(Integer::parseInt).toArray();
}

Off-by-one error here:
for (int i = 0; i <= arrayString.length; i++ ) {
^
It should be:
for (int i = 0; i < arrayString.length; i++ ) {

This is wrong
for (int i = 0; i <= arrayString.length; i++ )
should be
for (int i = 0; i < arrayString.length; i++ )
The indexes of the array are between the 0 and length -1

Variable i should go from 0 to N-1, N being the length of the array. Java arrays, like C ones are zero-based, which means that you should iterate them from 0 to N-1. So your for should look like this:
for (int i = 0; i < arrayString.length; i++)

You could use a stream:
Arrays.stream(arrayString).mapToInt(Integer::parseInt).toArray()

Simply change this statement
for (int i = 0; i <= arrayString.length; i++ )
To
for (int i = 0; i < arrayString.length; i++ )
It will work fine. ArrayIndexOutOfBoundsException means you're trying to access an index in the array that does not exist.
For example,
int [] a= new int [5];
Then the indices available to me are
a [0], a [1], a [2], a [3], and a [4]
I cannot access
a [5]
And if i try i would get ArrayIndexOutOfBoundsException.
That means array indices start at 0 and go upto array length-1.
Hope this helps.

Related

Filling two new arrays from existing array

I already have one Array with random numbers between 0-999.
I also have created two new arrays, one with correct the size to hold all numbers 0-499, and one with the correct size for numbers 500-999.
Problem is to then loop through the Array holding all numbers and copying the right numbers 0-499 and 500-999 to the new Arrays.
Anyone know the correct way to do this? Have spent many days now trying to figure this out.
What i got so far:
public static void main(String[] args) {
Scanner scannerObject = new Scanner(System.in);
Random generator = new Random();
System.out.print("How many numbers between 0 - 999?" );
int number= scannerObject.nextInt();
int [] total= new int[number];
for(int index = 0; index < total.length; index++ )
{
total[index] = generator.nextInt(1000);
}
System.out.println("Here are the random numbers:");
for(int index = 0; index < total.length; index++ )
{
System.out.print(total[index]+ " ");
}
int lowNumber=0;
int largeNumber = 0;
for(int index = 0; index < total.length; index++ )
{
if (total[index] < 500)
{
lowNumber++;
}
if (total[index] >= 500)
{
largeNumber++;
}
}
System.out.println();
System.out.println(lowNumber);
System.out.println(largeNumber);
int [] totalLownumber = new int [lowNumber];
int [] totalLargeNumber = new int [largeNumber];
for(int index = 0; index < total.length; index++ )
{ // TODO
}
}
2 of the approaches you can take are as follows:
You can go through the initial array, count the elements you have, and use the counter values to define the size of the arrays you need. You then go over the original array once again and copy the elements to their respective array. You can use the counter values once again (you would need to reset them first) to allow you to keep track in which array location will the current number need to go. This should be similar to what you are doing.
Consider using a variable length data structure such as a List (ArrayList in Java). This would allow you to go over your original array and assign the numbers to their respective list (let's call them largeNumberList and lowNumberList). Since these collections have a dynamic size, you would only need to traverse the array once and assign as you go along.
The latter approach is usually what is used more often, however, since it would seem that this question is related to homework, I would recommend you try both approaches and compare them.
Try this:
int lowIndex = 0;
int largeIndex = 0;
for(int index = 0; index < total.length; index++ ) {
if (total[index] < 500) {
totalLowNumber[lowIndex++] = total[index];
} else {
totalLargeNumber[largeIndex++] = total[index];
}

Array error with string

I have an issue with string array where's the program takes the use names the put it in the screen. I did some coding and creating 2D games and android app but the fact I never used array for saving scores or something and now I'm stuck and need to learn it and code below think of it as we are putting degrees for collage students put the error that the array is making an error and I can't figure it out why the full code below:
public static void main(String[] args) {
// TODO Auto-generated method stub
Chatlength = new String[10];
for(i =0; i <= Chatlength.length ; i++){
Scanner s = new Scanner(System.in);
String ss = s.nextLine();
Chatlength[i] = ss;
}
while(true){
if(i > Chatlength.length){
int ints = 0;
while(ints <10){
System.out.println("Name "+ints+": "+Chatlength[ints]);
ints++;
}
}
}
It gives me and error with Chatlength[i] = ss;.
I'm guessing you're getting an ArrayIndexOutOfBoundsException due to your loop bounds:
for(i =0; i <= Chatlength.length ; i++){
That should be:
for (int i = 0; i < Chatlength.length; i++) {
... using a local variable declaration instead of the static variable which I assume you've declared in code that you haven't shown us.
An array of length 10 has valid indexes of 0 to 9 inclusive. It's very rare that you actually want <= for a loop index variable when you're trying to iterate over a collection. (All the standard collections in Java are 0-based, so you pretty much always want to have an exclusive upper bound.)
Additionally, I strongly suggest that you start following Java naming conventions.
The condition is culprit. You are going one plus the size of array.
i <= Chatlength.length
Change it to
i < Chatlength.length
Check your for - loop:
for(i =0; i <= Chatlength.length ; i++)
should be
for(i =0; i < Chatlength.length ; i++)
you didn't declare the array first:
Chatlength = new String[10]; //Wrong code;
change it to :
String[] Chatlength = new String[10];
then java is zero based and you should use this:
for(i =0; i < Chatlength.length ; i++)
There is no such index i=10 for the array you created, as per your condition in loop, it allows i=10 (i<= Chatlength.length) which is not a valid array location hence you got the exception

Java loop output keep on repeating

String[] month = {"Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec"};
int[] monthArray = new int[12];
String[][] itemArray = new String[12][10];
Variables
monthArray[i] = input.nextInt();
itemArray[monthArray[i]-1][e] = input.next();
Store a maximum of 5 String values on user input's month.
for(int i=0;i<e;e++){
System.out.println(itemArray[monthArray[i]-1][i]);
}
Having a problem displaying the String values (it just keep repeating the first String value) under user input's month.
You are increasing e instead of i in the last loop. e is the limit and not the variable you use for the iteration and thus the loop will not terminate until you overflow int.
for(int i = 0; i < e; i++ /* Note the usage of i here*/) {
use i++ instead of e++
here e stands for the limit
and i stands for the variable.
Since you have a 2D array, maybe you want something more like this, to print out the values, once, the array has been populated.
String[][] itemArray = new String[12][10];
for(int i = 0; i < itemAreray.length; i++){
for (int j = 0; j < itemArray[i].legnth; j++){
System.out.println(itemArray[i][j]);
}
}
Unless you're having difficulty populating the array. Then that's a different problem

ArrayIndexOutOfBoundsException when looping

I'm pretty much a noob to programming but i have researched all over the place and cant find an answer. im using eclipse and every time i run my program it says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at computer.guess(game1player2.java:24)
at game1player2.main(game1player2.java:39)
Here's my code:
import java.util.Scanner;
class computer{
int g = 0;
int[] compguess = new int[g];
void guess(){
int rand;
while(0 < 1){
int i;
rand = (int) Math.ceil(Math.random()*10);
for (i = 1; i < compguess.length; i++){
if(rand == compguess[i]){
break;
}
}
if(i > compguess.length){
g++;
rand = compguess[g];
System.out.println(compguess[compguess.length]);
}
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer();
for(int a = 0; a < 2; a++){
computer1.guess();
for(int n = 0; n <= computer1.compguess.length; n++)
System.out.println(computer1.compguess[n]);
}
{
input.close();
}
}
}
i am now really confused, i am trying to make a computer generate a random number 1-10, but if it is already in the array generates another one.
int g = 0;
int[] compguess = new int[g];
Your array is size 0, so you have no valid entries.
Since you initialized g as zero, your array compguess has a length of zero. Next when you enter your for loop you assign 1 to i which will allow you to enter into the if condition at the end of guess which will try to access element compguess[1] but this cannot exist because the array is of size zero.
You will run into problems if you do not correct the following.
Change: for(int n = 0; n <= computer1.compguess.length; n++)
To: for(int n = 0; n < computer1.compguess.length; n++)
If your array length is 8 then the last item in the array will be index 7, but the <= tells the loop to grab item index 8.
Your compguess has a length of 0, and you are starting your for loop with i = 1, wich is already greater than 0.
compguess is a zero-length array. If you try to index it, you will fall out of the array and hence the ArrayIndexOutOfBoundsException
If your intent is to make the array longer and add a new item to the end of it, you can't do that. I'm guessing that this is what you were trying to do here:
rand = compguess[g];
First of all, if the language did allow it, you'd want to write it the other way:
compguess[g] = rand;
because you're trying to put a value into a new element of the array, not read from the array. This would actually work in some languages (JavaScript, Perl, others). In Java, however, when you create an array object with something like new int[], the size is fixed. You can't make it longer or shorter.
You probably want to use an ArrayList, which does let you create an array that you can make longer. See this tutorial.

Where does this program get its numbers from, and why is this caused by increasing 1 array size? (Java)

This program simply is supposed to eliminate duplicates from an array. However, the second for loop in the eliminate method was throwing an out of bounds exception. I was looking and couldnt see how that could be, so I figured I would increase the array size by 1 so that I would get it to work with the only downside being an extra 0 tacked onto the end.
To my surprise, when I increased tracker[]'s size from 10 to 11, the program prints out every number from 0 to 9 even if I dont imput most of those numbers. Where do those numbers come from, and why am I having this problem?
import java.util.*;
class nodupes
{
public static void main(String[] args)
{
int[] dataset = new int[10];
//getting the numbers
for (int i = 0; i <= 9 ; i++)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a one digit number");
dataset[i] = input.nextInt();
}
int[] answer = (eliminateduplicates(dataset));
System.out.println(Arrays.toString(answer));
}
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[11];
int arraysize = 1;
for(int k = 0; k <= 9; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
for(int l = 0; l <= arraysize; l++)
{
if(tracker[l] == true)
{
singles[l] = l;
}
}
return singles;
}
}
The exception was occuring at this part
if(tracker[l] == true)
but only when trackers size was 10. At 11 it just prints [0,1,2,3,4,5,6,7,8,9]
EDIT: The arraysize = 1 was a hold over from debugging, originally it was at 0
EDIT: Fixed it up, but now there is a 0 at the end, even though the array should be getting completely filled.
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[10];
int arraysize = 0;
for(int k = 0; k < numbers.length; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
int counter = 0;
for(int l = 0; l < arraysize; l++)
{
if(tracker[l] == true)
{
singles[counter] = l;
counter++;
}
}
return singles;
}
Since arrays start at 0, your arraysize will be one larger than the number of unique numbers, so your final loop goes through one too many times. In other words "l" (letter l -- try using a different variable name) will get to 11 if you have 10 unique numbers and tracker only has item 0-10, thus an out of bounds exception. Try changing the declaration to
int arraysize = 0;
Once again defeated by <=
for(int l = 0; l <= arraysize; l++)
An array size of 10 means 0-9, this loop will go 0-10
For where the numbers are coming from,
singles[l] = l;
is assigning the count values into singles fields, so singles[1] is assigned 1, etc.
Edit like 20 because I should really be asleep. Realizing I probably just did your homework for you so I removed the code.
arraySize should start at 0, because you start with no numbers and begin to add to this size as you find duplicates. Assuming there was only 1 number repeated ten times, you would've created an array of size 2 to store 1 number. int arraysize = 0;
Your first for loop should loop through numbers, so it makes sense to use the length of numbers in the loop constraint. for( int i = 0; i < numbers.length; i ++)
For the second for loop: you need to traverse the entire tracker array, so might as well use the length for that (tracker.length). Fewer magic numbers is always a good thing. You also need another variables to keep track of your place in the singles array. If numbers was an array of 10 9s, then only tracker[9] would be true, but this should be placed in singles[0]. Again, bad job from me of explaining but it's hard without diagrams.
Derp derp, I feel like being nice/going to bed, so voila, the code I used (it worked the one time I tried to test it):
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[10];
int arraysize = 0;
for(int k = 0; k < numbers.length; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
for(int l = 0, count = 0; l < tracker.length; l++)
{
if(tracker[l] == true)
{
singles[count++] = l;
}
}
return singles;
}
I feel you are doing too much of processing for getting a no duplicate, if you dont have the restriction of not using Collections then you can try this
public class NoDupes {
public static void main(String[] args) {
Integer[] dataset = new Integer[10];
for (int i = 0; i < 10; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a one digit number");
dataset[i] = input.nextInt();
}
Integer[] arr = eliminateduplicates(dataset);
for (Integer integer : arr) {
System.out.println(integer);
}
}
public static Integer[] eliminateduplicates(Integer[] numbers) {
return new HashSet<Integer>(Arrays.asList(numbers)).toArray(new Integer[]{});
}
}
To answer your question your final loop is going one index more than the size.
The range of valid indexes in an array in Java is [0, SIZE), ie. from 0 up to arraysize-1.
The reason you're getting the exception is because in your loop you're iterating from 0 to arraysize inclusively, 1 index too far:
for(int l = 0; l <= arraysize; l++)
Therefore when you get to if(tracker[l] == true) in the last iteration, l will equal arraysize and tracker[l] will be outside the bounds of the array. You can easily fix this by changing <= to < in your for loop condition.
The reason that the problem goes away when the size of your array is changed from 10 to 11 has to do with arraysize being incremented up to 10 in the for loop above the one causing the problems. This time, singles[10] is a valid element in the array since the range of indexes in your array is now [0, 11).
EDIT: Actually arraysize has the potential to be incremented to 11, I thought it was initialised to 0 in which case it would only get to 10. Either way the above is still valid; the last index you try and access in your array must be 1 less than the length of your array in order to avoid the exception you're getting, since arrays are zero-based. So yeah, long story short, <= should be <.

Categories