I can't see what's wrong with my Java code? - java

I am making a program that puts all data from one array, into a different array, backwards.
So, if
String[] originalArray = {"you", "see", "I"};
then it should transfer that into a new array like this:
String[] newArray = new String[3];
newArray = "I", "see", "you"
Here's my code.
public class ReverseArray {
public static void reverse() {
String[] originalArray = {"cool", "really", "are", "You"};
String[] newArray = {"", "", "", ""};
for(int b = 0; b < newArray.length; b++) {
for(int a = 3; a < -1; a--) {
newArray[b] = originalArray[a];
}
}
for(int c = 0; c < newArray.length; c++) {
System.out.print(newArray[c] + "+");
}
}
}
I'm not sure what is wrong. When I try to print it out, it just prints out (+ + + +)
I've tried changing
String[] newArray = {"", "", "", ""};
to
String[] newArray = new String[4];
But it just made then output as
null
Any help?

Your problem is in your inner loop...
for (int a = 3; a < -1; a--) {
Read this out loud...
a equals 3
while a is less than -1 do a--
See where it falls down, the for-loop will only run while a is -1, but you've initialised it to 3
You can actually get away with a single loop, for example...
String[] newArray = new String[originalArray.length];
for (int index = 0; index < newArray.length; index++) {
newArray[index] = originalArray[originalArray.length - index - 1];
}
Basically this uses the index value for both arrays, but adjust the originalArray so it moves from the end instead of the start, as one possible solution ;)

An alternative way using Collections.reverse():
List<String> list = Arrays.asList("cool", "really", "are", "You");
System.out.println(list);
Collections.reverse(list);
System.out.println(list);
Output:
[cool, really, are, You]
[You, are, really, cool]

Okay, so the steps are the following:
You have an array A of size X. You want to put these elements in an array B of size X. So basically what you want is that the element in A[0] (the first element) is in the last position of B, being B[2]. To do this, you need to calculate the "reverse" index.
So first you loop over your array:
for(int index = 0; index < A.length;index++)
{
String thisElement = A[index];
}
Next, you want to put it in the other array at the last position, right? So then you need to take the length of that array, minus the current index.
for(int index = 0; index < A.length;index++)
{
String thisElement = A[index];
// The other index
int otherIndex = (B.length - 1) - index; // We do -1 because we have zero-indexing.
B[otherIndex] = thisElement;
}
This should now contain all your elements in reverse order.
Some things you did wrong
I've tried changing
String[] newArray = {"", "", "", ""};
to
String[] newArray = new String[4];
These things are basically the same. The latter tells the compiler "Give me room for 4 strings". In the former you give it 4 strings and it makes room for them. So that's not really necesarry, but correct.
for(int b = 0; b < newArray.length; b++) {
for(int a = 3; a < -1; a--) {
newArray[b] = originalArray[a];
}
}
This piece of code is quite wrong as well. You walk over your array in the outer loop. And for each element you try to loop again. That is not needed either. Even so, your loop goes from 3 to 2 to ... But the condition is "as long as a is smaller than -1". It is not smaller than -1 to start with, so this loop will never execute.

You have big problems in your code here:
for(int b = 0; b < newArray.length; b++) {
for(int a = 3; a < -1; a--) {
newArray[b] = originalArray[a];
}
}
With "a < -1" you probably wanted "a > -1" otherwise the inner loop does not start. But most importantly you have two nested loops (two for loops) which doesn't make sense, you need only one for loop two reverse an array and you don't even need the new array to put the result:
for (i = 0; i < originalArray.length / 2; i++) {
int temp = originalArray[i];
originalArray[i] = originalArray[originalArray.length - 1 - i];
originalArray[originalArray.length - 1 - i] = temp;
}
This for loop works from both sides of the array inwards replacing the positions.
When you reach code mastery (or are not required to provide your own algorithm) you'll just use:
Collections.reverse()
:)

Related

Trying to create a array with the intersection of two arrays but fails at creating array with the proper structure

So, I am trying to create 2 randomly generated arrays,(a, and b, each with 10 unique whole numbers from 0 to 20), and then creating 2 arrays with the info of the last two. One containing the numbers that appear in both a and b, and another with the numbers that are unique to a and to b. The arrays must be listed in a "a -> [1, 2, 3,...]" format. At the moment I only know how to generate the 2 arrays, and am currently at the Intersection part. The problem is, that I can create a array with the correct list of numbers, but it will have the same length of the other two, and the spaces where it shouldn't have anything, it will be filled with 0s when its supposed to create a smaller array with only the right numbers.
package tps.tp1.pack2Arrays;
public class P02ArraysExtractUniqsAndReps {
public static void main(String[] args) {
int nbr = 10;
int min = 0;
int max = 20;
generateArray(nbr, min, max);
System.out.println();
}
public static int[] generateArray(int nbr, int min, int max) {
int[] a = new int[nbr];
int[] b = new int[nbr];
int[] s = new int[nbr];
s[0] = 0;
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * (max - min));
b[i] = (int) (Math.random() * (max - min));
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
i--;
}
if (b[i] == b[j]) {
i--;
}
}
}
System.out.println("a - > " + Arrays.toString(a));
System.out.println("b - > " + Arrays.toString(b));
for (int k = 0; k < a.length; k++) {
for (int l = 0; l < b.length; l++) {
if (a[k] == b[l]) {
s[l] = b[l];
}else {
}
}
}
System.out.println("(a ∪ (b/(a ∩ b)) - > " + Arrays.toString(s));
return null;
}
public static boolean hasValue(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
}
Is there any way to create the array without the incorrect 0s? (I say incorrect because it is possible to have 0 in both a and b).
Any help/clarification is appreciated.
First, allocate an array large enough to hold the intersection. It needs to be no bigger that the smaller of the source arrays.
When you add a value to the intersection array, always add it starting at the beginning of the array. Use a counter to update the next position. This also allows the value 0 to be a valid value.
Then when finished. use Array.copyOf() to copy only the first part of the array to itself, thus removing the empty (unfilled 0 value) spaces. This works as follow assuming count is the index you have been using to add to the array: Assume count = 3
int[] inter = {1,2,3,0,0,0,0};
inter = Arrays.copyOf(inter, count);
System.out.println(Arrays.toString(inter);
prints
[1,2,3]
Here is an approach using a List
int[] b = {4,3,1,2,5,0,2};
int [] a = {3,5,2,3,7,8,2,0,9,10};
Add one of the arrays to the list.
List<Integer> list = new ArrayList<>();
for(int i : a) {
list.add(i);
}
Allocate the intersection array with count used as the next location. It doesn't matter which array's length you use.
int count = 0;
int [] intersection = new int[a.length];
Now simply iterate thru the other array.
if the list contains the value, add it to the intersection array.
then remove it from the list and increment count. NOTE - The removed value must be converted to an Integer object, otherwise, if a simple int value, it would be interpreted as an index and the value at that index would be removed and not the actual value itself (or an Exception might be thrown).
once finished the intersection array will have the values and probably unseen zeroes at the end.
for(int i = 0; i < b.length; i++) {
int val = b[i];
if (list.contains(val)) {
intersection[count++] = val;
list.remove(Integer.valueOf(val));
}
}
To shorten the array, use the copy method mentioned above.
intersection = Arrays.copyOf(intersection, count);
System.out.println(Arrays.toString(intersection));
prints
[3, 2, 5, 0, 2]
Note that it does not matter which array is which. If you reverse the arrays for a and b above, the same intersection will result, albeit in a different order.
The first thing I notice is that you are declaring your intersection array at the top of the method.
int[] s = new int[nbr];
You are declaring the same amount of space for the array regardless of the amount you actually use.
Method Arrays.toString(int []) will print any uninitialized slots in the array as "0"
There are several different approaches you can take here:
You can delay initializing the array until you have determined the size of the set you are dealing with.
You can transfer your content into another well sized array after figuring out your result set.
You could forego using Array.toString, and build the string up yourself.

Find the maximum of the length of 2 arrays

I am passing 2 arrays to the controller with different lengths, I want to execute a for loop and length of that will be the max of the length of 2 arrays.
I am not getting how to execute that. I tried Math.max but its giving me error as cannot assign a value to the final variable length.
String[] x =0;
x.length = Math.max(y.length,z.length);
for(int i=0; i < x.length; i++)
The no of elements in x and y are not fixed. it changes what we are passing from the front end.
Initialize the new array with the desired length:
String[] x = new String[Math.max(y.length,z.length)];
In case you don't need to create an array, just use the result of Math.max as conditional to stop your loop:
for (int i = 0; i < Math.max(y.length,z.length); i++) {
//...
}
Just bring your Math.max() operation into the array's initialization.
String[] x = new String[Math.max(y.length, z.length)];
Here's an expansion for clarity:
int xLength = Math.max(y.length, z.length);
String[] x = new String[xLength];
Edit: Unless, OP, you're not interested in creating another array...
I want to execute a for loop and length of that will be the max of the length of 2 arrays
Just bring your Math.max() operation into your for loop:
for(int i=0; i < Math.max(y.length, z.length); i++){
//code here
}
Set a variable to the maximum length of the arrays, create a new array with that length and then loop until that point.
int maxLen = Math.max(y.length, x.length);
String[] array = new String[maxLen];
for(int i = 0; i < maxLen; i++){
// Loop code here
}
int max_length = Math.max(y.length,z.length);
for(int i=0; i < max_length ; i++){
//...
}
you can use that max_length to create a new String[] if you are trying to create an array with total length of y and z arrays, like
String[] newArray = new String[max_length];

2D array not printing the last element during comparison

I am trying to replace rows from an original 2d array to a updated 2d array. Problem is it won't store the last element during the replacement.
Here's my code:
String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};
String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};
for (int i = 0; i < updatedArray.length;i++ ) {
for (int j = 0; j < updatedArray[i].length; j++){
for(int x = 0; x < originalArray.length;x++){
for(int z = 0; z < originalArray[x].length;z++){
if(originalArray[x][0].equals(updatedArray[i][0])) {
updatedArray[i][j] = originalArray[x][j];
System.out.println("There's a match!!");
}else{
System.out.println("No match!");
}
}
}
}
}
System.out.println("originalArray:");
System.out.println(Arrays.deepToString(originalArray));
System.out.println("updatedArray:");
System.out.println(Arrays.deepToString(updatedArray));
For example, initially updatedArray in last row "purple" has {"purple","a","b","c"}. When it does the replacement using values from originalArray, the code above only outputs:
... [purple, nn, mm, bb]
which is wrong because it doesn't add the last element "hello". It should output:
... [purple, nn, mm, bb, hello]
I am aware the problem is in this line:
updatedArray[i][j] = originalArray[x][j];
Problem is no matter what I try to change originalArray[x][j] to originalArray[x][z] ... its screws up everything.
Any ideas on this? Still trying to get the jist of 2D arrays.
If there is a match, instead of trying to set each element in the updatedArray to the corresponding element in the original array you can just set the entire array to the original array.
String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};
String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};
for (int i = 0; i < updatedArray.length;i++ ) {
for (int j = 0; j < originalArray.length; j++){
if(originalArray[j][0].equals(updatedArray[i][0])) {
updatedArray[i] = originalArray[j];
System.out.println("There's a match!!");
}else{
System.out.println("No match!");
}
}
}
The issue is how you chose to iterate over the dimensions of updatedArray which are different than the dimensions of originalArray.
Let just look at the case i=2 which is the 'row' for purple:
for (int j = 0; j < updatedArray[i].length; j++){
updatedArray[i=2].length = 4
in updated:
index = 0 , 1 , 2 , 3
{"purple","a","b","c"}
in original:
index = 0 , 1 , 2 , 3 , 4
{"purple","nn","mm","bb","hello"}
Therefore since j will always be < 4 it can never be used to index originalArray[x][4] = "hello"
DANGER: this code also doesn't handle the fact that you would need to extend the purple array for updatedArray. Java may do some magic to handle this for you but I wouldn't trust it to work that way.
Suggestion:
- compare the lengths of each row and allocate extra memory where necessary before copying data from originalArray to updatedArray
- if possible just copy the whole row between original and updated.

Appending to double Array method

So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.

How do you add two int arrays with different lengths?

I've been working on a Java lab that wants us to have the user enter two digits up to 50 digits long and add them together. I've successfully been able to complete everything except for when the two arrays have a different length. I've been toying around with the code for a while, but I keep coming up short. Can anyone look at the code for this and have any suggestions? Thanks!
int[] number1 = new int[input1.length()];
int[] number2 = new int[input2.length()];
int[] answer = new int[input1.length()];
if(number1.length > number2.length){
number2 = new int[number1.length];
for(int i = 0; i < number2.length - number1.length; i++){
number2[i] = 0;
}
}
if(number2.length > number1.length){
number1 = new int[number2.length];
for(int i = 0; i < number1.length - number2.length; i++){
number1[i] = 0;
}
}
Whenever I add, say 120 and 12, it says there's an Array out of bounds error.
First thing you need to do is get the numbers into an int array. Do that by Splitting string to char array. Then convert to int array. Then add.
String input1 = scanner.nextLine().trim(); <-- get input as String
String input2 = scanner.nextLine().trim();
char[] array1 = input1.toCharArray(); <-- split to char array
char[] array2 = input2.toCharArray();
// convert to int array
int[] intArray1 = new int[array1.length]; <-- declare int array
int[] intArray2 = new int[array2.length];
for (int i = 0; i < array1.length; i++){
intArray1[i] = Integer.parseInt(String.valueOf(array1[i])); <-- convert to int
}
for (int i = 0; i < array2.legnth; i++){
intArray2[i] = Integer.parseInt(String.valueOf(array2[i]));
}
// check which one is larger and add to that one
if (intArray1.length > intArray2.length){
for (int i = 0; i < intArray2.length; i++){
intArray1[i] += intArray2[i]; <-- add values
}
System.out.println(Arrays.toString(intArray1); <-- print largest
} else {
for (int i = 0; i < intArray1.length; i++){
intArray2[i] += intArray1[i];
}
System.out.println(Arrays.toString(intArray2);
}
If you want to get the number representation printed instead of an array, instead of the System.out.println(), use this
StringBuilder sb = new StringBuilder();
for (int i : intArray1){
sb.append(String.valueOf(i));
}
System.out.println(sb.toString());
So 123 and 12 will print out 233
My understanding of your code is, you try to pre-append (push from head) 0s to the shorter array. Look at the first if-block. The length of number1 is larger than what of number2. Thus, number2.length - number1.length is negtive. Then, in the for loop, i < number2.length - number1.length is always ture. (I am not familiar with java. I guess array's length is an integer.) And you still have to copy the rest of array.
The correct code should be,
if(number1.length > number2.length) {
int[] number3 = new int[number1.length];
for(int i = 0; i < number1.length - number2.length; ++i) {
number3[i] = 0;
}
for(int i = 0; i < number2.length; ++i) {
number3[i + number1.length - number2.length] = number2[i];
}
number2 = number3;
}
BTW, the second if-block should be changed in a similar way. Perhaps, java provides an API link insert(0, 0) for array object. It will be easier to implement.

Categories