Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: - java

So my assignment is write a recursive Java method that finds the maximum of an array of
integers without using any loops. The input is a first line that contains a single integer n < 10. The next line contains n numbers separated by spaces. The output should be a single integer. Call your program FindMax. The below code is what I have so far, it compiles but instead of me being able to enter
input line 1: 5 (n) }
This is what I need to be able to input
input line2: 2 3 4 5 3 }
it makes me enter
input: 5 (n)
input: 2
input: 3
input: 4
input: 5
input: 3
also after entering the above I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at FindMaxtesting.getmax(FindMaxtesting.java:35)
at FindMaxtesting.getmax(FindMaxtesting.java:48)
at FindMaxtesting.getmax(FindMaxtesting.java:42)
at FindMaxtesting.getmax(FindMaxtesting.java:42)
at FindMaxtesting.getmax(FindMaxtesting.java:42)
at FindMaxtesting.getmax(FindMaxtesting.java:42)
at FindMaxtesting.main(FindMaxtesting.java:17)
This is my code so far:
import java.util.Scanner;
public class FindMaxtesting
{
public static void main (String[]args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 0;
int fin = 0;
System.out.println(getmax( Inca(n ) , n , fin , i));
}
public static int[] Inca(int n )
{
Scanner sc = new Scanner(System.in);
int[] arr = new int[n];
for(int j=0;j<n;++j)
{
arr[j] = sc.nextInt();
}
return arr;
}
public static int getmax ( int arr[], int n, int fin, int i )
{
int temp = 0;
if (fin < arr[i])
{
temp = fin;
fin = arr[i];
arr[i] = temp;
i++;
getmax(arr , n , fin , i);
}
else if (fin > arr[i])
{
i++;
getmax(arr , n , fin , i);
}
else if ( i == n-1 )
{
return fin;
}
return fin;
}
}

The essence of your problem is that in getmax you need to add the lines
if (i >= n)
return fin;
You are searching through the array recursively, which isn't really the best way to do it, but I assume that this is a homework problem, and you need to say when to stop looking further through the array, however you continue to look further in the array. When i>=n then you know you have searched the entire array, and can just return fin, as there are no further values that can be greater.

Related

Array rotation TLE (Time Limit Exceeded)

I am really confused why my java code is not working it is giving TLE on Code Monks on Hacker Earth.
Here is the link to the 1
Link to Question
the first question MONK AND ROTATION
import java.util.Scanner;
class TestClass {
static int[] ar=new int[100001];
public static void main(String args[] ){
Scanner in=new Scanner(System.in);
byte t=in.nextByte();
while(t-->0){
int n=in.nextInt();
int k=in.nextInt()%n;
for(int i=0;i<n-k;i++)
ar[i]=in.nextInt();
for(int i=0;i<k;i++)
System.out.print(in.nextInt()+" ");
for(int i=0;i<n-k;i++)
System.out.print(ar[i]+" ");
System.out.println();
}
}
}
I don't know why is it giving TLE I think there is some infinite loop going.
the question at the site is-
Monk and Rotation
Monk loves to perform different operations on arrays, and so being the principal of HackerEarth School, he assigned a task to his new student Mishki. Mishki will be provided with an integer array A of size N and an integer K , where she needs to rotate the array in the right direction by K steps and then print the resultant array. As she is new to the school, please help her to complete the task.
Input:
The first line will consists of one integer T denoting the number of test cases.
For each test case:
The first line consists of two integers N and K, N being the number of elements in the array and K denotes the number of steps of rotation.
The next line consists of N space separated integers , denoting the elements of the array A.
Output:
Print the required array.
Constraints:
1<=T<=20
1<=N<=10^5
0<=K<=10^6
0<=A[i]<=10^6
Sample Input
1
5 2
1 2 3 4 5
Sample Output
4 5 1 2 3
Explanation
Here T is 1, which means one test case.
denoting the number of elements in the array and , denoting the number of steps of rotations.
The initial array is:
In first rotation, 5 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
In second rotation, 4 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
Time Limit: 1.0 sec(s) for each input file
Memory Limit: 256 MB
Source Limit: 1024 KB
I'm not sure about the correctness of your solution, but try to use StreamTokenizer or BufferedReader instead of Scanner. Scanner is too slow and may result in TLE when you need to read a lot of data.
Reduce the number of reads and writes from/to System.in and System.out.
Look at the following solution
Scanner scanner = new Scanner(System.in);
int noOfTestCases = scanner.nextInt();
for (int i = 0; i < noOfTestCases; i++) {
int arraySize = scanner.nextInt();
int noOfRotations = scanner.nextInt();
noOfRotations = noOfRotations % arraySize;
scanner.nextLine();
String inputString = scanner.nextLine();
String[] inputStringArray = inputString.split(" ");
StringBuffer sb = new StringBuffer();
for (int j = 0; j < arraySize; j++) {
sb.append(inputStringArray[(arraySize + j - noOfRotations) % arraySize] + " ");
}
System.out.print(sb);
System.out.println("");
}
import java.util.*;
public class temp {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
int k = sc.nextInt();
int p = 0;
int ar[] = new int[n];
for(int i=0;i<n;i++){
ar[i] = sc.nextInt();
}
k %= n;
for(int i=0;i<n;i++){
p = ar[(i+(n-k))%n];
System.out.print(p+" ");
}
System.out.println();
}
}
}
Though I have not used a big sized array in the starting, this code is working fine for all test cases.
Try this one.
Think from a different perspective. Instead of splitting the string and converting it into an array and applying the iterative logic, we can apply a different logic.
The trick is you just need to find the position of the input string where we have to split only once.
By that I mean,
input=>
6 2       //4 is the length of numbers and 2 is the index of rotation
1 2 3 4 5 6     //array (take input as a string using buffered reader)
Here, we just need to split the array string at the 2nd last space i.e. 4th space. So the output can be achieved by just splitting the string once-
5 6 1 2 3 4
first split- 5 6 + space + second split- 1 2 3 4
This logic worked for me and all the test cases passed.
Also don't forget to cover the corner case scenario when array input string is just one number.
Code Snippet-
int count=0;
for(int k=0; k<arr.length(); k++) {
if(arr.charAt(k)==' ')
count++;
if(count==size-rot) {
System.out.println(arr.substring(k+1,arr.length())
+ " " + arr.substring(0,k));
break;
}
}
Problem is in the System.out.print() call that is inside the for-loop. Thats a fairly heavy call and if called too many times and creates an overhead. This solution works:
//import for Scanner and other utility classes
import java.util.*;
class TestClass {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
int noOfTests = Integer.parseInt(input);
for (int t = 0; t < noOfTests; t++) {
input = s.nextLine();
String[] str = input.split(" ");
int sizeOfArray = Integer.parseInt(str[0]);
int noOfRotations = Integer.parseInt(str[1]);
String strIntegerArray = s.nextLine();
String[] array = strIntegerArray.split(" ");
printRightRotatedArray(array, noOfRotations, strIntegerArray.length());
}
}
static void printRightRotatedArray(String[] array, int noOfRotations, int lengthOfStr) {
int len = array.length;
int noOfAcutalRotations = noOfRotations % len;
int startingIndex = len - noOfAcutalRotations;
StringBuilder sb = new StringBuilder(lengthOfStr+1);
for (int i = 0; i < len; i++) {
sb.append(array[(startingIndex + i) % len]);
sb.append(" ");
}
System.out.println(sb);
}
}
putting all into string buffer and print at the end worked for me.
class TestClass {
public static void main(String args[] ) throws Exception {
//BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();// output
for(int i=0;i<t;i++){
String [] nk=br.readLine().split(" ");
int n= Integer.parseInt(nk[0]);
int k=Integer.parseInt(nk[1]);
String [] a=br.readLine().split(" ");
int split=n-(k%n);
for (int j = split; j < a.length; j++) {
sb.append(a[j]);
sb.append(' ');
}
for (int j = 0 ; j < split; j++) {
sb.append(a[j]);
sb.append(' ');
}
sb.append("\n");
}
System.out.println(sb);
}
}

Finding the sum of all elements of a sequence, ending with the number 0 using do-while loop in Java

I am a beginner. I appreciate if someone solves my problem in simple way in Java.
Problem:
Find the sum of all elements of a sequence, ending with the number 0.
The number 0 itself is not included into the sequence and serves as a sign of cessation.
Sample Input:
3
6
8
0 and
Sample Output:
17
I am writing following program:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
do {
sum += scanner.nextInt();
} while (scanner.nextInt() != 0);
System.out.println(sum);
}
And What I get is as following:
Input:
3
6
8
0
Output:
11 <---it should come out as 17.
Please figure out where the code is wrong.
The problem with your code
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
do {
sum += scanner.nextInt(); // consuming an int from keyboard with nextInt()
} while (scanner.nextInt() != 0); // consuming another int from keyboard with nextInt()
System.out.println(sum);
for input 3 6 8 0
sum += scanner.nextInt(); //this nextInt() consumes 3 now sum has 3
scanner.nextInt() != 0 // this nextInt() consumes 6 but does not add to sum now sum has 3 only the 6 is ignored
sum += scanner.nextInt(); // same here this consumes 8 and add to sum now sum has 11 which is the output
scanner.nextInt() != 0 // this nextInt() consumes 0 which fails the condition
In short you are ignoring every second input
The fix
Scanner scanner = new Scanner(System.in);
int sum = 0;
int num = 0;
while((num = scanner.nextInt()) != 0) { // nextInt() is called only once and value is cashed in num
sum += num; // add this num to sum
}
System.out.println(sum); // prints 17 as expected
Please try below code
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int checker = 0;
do {
checker = scanner.nextInt();
sum += checker;
} while (checker != 0);
System.out.println(sum);
}
}
In your code value coming from scanner.nextInt() in while loop is being missed to be added. That's causing a issue

Creating Array Based on User input Using Scanner

I'm trying to create a program where the user can create an array using scanner. In this example, if the first input is 4, an array with the length of 4 is then initialized. However, in the next part, the scanner is asking for 5 inputs instead of 4. If the next inputs are 1 2 3 4 5, the final output will be [2,3,4,5]. I'm not sure why it's asking for 5 inputs instead of 4. Can someone tell me what I did wrong?
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] numbers = new int[n];
int input = s.nextInt();
for (int i = 0; i < n; i++) {
numbers[i] = s.nextInt();
}
System.out.println("---------");
for (int x : numbers) {
System.out.print(x);
}
}
}
The line int input = s.nextInt(); is consuming the first input.. that's why array is getting initialized from 2 at 0'th index.
Remove the line int input = s.nextInt(); and it'll work fine

loop is cut one element of the array

The problem is :
Write a program that reads a number n and then declares an array of n elements. The program then fills the array with the first n numbers, where each number is two to the power of the previous. Finally, display array’s contents.
My code :
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ;
for ( ;i<=a.length-1 ; i++) {
a[i+1] = Math.pow(2,a[i]);
System.out.println((int)(a[i]) );
}
}
}
The error is :
----jGRASP exec: java Q1
Enter a number :
4
4
16
65536
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Q1.main(Q1.java:16)
----jGRASP wedge2: exit code for process is 1.
why it says that?
And the number by user printed twice!
a[i+1] = Math.pow(2,a[i]); // issue here
When i=a.length-1, i+1 is a.length. So there is no index value match in this array.
Suggestion:
Create an array witch has lenght= a.length+1
double powArray[] =new double[a.length+1];
Now
powArray[0]=a[0];
for(int i=1;i<powArray.length;i++){
powArray[i]=Math.pow(2,a[i-1]);
}
Issue is on line.16 as per compiler : a[i+1] = Math.pow(2,a[i]); The problem is indexes are not properly matched here.So it gives ArrayIndexOutOfBound Exception.Here i=a.length-1, i+1=a.length.So it is giving ArrayIndexOutOfBound Exception.
You should check that your index is not negative and not higher than the array length before accessing an array item.
Refer this : Avoiding index out of bounds exceptions
Concentrate on below portion of your code, its easy and you'll feel good if you figure out yourself:
for ( ;i<=a.length-1 ; i++) // check from where i starts and where it ends
{
a[i+1] = Math.pow(2,a[i]); // check what value of i would be here on each iteration
System.out.println((int)(a[i]) );
}
Also you could use a debugger and check every iteration
Few things to look upon here.
You have written a[0]= num ; which means the first value in the array is the same as the number entered by the user. Thus, you can see the number printed again. Thus,
a[0] = 1; // initial value has to be 1, contrary to what you've used
Next, your loop to generate the array values needs to be fixed. When you have i+1, the array index goes out of bounds in the last iteration, where your i is a.length - 1. Thus change your loop to something like this
for (int i = 1; i < a.length; i++) {
a[i] = Math.pow(2, a[i-1]);
}
Now, print the array values in a separate loop, as the previous loop won't print the value of the first index of the array.
for (int i = 0; i < a.length; i++) {
System.out.println((int)a[i]);
}
Change the upper limit to a.length-2 .Rest code remain same
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ;
for ( ;i<=a.length-2 ; i++) {
a[i+1] = Math.pow(2,a[i]);
System.out.println((int)(a[i]) );
}
}
}
int num ;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ; //Assign First Element To Array
double prev = a[0];
for(int i=1;i<a.length;i++){
a[i] = Math.pow(2,prev);
prev = a[i];
}
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
Output
Enter a number :
3
3.0
8.0
256.0
Just change the loop to :
for(;i < a.length-1;i++)
since when you assign 4 as a length for a[]..
you have a[0],a[1],a[2],a[3]... 4 slots.
Now a.length gives 4.
so for your a[i+1] for i=a.length-1 (i.e 3 ) .. a[i+1] = a[4]... which is out of the array bound for you array.
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
for ( ;i<a.length ; i++) {
a[i] = Math.pow(2,i);
System.out.pri``nt((int)a[i]+ " ");
}
}
}

sorting an array and counting its elements

I tried to sort an array accending and count the array elements
please help me find whats missing, have debugged many times. here is my code and the output i got. Thanks
package habeeb;
import java.util.*;
public class Habeeb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[30];
int i, count=0;
System.out.println("Enter the integers between 1 and 100" );
for( i=0; i<num.length; i++){
num[i]= input.nextInt();
if(num[i]==0)
break;
count++;
}
calling the function here
Sorting(num, i, count);
}
public static void Sorting(int[] sort, int a, int con){
if (a<0) return;
/*am sorting the array here*/
Arrays.sort(sort);
int j, count=0;
for(j=0; j<con; j++){
if(sort[a]==sort[j])
count++;
}
System.out.println(sort[a]+" occurs "+count+" times");
Sorting(sort, a-1, con);
}
}
Here is the output:
run:
Enter the integers between 1 and 100
2
5
4
8
1
6
0
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
Your problem is that the array is of size 30 and when you sort it you have all the values you did not assign to equal to 0 and thus they go in the front of the sorted array. Later on out of the first 6 numbers all are 0 so the output you have is correct.
To aviod the problem you face I suggest you use ArrayList instead of simple array so that you can add elements dynamically to it.
Try this
The counting method
public int count(int[] values, int value)
{
int count = 0;
for (int current : values)
{
if (current == value)
count++;
}
return count;
}
Then use
int[] sorted = Arrays.sort(num);
for (int value : sorted)
{
System.out.println("" + value + " occurs " + count(sorted, value) + " times");
}
This works for sure.
You are doing a bit more work than is necessary. I would solve this like so:
Map<Integer, Integer> countMap = new HashMap<Integer,Integer>();
for( i=0; i<num.length; i++){
int current = input.nextInt();
if(countMap.get(current) != null)
{
int incrementMe = countMap.get(current);
countMap.put(current,++incrementMe);
}
else
{
countMap.put(input.nextInt(),1);
}
}

Categories

Resources