This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am working on a program,I have tried to find a way how to find all possible permutations of an array elements in Java, but it didn't work .
My code is:
public class Permutation {
public static void main(String[] args) {
int[] list = new int[3];
System.out.println("enter the elements of array");
Scanner sc = new Scanner(System.in);
for (int i = 0; i < list.length; i++) {
list[i] = sc.nextInt();
}
System.out.println(Arrays.toString(list));
int n = list.length;
permutation(list, n, 0);
}
public static void permutation(int[] list, int n, int l) {
if (l == n - 1) {
printArray(n, list);
return;
}
for (int i = 1; i < n; i++) {
swap(list, list[i], list[l]);
permutation(list, n, l + 1);
swap(list, list[i], list[l]);
}
}
public static void swap(int[] list, int x, int y) {
int temp = list[x];
list[x] = list[y];
list[y] = temp;
}
public static void printArray(int n, int[] list) {
for (int i = 0; i < list.length; i++) {
System.out.print(list[i]);
}
}
}
This code is continuously throws an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Permutation.swap(Permutation.java:34)
at Permutation.permutation(Permutation.java:27)
at Permutation.permutation(Permutation.java:28)
at Permutation.main(Permutation.java:15)
I'm not able to understand what to do in this program so that it'll produce desired output.
And what is the meaning of this error which is thrown by program??
you are getting this error because you are trying to access items, not in the array try changing
i = 0 in line 25
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
//import java.util.Arrays;
import java.util.*;
public class Solution {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int arr[] = new int[size];
int u=0;
for (int i = 0; i < size; i++) {
u=sc.nextInt();
arr[i] = u;
}
System.out.println(arr);
int pos = 0, neg = 0, zero = 0;
for (int i:arr) {
if (i > 0) {
pos += 1;
} else if (i == 0) {
zero += 1;
} else {
neg += 1;
}
}
System.out.println(pos / size);
System.out.println(neg / size);
System.out.println(zero / size);
}
}
this was my code to print the ratio of positive negative and zero's present in my array but in the print statement where i am printing the array, it is showing this [I#7cc355be
The right way to print an array in one line would be:
System.out.println(Arrays.toString(arr));
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
I'm creating a program that uses two methods to print all the odd numbers in an array and then get the sum of the odd numbers. However, I'm getting an output that makes no sense. This is the code that I'm using:
public class ArrayMethods1 {
public static int[] printOdds(int[]arrayExample) {
int i;
String oddNum = "";
int [] newArray = new int [3];
int x = 0;
for (i = 0; i < arrayExample.length; i++) {
if (arrayExample[i] % 2 != 0) {
System.out.print(arrayExample[i] + " ");
}
}
int[] sumOfOdds = new int [1];
sumOfOdds = sumOdds(newArray);
return sumOfOdds;
}
public static int[] sumOdds(int[]arrayExample1) {
int i;
int[] oddsTotal = new int[1];
int total = 0;
for (i = 0; i < arrayExample1.length; i++) {
if (arrayExample1[i] % 2 != 0) {
total = total + arrayExample1[i];
}
}
oddsTotal[0] = total;
return oddsTotal;
}
public static void main(String[] args) {
int [] mainArray = new int [5];
mainArray[0] = 17;
mainArray[1] = 92;
mainArray[2] = 21;
mainArray[3] = 984;
mainArray[4] = 75;
printOdds(mainArray);
int [] oddSum = new int[1];
oddSum = sumOdds(mainArray);
System.out.println(oddSum);
}
}
And I'm getting this as output:
17 21 75 [I#51016012
I have absolutely no idea where that second part is coming from, so any help would be awesome. Thanks!
well you are storing the result of the sum in an array and then you print the reference of type int[], that's why you get [I#51016012. so you need to print oddSum[0].
It is not quite clear why you return int[] from the methods that just print and calculate the sum of the odd numbers.
So the code could be enhanced:
public static void printOdds(int[] arr) {
for (int n : arr) {
if (n % 2 == 1) {
System.out.print(n + " ");
}
}
System.out.println();
}
public static int sumOdds(int[] arr) {
int total = 0;
for (int n : arr) {
if (n % 2 == 1) {
total += n;
}
}
return total;
}
Also, it may be worth to use Java 8+ stream to implement both tasks in one run:
import java.util.Arrays;
public class PrintAndSumOdds {
public static void main(String [] args){
int[] arr = {17, 92, 21, 984, 75};
int sumOdds = Arrays.stream(arr) // get IntStream from the array
.filter(n -> n % 2 == 1) // filter out the odds
.peek(n -> System.out.print(n + " ")) // print them in one line
.sum(); // and count the sum (terminal operation)
System.out.println("\nTotal odds: " + sumOdds);
}
}
Output:
17 21 75
Total odds: 113
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am getting a NullPointerException in the hanoi function when pushing the values from the input into the stack and I'm not sure why heres my code:
public class Hanoi {
public static Stack<Integer>[] towersOfHanoi = new Stack[4];
static int moves;
public static void hanoi(int n) {
for(int i = n; n > 0; i--) {
towersOfHanoi[1].push(i);
}
moveDisc(n, 1, 2, 3);
}
public static void moveDisc(int n, int j, int k, int l) {
moveDisc(n-1, j, k, l);
int i = towersOfHanoi[j].pop();
towersOfHanoi[k].push(i);
moves++;
moveDisc(n-1, l, j, k);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number of discs: ");
int n = in.nextInt();
in.close();
hanoi(n);
towersOfHanoi[1] = new Stack<Integer>();
towersOfHanoi[2] = new Stack<Integer>();
towersOfHanoi[3] = new Stack<Integer>();
System.out.println(moves);
You've initialized an array of Stacks, but you haven't actually allocated Stacks and put them in said Array. In your main() function, you should do something like:
for (int i = 0; i < 4; i++)
{
towersOfHanoi[i] = new Stack<Integer>();
}
Edit: Do this BEFORE you call hanoi(n). Otherwise, you're referencing objects before allocating them.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I created this method randomInt, that gives a random number, between -5, and 15. I created another method randomIntArray that calls randomInt, in a loop, and stores the random integers into an array. However, when I try to print it, it just returns an ArrayIndexOutOfBoundsException.
public static int randomInt(int low, int high) {
double e;
double x = Math.random();
e = low + x * (high - low);
return (int) e;
}
public static int[] randomIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15); //"-5&15 are the lower and upper bounds of the random number array
}
return a;
}
In randomInt, When I didn't cast the return value into an int, it worked, however I need it to return an int for the array to work.
Check your printing code after calling randomIntArray(number);
/**
* #param args the command line arguments
*/
public static void main(String[]args) {
int[] myArray = randomIntArray(10);
// Manual iteration through your array
for (int i = 0; i < myArray.length; i++) {
System.out.print(myArray[i] + " ");
}
System.out.println("");
// Use of Arrays class to print your array
System.out.println(Arrays.toString(myArray));
}
public static int randomInt(int low, int high) {
double e;
double x = Math.random();
e = low + x * (high - low);
return (int) e;
}
public static int[] randomIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15);
}//"-5&15 are the lower and upper bounds of the random number array
return a;
}
Results:
http://ideone.com/3OrTei
In the function calling randomIntArray(int n):
int[] array = randomIntArray(5);
for(int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
The code works, just make sure you're printing the results properly
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Q:
Obtain start and end integers in main method. Pass those two values into a separate function.Return all the numbers between those values (inclusive), which is divisible by 3 back to the main from the function.
I have done upto:
import java.util.*;
public class inbetween {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter range of values");
int x =in.nextInt();
int y =in.nextInt();
search(x,y);
}
public static void search(int a, int b) {
int length = (b-a)+1;
int [] arr = new int [length];
for(int i=0; i<length; i++)
{
a = a+1;
int c;
// int count=0;
c = a%3;
if (c==0) {
arr[i] = a;
System.out.println(arr[i]);
// count = count+1;
// return count;
}
}
}
}
Now my question is ..How can I return the array and print it in function and print it there??? this code works but in this, the values are getting printed in the function itself (but it should be printed in the main)...
Change it to
import java.util.*;
public class inbetween {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter range of values");
int x =in.nextInt();
int y =in.nextInt();
int[] result = search(x,y);
for (int i=0;i < result.length; i++)
System.out.println(result[i]);
}
public static int[] search(int a, int b) {
int length = (b-a)+1;
int [] arr = new int [length];
for(int i=0; i<length; i++)
{
a = a+1;
int c;
// int count=0;
c = a%3;
if (c==0) {
arr[i] = a;
}
}
return arr;
}
}
Create array in main
Pass reference to array to function to do work
Print array out in main
You need to return an array to main:
package com.stackoverflow.homework;
import java.util.Arrays;
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
int[] result;
Scanner in = new Scanner(System.in);
System.out.println("Enter range of values: ");
int x = in.nextInt();
int y = in.nextInt();
result = findNumbersBetween(x,y);
for(int i=0; i<result.length; i++) {
System.out.println(result[i]);
}
}
private static int[] findNumbersBetween(int a, int b) {
int[] temp = new int[(b-a)+1];
int x = a;
int i = 0;
while(x <= b) {
if(x % 3 == 0) {
temp[i] = x;
i++;
}
x++;
}
return Arrays.copyOfRange(temp, 0, i);
}
}
Also remember that first letter of class name should always be capitalized!