Why won't this print in Reverse? - java
I have a very simple problem but I can't seem to solve it. I'm getting an out of bounds error on this code
int c = 0;
System.out.println();
System.out.println("Printing array in Reverse order:");
for (int i = array.length ; i >= -1; i--)
{
System.out.println(array[i] +" ");
c++;
if(c == 10)
{
System.out.println();
c=0;
}
}
What's the deal?
for (int i = array.length ; i >= -1; i--) {
wrong, arrays starts at index zero, so a "length" array is from index 0 to index "length - 1"
so your code is wrong, you should use
for (int i = array.length - 1 ; i >= 0; i--) {
You get an IndexOutOfBounds because you're starting out of the array
int c = 0;
System.out.println();
System.out.println("Printing array in Reverse order:");
for (int i = array.length -1; //HERE
i >= 0;//HERE
i--) {
System.out.println(array[i] +" ");
c++;
if(c == 10) {
System.out.println();
c=0;
}
}
In Java, array index go from 0 to "length - 1". So if you start in array.length, you are trying to access out of the array's positions. Same occurs if you try to access to -1 index, because your least index is 0.
Here is a small piece of code which will work you to get the reverse :)
public class newarray {
public static void main(String args[]){
int arr[]={10,20,30};
int size=arr.length;
for(int i=size-1;i>=0;i--){
System.out.println(arr[i]);
}
}
}
OutPut :
30
20
10
Related
How to check if certain numbers appear in an array?
I'm relatively new to java. I'm trying to find if numbers from 0 - 4 are stored somewhere in an array of size 5. The array is populated by the user entering integers between 0-4. I have successfully managed to get it to confirm that the first number entered by the user is in the array however, the numbers after that not appearing. So for example: If the user enters the numbers 2,2,2,1,3 I will get only 2 appears in the array as a result. public static void checkEachNumber(int[] array) { int currentNum = 0; for(int i = 0; i < array.length; i++) { for(int j = 0; j < array.length; j++) { currentNum = i; if(currentNum == array[j]) { System.out.println(currentNum + " appears in the array"); break; } else { System.out.println(currentNum + " doesn't appear in the array"); break; } } } }
To resolve your problem you should simply remove the have used in the else part of the array. Consider a case like this ex. 2 1 4 3 when checking for i=1 it will first compare the value with 2 so it will come out of the loop. public static void checkEachNumber(int[] array) { int currentNum = 0; for(int i = 0; i < array.length; i++) { int flag=0; for(int j = 0; j < array.length; j++) { currentNum = i; if(currentNum == array[j]) { System.out.println(currentNum + " appears in the array"); flag=1; break; } } if(flag==0) { System.out.println("currentNum+"Doesn't appear in array"); } } }
When you execute a break statement, the loop stops running completely. In general, the way to scan for a match is going to look like this: found_match = no for (... in ...) { if (match) { found_match = yes break } } if (found_match) { do_found_match_stuff(); }
Java 2d array counts zeros in column
I start learning programming about 4 days ago by myself and iam a lil bit stuck with 2d arrays. I try to challenging myself with tasks, like get from 2d array column with most zeros or atleast just count zeros, so far i get this far public class b { public static void main(String[] args) { int a[][] = new int [5][5]; int i,j; int s = 0; for(i= 0;i<a.length; i++) for(j = 0; j<a[i].length; j++){ a[i][j] = (int)(Math.random()*10); } for(i=0;i<a.length;i++){ for(j=0;j<a[i].length;j++) { System.out.print(a[i][j] + "\t"); } System.out.println(); } for(j=0;j<a[0].length;j++) { for(i=0;i<a.length;i++) { if(a[i][j] >-1 || a[i][j]<1) { s++; System.out.println(s +"\t"); s = 0; } } } } } Can somebody explain me why result is always 1 and why it counts columns and rows in one row?
Suppose the condition enters into if(a[i][j] >-1 || a[i][j]<1) then you increase s by 1 then print it which gives 1 then you reassign it to s=0 so it gives same 1 each time.So remove the s=0 and place the printing line after end of loop public class b { public static void main(String[] args) { int a[][] = new int [5][5]; int i,j; int s = 0; for(i= 0;i<a.length; i++) for(j = 0; j<a[i].length; j++){ a[i][j] = (int)(Math.random()*10); } for(i=0;i<a.length;i++){ for(j=0;j<a[i].length;j++) System.out.print(a[i][j] + "\t"); System.out.println(); } for(j=0;j<a[0].length;j++){ for(i=0;i<a.length;i++) if(a[i][j] >-1 && a[i][j]<1){ s++; } System.out.println("Zero in column no. "+j+" is "+s +"\t"); s=0; } } } Demo
Result will be 1 because you're re-assigning 0 to s everytime. But the issue is not only that. Firstly your condition is using wrong indices. Instead of a[i][j] you should use a[j][i] as you're traversing column-wise. Secondly: if(a[j][i] >-1 || a[j][i]<1){ can be simply written as: if(a[j][i] == 0) { So the structure is the outer for loop will iterate over each column number. And for each column number, inner for loop will find count of 0. You've to maintain a max variable outside both the loops, to track the current max. Also, you've to use another variable inside the outer for loop to store the count for current column. Everytime the inner for loop ends, check if current column count is greater than max. If yes, reset max. int max = 0; for(j=0;j<a[0].length;j++){ int currentColumnCount = 0; for(i=0;i<a.length;i++) { if(a[j][i] == 0) { currentColumnCount++; } } if (currentColumnCount > max) { max = currentColumnCount; } }
Numerically listing Arrays
So my code is having a problem. Here's what I want to do: have one array have the original set of numbers (up to 10 numbers) and then copy and paste those numbers onto the second array. And then afterwards, the second area lists those numbers from the first array numerically (going from the lowest number to the highest). The problem is... my second output is giving me a good output with the lowest numbers going to the highest numbers, however, at the same time, I'm getting a long list of repeated numbers and a ton of zeros if I stop my code with the -9000 input. Can anyone tell me what the problem is and how to fix it? I don't want to sort this second array with the Array.sort() option, by the way. No importing anything but the scanner: public static void main(String[] args) { System.out.println("Input up to '10' numbers for current array: "); int[] array1 = new int[10]; int i; Scanner scan = new Scanner(System.in); for (i = 0; i < 10; i++) { System.out.println("Input a number for " + (i + 1) + ": "); int input = scan.nextInt(); if (input == -9000) { break; } else { array1[i] = input; } } System.out.println("\n" + "Original Array: "); for (int j = 0; j < i; j++) { System.out.println((j + 1) + ": " + array1[j]); } System.out.println("\n" + "Organized Array: "); int[] array2 = new int[i]; for (i = 0; i < array1[i]; i++) { System.out.println(+array1[i]); for (int j = 0; j < i; j++) { int temp; boolean numerical = false; while (numerical == false) { numerical = true; for (i = 0; i < array1.length - 1; i++) { if (array2[i] > array2[i + 1]) { temp = array2[i + 1]; array2[i + 1] = array2[i]; array2[i] = temp; numerical = false; } } } } for (i = 0; i < array2.length; i++) { System.out.println(array2[i]); } } }
You have several issues that you need to fix to make your program run: You have forgotten to copy array1 into array2: The output that you think is coming from sorting array2 is actually from the process of sorting. int[] array2 = new int[i]; for (int j = 0; j < i; j++) { array2[j] = array1[j]; } You placed the output of sorted array inside the loop that does sorting: Check the level of curly braces, and move the output loop to after the sorting loop for (i = 0; i < array2.length; i++) { System.out.println(array2[i]); } Your sorting algorithm has an extra loop: Having the outermost loop makes no sense: your bubblesort algorithm works perfectly without it, so you should remove the loop, and move its body up by one level of nesting: for (i = 0; i < array1[i]; i++) { // Remove the loop ... // <<== Keep the body } Your innermost loop reuses i incorrectly: Replace loop variable i with another variable, e.g. m for (int m = 0 ; m < array2.length - 1; m++) { if (array2[m] > array2[m + 1]) { temp = array2[m + 1]; array2[m + 1] = array2[m]; array2[m] = temp; numerical = false; } } Demo.
in your for loop you set i limit to array1[i] value not to array lenght, surely it is wrong. you are reusing the same index i, inside the other loops of the outer big 'for' loop, so the i value will be messed up by inner loops you never copied the array1 values to array2
For loop with substrings
Beginning CS student here, trying to get a handle on loops. My task is to take a String s, such that if s = 'abcd', the program will print: 'a,b,c,d,ab,bc,cd,abc,bcd,abcd'. Clearly the begin index and end index change as the loop iterates—(0,1),(1,2),(2,3),(3,4). That's fine and I can print: 'a,b,c,d'. But how do I control it such that it will go from that to (0,2),(1,3),(2,4) and then (0,3),(1,4), and finally (0,4)? This is where I am stumped. Thanks for the assistance and here's my code: void printSubstring() { int len = s.length(); for (int i=0;i<len;i++) { for (int k=0;k<len;k++) System.out.print(s.substring(k,k+1)+", "); } System.out.println(); }
for (int i=0;i<len;i++) { for (int k=0;k<len-i;k++) System.out.print(s.substring(k,k+i+1)+","); } This as your for structure should work. At each step inner loop, the number of strings to print decreases (using -i). And the length of the strings increase (using +i in the substring) Tested with: abcdefghijklmnopqrstuvwxyz Output: a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,ab,bc,cd,de,ef,fg,gh,hi,ij,jk,kl,lm,mn,no,op,pq,qr,rs,st,tu,uv,vw,wx,xy,yz,abc,bcd,cde,def,efg,fgh,ghi,hij,ijk,jkl,klm,lmn,mno,nop,opq,pqr,qrs,rst,stu,tuv,uvw,vwx,wxy,xyz,abcd,bcde,cdef,defg,efgh,fghi,ghij,hijk,ijkl,jklm,klmn,lmno,mnop,nopq,opqr,pqrs,qrst,rstu,stuv,tuvw,uvwx,vwxy,wxyz,abcde,bcdef,cdefg,defgh,efghi,fghij,ghijk,hijkl,ijklm,jklmn,klmno,lmnop,mnopq,nopqr,opqrs,pqrst,qrstu,rstuv,stuvw,tuvwx,uvwxy,vwxyz,abcdef,bcdefg,cdefgh,defghi,efghij,fghijk,ghijkl,hijklm,ijklmn,jklmno,klmnop,lmnopq,mnopqr,nopqrs,opqrst,pqrstu,qrstuv,rstuvw,stuvwx,tuvwxy,uvwxyz,abcdefg,bcdefgh,cdefghi,defghij,efghijk,fghijkl,ghijklm,hijklmn,ijklmno,jklmnop,klmnopq,lmnopqr,mnopqrs,nopqrst,opqrstu,pqrstuv,qrstuvw,rstuvwx,stuvwxy,tuvwxyz,abcdefgh,bcdefghi,cdefghij,defghijk,efghijkl,fghijklm,ghijklmn,hijklmno,ijklmnop,jklmnopq,klmnopqr,lmnopqrs,mnopqrst,nopqrstu,opqrstuv,pqrstuvw,qrstuvwx,rstuvwxy,stuvwxyz,abcdefghi,bcdefghij,cdefghijk,defghijkl,efghijklm,fghijklmn,ghijklmno,hijklmnop,ijklmnopq,jklmnopqr,klmnopqrs,lmnopqrst,mnopqrstu,nopqrstuv,opqrstuvw,pqrstuvwx,qrstuvwxy,rstuvwxyz,abcdefghij,bcdefghijk,cdefghijkl,defghijklm,efghijklmn,fghijklmno,ghijklmnop,hijklmnopq,ijklmnopqr,jklmnopqrs,klmnopqrst,lmnopqrstu,mnopqrstuv,nopqrstuvw,opqrstuvwx,pqrstuvwxy,qrstuvwxyz,abcdefghijk,bcdefghijkl,cdefghijklm,defghijklmn,efghijklmno,fghijklmnop,ghijklmnopq,hijklmnopqr,ijklmnopqrs,jklmnopqrst,klmnopqrstu,lmnopqrstuv,mnopqrstuvw,nopqrstuvwx,opqrstuvwxy,pqrstuvwxyz,abcdefghijkl,bcdefghijklm,cdefghijklmn,defghijklmno,efghijklmnop,fghijklmnopq,ghijklmnopqr,hijklmnopqrs,ijklmnopqrst,jklmnopqrstu,klmnopqrstuv,lmnopqrstuvw,mnopqrstuvwx,nopqrstuvwxy,opqrstuvwxyz,abcdefghijklm,bcdefghijklmn,cdefghijklmno,defghijklmnop,efghijklmnopq,fghijklmnopqr,ghijklmnopqrs,hijklmnopqrst,ijklmnopqrstu,jklmnopqrstuv,klmnopqrstuvw,lmnopqrstuvwx,mnopqrstuvwxy,nopqrstuvwxyz,abcdefghijklmn,bcdefghijklmno,cdefghijklmnop,defghijklmnopq,efghijklmnopqr,fghijklmnopqrs,ghijklmnopqrst,hijklmnopqrstu,ijklmnopqrstuv,jklmnopqrstuvw,klmnopqrstuvwx,lmnopqrstuvwxy,mnopqrstuvwxyz,abcdefghijklmno,bcdefghijklmnop,cdefghijklmnopq,defghijklmnopqr,efghijklmnopqrs,fghijklmnopqrst,ghijklmnopqrstu,hijklmnopqrstuv,ijklmnopqrstuvw,jklmnopqrstuvwx,klmnopqrstuvwxy,lmnopqrstuvwxyz,abcdefghijklmnop,bcdefghijklmnopq,cdefghijklmnopqr,defghijklmnopqrs,efghijklmnopqrst,fghijklmnopqrstu,ghijklmnopqrstuv,hijklmnopqrstuvw,ijklmnopqrstuvwx,jklmnopqrstuvwxy,klmnopqrstuvwxyz,abcdefghijklmnopq,bcdefghijklmnopqr,cdefghijklmnopqrs,defghijklmnopqrst,efghijklmnopqrstu,fghijklmnopqrstuv,ghijklmnopqrstuvw,hijklmnopqrstuvwx,ijklmnopqrstuvwxy,jklmnopqrstuvwxyz,abcdefghijklmnopqr,bcdefghijklmnopqrs,cdefghijklmnopqrst,defghijklmnopqrstu,efghijklmnopqrstuv,fghijklmnopqrstuvw,ghijklmnopqrstuvwx,hijklmnopqrstuvwxy,ijklmnopqrstuvwxyz,abcdefghijklmnopqrs,bcdefghijklmnopqrst,cdefghijklmnopqrstu,defghijklmnopqrstuv,efghijklmnopqrstuvw,fghijklmnopqrstuvwx,ghijklmnopqrstuvwxy,hijklmnopqrstuvwxyz,abcdefghijklmnopqrst,bcdefghijklmnopqrstu,cdefghijklmnopqrstuv,defghijklmnopqrstuvw,efghijklmnopqrstuvwx,fghijklmnopqrstuvwxy,ghijklmnopqrstuvwxyz,abcdefghijklmnopqrstu,bcdefghijklmnopqrstuv,cdefghijklmnopqrstuvw,defghijklmnopqrstuvwx,efghijklmnopqrstuvwxy,fghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuv,bcdefghijklmnopqrstuvw,cdefghijklmnopqrstuvwx,defghijklmnopqrstuvwxy,efghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvw,bcdefghijklmnopqrstuvwx,cdefghijklmnopqrstuvwxy,defghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwx,bcdefghijklmnopqrstuvwxy,cdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxy,bcdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxyz,
Inner loop should be - for (int k=0;k<len-i;k++) System.out.print(s.substring(k,k+i+1)+", "); Hope that helps
You could try something like this, void printSubstring(String s){ if(s == null){ return; } for(int lenghtSubstring = 1; lenghtSubstring <= s.length(); lenghtSubstring++){ for(int index = 0; index <= s.length() - lenghtSubstring; index++){ System.out.print(s.substring(index, index + lenghtSubstring) + ","); } } }
void printSubstring() { int len = s.length(); for (int i=1;i<len+1;i++) { for (int k=0;k<len-i;k++) System.out.print(s.substring(k,k+i)+", "); } System.out.println(); }
Completely stumped on a multiple loop Java program
The following is NOT a homework problem, it's just a set of problems that I've been working through for practice and I was wondering if anybody else could figure it out: http://codingbat.com/prob/p159339 Return an array that contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3's, but every other number may move. The array contains the same number of 3's and 4's, every 3 has a number after it that is not a 3 or 4, and a 3 appears in the array before any 4. *SOLVED - here is my working code: public int[] fix34(int...nums) { int[] returnArray = new int[nums.length]; //ASSIGN ARRAY //We know that all 3's can't be moved, and after every 3 there //will automatically be a 4 for(int i = 0; i<nums.length; i++) { if(nums[i] == 3) { returnArray[i] = 3; returnArray[i+1] = 4; } } //REBUILD ARRAY - UNMOVED INDEXES //If a value was not moved/affected by the above, it will get placed into the array //in the same position for (int i = 0; i < nums.length; i++) { if (returnArray[i] != 3 && returnArray[i] != 4 && nums[i] != 3 && nums[i] != 4) { returnArray[i] = nums[i]; } } //REBUILD ARRAY - MOVED INDEXES //changed values = 0 in returnArray, as a result, any time we hit a 0 we //can simply assign the value that was in the 4's place in the nums array OuterLoop: for (int i = 0; i < nums.length; i++) { if (returnArray[i] == 0) { for (int n = 0; n < returnArray.length; n++) { if (returnArray[n] == 4) { returnArray[i] = nums[n]; continue OuterLoop; } } } } return returnArray; }
I don't know java, but maybe I can help anyway. i dont want to give you the solution, but think of it like this: you can move every number that isn't a 3. that's our only limit. that being said: the only spots you need to change are the spots following 3s....so....every time you loop through, your program should be aware if it finds a spot after a 3 that isn't a 4.... it should also be aware if it finds any 4s not preceded by a 3...... during each loop, once it's found the location of each of those two things, you should know what to do.
Initialize all the variables for(int i = 0; i<n-1; i++) { if(arr[i] == 3) { if(arr[i+1] == 4) continue; else { temp = 0; while(arr[temp] != 4) temp++; //Write your own code here } //Complete the code } I have NOT provided the entire code. Try completing it as you said it was for your practice.
public int[] fix34(int[] nums) { int[] arr = new int[nums.length]; int index = 0; int tempVal= 0,j=0; for(int i=0;i<nums.length;i++){ if(nums[i]==3){ arr[i] = nums[i]; index=i+1; tempVal = nums[i+1]; j=index; while(j<nums.length){ if(j<nums.length && nums[j]==4){ //System.out.println(j+"\t="+nums[j]); nums[j]=tempVal; nums[index] = 4; break; } j++; } tempVal=0; index=0; }else{ arr[i] = nums[i]; } } index =0; for(int i=0;i<nums.length;i++){ if(nums[i]==3 && nums[i+1]==4){ i+=1; }else if(nums[i]==4){ index = i; j=index; while(j<nums.length){ if(nums[j]==3 && nums[j+1]!=4){ arr[index] = nums[j+1]; arr[j+1] = 4; } j++; } } } return arr; }
Here's mine: A little overkill, but is always right, anyways i make 2 additional arrays and I make 2 passes in the loop putting the correct elements in the correct places. See Logic Below. public int[] fix34(int[] nums) { int index1 = 0; int index2 = 0; int index3 = 0; int[] only4 = fours(nums); //holds all 4's in nums int[] misc = new int[count4(nums)]; //will hold numbers after 3 for(int a = 0; a < nums.length - 1; a++){ if(nums[a] == 3){ misc[index1] = nums[a + 1]; //get it for later use index1++; nums[a + 1] = only4[index2]; //now the number after 3 is a 4, from the index2++; //only4 array } } for(int b = 1; b < nums.length; b++){ if(nums[b] == 4 && nums[b - 1] != 3){ //finds misplaced 4's nums[b] = misc[index3]; //replaces lone 4's with the index3++; //right hand side of each 3 original values. } } return nums; } public int count4(int[] nums){ int cnt = 0; for(int e : nums){ if(e == 4){ cnt++; } } return cnt; } public int[] fours(int[] nums){ int index = 0; int[] onlyFours = new int[count4(nums)]; //must set length for(int e : nums){ if(e == 4){ onlyFours[index] = e; index++; } } return onlyFours; }
I solved mine using two ArrayLists which contain the places of 3's and 4's. I hope this helps. public int[] fix34(int[] nums) { //Create a copy of nums to manipulate. int[] ret = nums; //Create two ArrayLists which carry corresponding places of 3 and 4; ArrayList<Integer> threePositions = new ArrayList<Integer>(); ArrayList<Integer> fourPositions = new ArrayList<Integer>(); //Get the places of 3 and 4 and put them in the respective ArrayLists. for (int i = 0; i < ret.length; i++) { if (ret[i] == 3) { threePositions.add(i); } if (ret[i] == 4) { fourPositions.add(i); } } //Swap all ints right after the 3 with one of the 4s by using the referenced //ArrayLists values. for (int i = 0; i < threePositions.size(); i++) { int temp = ret[threePositions.get(i) + 1]; ret[threePositions.get(i) + 1] = ret[fourPositions.get(i)]; ret[fourPositions.get(i)] = temp; } //Return the ret array. return ret; }