This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
public static void selectionShuffle(int[] values) {
Random rand = new Random();
for(int i = values.length; i > 0; i--) {
int r = rand.nextInt(i);
swap(values, r, i);
}
//updated answer to include below method
public static void swap(int[]a, int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
I am writing a card game and need to randomly sort the cards in place, I got an ArrayOutOfBoundsException when I ran the above code, with the compiler complaining particularly about the reassignment from values[i] = values[r] . To be clear, this is , not intended to be a selection sort but instead a selection shuffle. Any help is appreciated!
Alternatively, you may try Collections.shuffle() but it would be more handy if you have to use the wrapper class Integer instead of the primitive type intat first.
Integer[] version:
public static void selectionShuffle(Integer[] values) {
Collections.shuffle(Arrays.asList(values));
}
int[] version:
public static void selectionShuffle(int[] values) {
Integer[] boxedArr = Arrays.stream(values).boxed().toArray( Integer[]::new );
Collections.shuffle(Arrays.asList(boxedArr));
for(int i=0 ; i<values.length ; i++){
values[i] = boxedArr[i];
}
}
Your start condition needs to be values.length-1, as Java arrays are 0 to length-1.
Also the test should be >=0, since as you wrote it'll only go down to index 1.
for(int i = values.length - 1; i >= 0; i--) {
Or as pointed out by Iłya Bursov, you could compare at index i-1 and leave your for loop conditions as you have them. Not sure what's the best form I always do it as in my example above.
Also, you aren't shuffling. You set the value at index i to the one at r, but you lost the value that was previously at i. You need a temp variable to swap the values.
tmp = values[i];
values[i] = values[r];
values[r] = tmp;
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Array Printing Java
(3 answers)
Closed 2 years ago.
I have to use the math.random to populate my array with 25 random integers between the range 10 and 99. I'm also having problems trying to print the array. Instead of the full array being printed, only the memory location is printed. How to I write the command for it to print? This is how I've written my code and I know there's something wrong with it but just done know how to iron it out.
public class Proj5COMP110
{
public static void main(String args[])
{
System.out.println ("Project 5: Quick Sort");
int i;
int mSample [] = new int[25];
for ( i= 0; i< mSample.length ; i++)
{
mSample[25] = (int)(Math.random ()* (99-10)+10);
}
System.out.print(mSample[25]);
}
}
The problem as already mentioned in comments is that you have to change
mSample[25] = (int)(Math.random ()* (99-10)+10);
to
mSample[i] = (int)(Math.random ()* (99-10)+10);
I would like to prefer below code, which is less erroneous and doesn't have any warning.
public static void main(String[] args) {
int[] mSample = new int[25];
for (int loop = 0; loop < mSample.length; loop++)
mSample[loop] = new Random().nextInt(90) + 10;
for (int element : mSample)
System.out.println(element);
}
You are storing values into wrong index. use mSample[i] instead of mSample[25] to store value at index i.
mSample[i] = (int)(Math.random ()* (99-10)+10);
Also don't forget to change this line: System.out.print(mSample[25]); This will give you an indexOutOfBounds exception. Learn why this exception occurred.
public class Proj5COMP110
{
public static void main(String args[])
{
System.out.println ("Project 5: Quick Sort");
int i;
int mSample [] = new int[25];
for ( i= 0; i< mSample.length ; i++)
{
mSample[i] = (int)(Math.random ()* (99-10)+10);
}
for ( i= 0; i< mSample.length ; i++)
{
System.out.print(mSample[i]);
}
}
}
In an array the index starts from 0, therefore you should be able to store from mSample[1-24], mSample[25] would be out of bounds. When you are trying to print mSample[25], it is printing garbage value and not memory address.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I've been trying to dive into java development and have gone for a relatively easy problem of finding prime numbers, however, I keep getting errors and can't see what I've done wrong, any help?
I've been toiling over my computer for an infuriating while and have tried everything, even rewriting the code from beginning
public class HelloWorld{
public static void main(String []args){
int[] check = {2};
//cycle through numbers 1-100
for (int i = 1; i < 100; i++) {
//cycle through numbers to be checked against i
for (int x = 0; x < 101; x++) {
//check if the current itteration of i has no multiples
if (i%check[x] == 0) {
check[i] = i;
} else {
// print any prime numbers
System.out.print(i);
check[i] = i;
}
}
}
}
}
The immediate cause of your error is that you defined the check[] array to have a size of 1, but you are trying to access elements higher than that, which don't exist. However, I don't think that you really need that array here. Consider this version:
for (int i=2; i < 100; i++) {
boolean match = true;
for (int x=2; x <= Math.sqrt(i); x++) {
if (i % x == 0) {
match = false;
break;
}
}
if (match) {
System.out.println("Prime number: " + i);
}
}
Note that the inner loop in x only needs to go as high as the square root of the outer i value. This is because any value greater than sqrt(i) can't possible divide it.
It is because your array has length 1
and you are trying to access out of bound indexes. In case you are lopping 0 to 101 You can initialize your array like this int [] check =new int [101]
This question already has answers here:
How can I convert List<Integer> to int[] in Java? [duplicate]
(16 answers)
Closed 4 years ago.
I am using Intellj Idea and I am playing with ArrayLists, Arrays and a sorting algorithm I want to generate 5 random grades put them into an ArrayList convert the values of the ArrayList into an Array. Sort the Array values from least to greatest and print to screen the grades before and after sort here is what I have:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Arrays;
public class Grades {
public static void main(String args[])
{
ArrayList <Integer> scores = new ArrayList<Integer>();
for(int i = 0; i < 5; i++)
{
scores.add((int) (Math.random() * 30 + 1));
}
for (int i =0; i < scores.size();i++)
{
System.out.println(scores.get(i));
}
int arrayOne[] = new int[scores.size()];
arrayOne = scores.toArray(new int[scores.size()]);
The last line is where I have the problem. Intellij says: no suitable method found for toArray(int[]).
Is my syntax wrong?
Did I forget to import a library?
Is it possible for ArrayLists and Arrays to interact in this way?
Please help.
int first,second, temp=0;
for(first=0; first < arrayOne.length -1; first++)
{
for (second = 0; second < arrayOne.length - 1 - first; second++)
{
if(arrayOne[second] < arrayOne[second +1])
{
temp = arrayOne[second];
arrayOne[second] = arrayOne[second + 1];
arrayOne[second+1] = temp;
}
}
}
I haven't been able to run this bit to see if it sorts the way I want it too yet.
for(int i = 0; i < arrayOne.length; i++)
{
System.out.println(arrayOne[i]);
}
}
}
As you can see from toArray(T[]) contract it takes an array containing a reference type and int is not a reference type.
Change your code as to arrayOne is of type Integer[]
Integer[] arrayOne = scores.toArray(new Integer[scores.size()]);
I have a question about my code.
class Zillion
{
private int[] d;
public Zillion(int size)
{
d = new int[size];
}
public void timesTen()
{
for(int i = 0; i<d.length;i++)
{
d[i] = d[i + 1];
}
d[d.length]=0;
}
public String toString()
{
String num;
num= "";
for(int i = 0; i<d.length; i++)
{
num = num + d[i];
}
return num;
}
}
Here in my class Zillion, I am trying to multiply a number that is represent by an array by 10. So what I did was I move the elements at each index to the left and change the value at the last index to 0. For instance,
0 1 4 8 will be come 1 4 8 0.
I am not sure whether my logic will work but that was my first start.
First, I am trying to change the values at each index of the array with an assigned size and here is my driver file.
class Driver
{
public static void main(String[] args)
{
Zillion z = new Zillion(5);
System.out.println(z); // 00000
for (int j = 0; j <= 5; j += 1)
{
z[j]=j;
}
System.out.println(z);
}
}
However, Java throws me an error and says: "Error:(32, 14) java: array required, but Zillion found".
I took C++ and I believe I could change array values like z[j] = j but I guess it is different in Java.
Is there a way I can change the values of the specific index I want? The reason why I used the for loop is because I could not think of any method that I can use to assign the values at each index I want. Is that possible that in the Driver file I create an array, say, 0148 and call my "timesTen" method to give me what I want?
Thank you!
You need to expose the array d of zillion class using a gettor method.
public getArray(){ return d;}
Instead of z[j]=j; you need to use z.getArray()[j] = j
Also your timesTen method will cause arrayindex out of bounds exception in the line
d[d.length]=0;
Java array is not dynamically growing so, Index should be lesser than array size.
You can't index a class, only arrays.
Define a method in Zillion
class Zillion {
public void set(int index, int value) {
// TODO implement
}
}
In your loop, call z.set(j, j)
Note: j <= 5 will cause an out of bound exception
I believe I could change array values like z[j] = j
You could - if z would be an array! But, as the error message also states, it is an object of type Zillion:
Zillion z = new Zillion(5);
You are using instance z of Zillion class, use array instead of it.
//Create getter method in Zillion Class
public int[] getD() {
return d;
}
//And access that array in Driver Class
int[] array = z.getD();
for (int j = 0; j < 5; j += 1) {
array[j] = j;
}
Moreover, you are going to face an
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
because of the statement d[d.length] = 0; in your timesTen() implementation. You have to replace that line with:
d[d.length-1] = 0;
This is not an answer to your question, because you have already received valuable ones, but I hope it could help you.
I'm trying to write a small program that prints out distinct numbers in an array. For example if a user enters 1,1,3,5,7,4,3 the program will only print out 1,3,5,7,4.
I'm getting an error on the else if line in the function checkDuplicate.
Here's my code so far:
import javax.swing.JOptionPane;
public static void main(String[] args) {
int[] array = new int[10];
for (int i=0; i<array.length;i++) {
array[i] = Integer.parseInt(JOptionPane.showInputDialog("Please enter"
+ "an integer:"));
}
checkDuplicate (array);
}
public static int checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
return 1;
}
}
The simplest way would be to add all of the elements to a Set<Integer> and then just print the contents of the Set.
First of all, the "else if" statement is incorrect, since you don't provide any condition to the if (if you want an if, you need to write "if (condition) ...").
Second, you cannot decide inside the inner loop, if a value should be printed: The way your code works you write a value array[i] for each value array[j] that is different from array[i]!
Third: the inner loop needs only to go from 0 to the outer index i-1: For each element, you need only to decide, if it is the first occurrence (i.e. if the same value occured at any previous index or not). If it is, print it out, if not, ignore it.
A proper implementation of CheckDuplicate() would be:
public static void checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
}
But of course, some kind of Set would be much more efficient for bigger arrays...
EDIT: Of course, mmyers (see comments) is right by saying, that since CheckDuplicate() doesn't return any value, it should have return type void (instead of int). I corrected this in the above code...
Put them in a set ordered by insertion time, then convert back to an array if necessary.
new LinkedHashSet<Integer>(array).toArray()
Try throwing all of the integers into a Set. Duplicates will not ever be added to the Set and you will be left will a set of unique integers.
What you want can be accomplished using Java collection API, but not exactly as an one-liner, due to fact collection methods work with Objects and not primitives. J2SE lacks methods that convert, say, int[] to Integer[], but Apache Commons Lang library contains such useful methods, like ArrayUtils.toObject() and ArrayUtils.toPrimitive().
Using them, method to remove duplicated elements from an integer array looks something like this:
public static int[] removeDuplicates(int... array) {
Integer[] ints = ArrayUtils.toObject(array);
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(ints));
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}
If your application is likely to include more of array/collection manipulation, I suggest you take a look at that library, instead of implementing things from scratch. But, if you're doing it for learning purposes, code away!
It would probably be better to add each number to a Set implementation rather than an array. Sets are specifically for storing collections of elements where you want to filter out duplicates.
Either use a Set as other people have suggested or use an List compatible class. With a list compatible class just use the Contains method to check if it already exists in the array.
import java.util.Scanner;
public class PrintDistinctNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int [] numberArray = createArray();
System.out.println("The number u entered are: ");
displayArray(numberArray);
getDistinctNumbers(numberArray);
}
public static int[] createArray() {
Scanner input = new Scanner(System.in);
int [] numberCollection = new int [10];
System.out.println("Enter 10 numbers");
for(int i = 0; i < numberCollection.length; i++){
numberCollection[i] = input.nextInt();
}
return numberCollection;
}
public static void displayArray(int[] numberArray) {
for(int i = 0; i < numberArray.length; i++){
System.out.print(numberArray[i]+" ");
}
}
public static void getDistinctNumbers(int[] numberArray) {
boolean isDistinct = true;
int temp = 0;
int [] distinctArrayNumbers = new int [10];
for ( int i = 0; i < numberArray.length; i++){
isDistinct = true;
temp = numberArray[i];
for( int j = 0; j < distinctArrayNumbers.length; j++){
if( numberArray[i] == distinctArrayNumbers[j] ){
isDistinct = false;
}
}
if(isDistinct){
distinctArrayNumbers[temp]=numberArray[i];
temp++;
}
}
displayDistinctArray(distinctArrayNumbers);
}
public static void displayDistinctArray(int[] distinctArrayNumbers) {
for( int i = 0; i < distinctArrayNumbers.length; i++){
if(distinctArrayNumbers[i] != 0){
System.out.println(distinctArrayNumbers[i]);
}
}
}
}