This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 2 years ago.
Here is what I'm supposed to do:
Write a program to read a 2-D array of 4x4. Then read the first element of the array and compare it with the third element of each column. Replace the smaller value with the larger values of the two. Create a method called swap to swap the values.
I'm not sure what I'm doing wrong and I'm just starting to learn arrays. My teacher is very conceptual and isn't very concrete on his definition so I'm having trouble with it. I keep receiving a .class expected error.
public class Array {
public static void main(String[] args) {
int num [][] = {{4, 6, 7, 2},
{5, 12, 9, 8},
{1, 0, 3, 10},
{5, 3, 14, 11}};
System.out.println("the array elements are:");
for(int i = 0; i < num.length; i++){
System.out.println();
for(int j = 0; j < num[i].length; j++)
System.out.print(num[i][j] + " ");
}
System.out.println("swaped elements are:");
for(int i = 0; i < num.length; i++){
System.out.println();
for(int j = 0; j < num[i].length; j++)
System.out.print(swap(num[][]) + " ");
}
}
public static void swap (int x[][]){
for(int i = 0; i < x.length; i++){
int temp = x[0][i];
if (x[0][i] > x[2][i] ){
x[2][i] = temp;
x[0][i] = x[2][i];
}
}
}
}
swap() doesn't return anything. Even if you did resolve the other issue (num[][] is a syntax error), you'd need to specify something to return from swap. Hint: probably the array you modified.
Write a program to read a 2-D array of 4x4.
I don't see you reading something. Just initializing it. Maybe you should read from stdin or from a file?
Then read the first element of the array and compare it with the third element of each column.
Replace the smaller value with the larger values of the two.
Create a method called swap to swap the values
As a swap method I would expect a method with 4 indexes for the 2 positions in the 2D-Array, where the values to swap are located.
public static void swap (int x[][], int i1, int i2, int j1, int j2) {
int temp = x[i1][j1];
x[i1][j1] = x[i2][j2];
x[i2][j2] = temp;
}
Have you heard about the simplified for-loop?
public static void show (int x[][]) {
for (int [] inner : x)
for (int i : inner)
System.out.print (i + " ");
}
Related
For my assignment, I need to write a method that returns the number of cows (see definition below) found between 2 arrays. If the input arrays have a different number of elements, then the method should throw an IllegalArgumentException with an appropriate message.
A bull is a common number in int arrays found at the same position while a cow is a common number in int arrays found at different position. Note that if a number is already a bull, it cannot be considered as a cow.
For example, considering the following arrays:
int[] secret = {2, 0, 6, 9};
int[] guessOne = {9, 5, 6, 2};
int[] guessTwo = {2, 0, 6, 2};
int[] guessThree = {1, 2, 3, 4, 5, 6};
int[] guessFour = {1, 3, 4, 4, 0, 5};
1) getNumOfCows(secret, guessOne) returns 2
2) getNumOfCows(secret, guessTwo) returns 0
3) getNumOfCows(secret, guessThree) returns an exception
4) getNumOfCows(guessThree, guessFour) returns 2
My method seen below works perfectly for examples 1 and 3, but there is a problem with examples 2 and 4 such that getNumOfCows(secret, guessTwo) returns 1 instead of 0 because the element at secret[0] and guessTwo[3] is considered a cow. Could anybody help me fix my code?
// A method that gets the number of cows in a guess --- TO BE FIXED
public static int getNumOfCows(int[] secretNumber, int[] guessedNumber) {
// Initialize and declare a variable that acts as a counter
int numberOfCows = 0;
// Initialize and declare an array
int[] verified = new int[secretNumber.length];
if (guessedNumber.length == secretNumber.length) {
// Loop through all the elements of both arrays to see if there is any matching digit
for (int i = 0; i < guessedNumber.length; i++) {
// Check if the digits represent a bull
if (guessedNumber[i] == secretNumber[i]) {
verified[i] = 1;
}
}
for (int i = 0; i < guessedNumber.length; i++) {
// Continue to the next iteration if the digits represent a bull
if (verified[i] == 1) {
continue;
}
else {
for (int j = 0; j < secretNumber.length; j++) {
if (guessedNumber[i] == secretNumber[j] && i != j) {
// Update the variable
numberOfCows++;
verified[i] = 1;
}
}
}
}
}
else {
// Throw an IllegalArgumentException
throw new IllegalArgumentException ("Both array must contain the same number of elements");
}
return numberOfCows;
}
First go through and mark all bulls using a separate array to make sure a position that is a bull also get counted as a cow
public static int getNumOfCows(int[] secretNumber, int[] guessedNumber) {
int max = secretNumber.length;
int cows = 0;
int[] checked = new int[max];
for (int i = 0; i < max; i++) {
if (secretNumber[i] == guessedNumber[i]) {
checked[i] = 1;
}
}
for (int i = 0; i < max; i++) {
if (checked[i] == 1) {
continue;
}
for (int j = 0; j < max; j++) {
if (secretNumber[i] == guessedNumber[j]) {
cows++;
checked[i] = 1;
}
}
}
return cows;
}
Now that this answer is accepted the original question can be voted to be closed as a duplicate
I am posting my answer from a duplicate question here and if this get approved then the other one can get closed as a duplicate.
The problem is that an element that is multiple times in at least one array will not be handled correctly.
A possible solution idea might be this one:
Create a cow list.
Iterate through both arrays and add every element that is in both arrays and has not been added yet. (note: complexity is n²)
Now that all possible cows are in the list, iterate through the array positions with the same index and if you find a bull, remove the number from the cow list.
Now the cow list contains only cows.
This solution might be a bit slower than your current one, but I think it's working properly.
First of all, I easily got this to work with the regular way of populating and accessing data from an array, so that as a suggested solution isn't what I'm looking for. I'm trying to better understand how to populate and access data from a multi-dimensional array. When I run the program the NetBeans error message is: cannot find symbol, symbol: method get(int), location: class Integer. I've looked at the .get() method for ArrayList and to me it seems like I'm correctly trying to access that data but something isn't right. Also, on the last statement of the program code NetBeans says incompatible types: ArrayList<Integer> cannot be converted to Object[]. I'm guessing that's because when I'm trying print the values of each nested element each value wants to be accessed as a String, it's just a guess.
So the the array I want to populate should look like this: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], and output should look something like below.
1 2 3 4
5 6 7 8
9 10 11 12
// TwoDimensionalArray_v2.java
// demonstrates populating and accessing elements from a two-dimensional array
package twodimensionalarray_v2;
import java.util.*;
public class TwoDimensionalArray_v2 {
public static void main(String args[]) {
// declare a dynamic array of class type Integer
ArrayList<Integer> table = new ArrayList<>();
// loop variables
int i, j;
// populate the array one nested element at a time
for (i = 0; i < 3; ++i) {
for (j = 0; j < 4; ++j) {
table.set(i, (i * 4) + j + 1);
// >>>>> NetBeans error message is for the below line on .get(j) <<<<<
System.out.print(table.get(i).get(j) + " ");
}
System.out.println();
}
// print 'table'
System.out.println();
System.out.println(Arrays.deepToString(table));
}
}
A list is a one-dimensional structure but you can use any aggregate for elements. Another List as element results in a two-dimensional array.
List<List<Integer>> table = new ArrayList<>();
// populate the array one nested element at a time
for (int i = 0; i < 3; ++i) {
List<Integer> row;
table.add( row = new ArrayList<Integer>() );
for (int j = 0; j < 4; ++j) {
row.add( (i * 4) + j + 1);
}
}
for (int i = 0; i < table.size(); ++i) {
for (int j = 0; j < table.get(i).size(); ++j) {
System.out.print( " " + table.get(i).get(j));
}
System.out.println();
}
You could do the same using proper arrays.
your table is Arraylist ,
table.get(i)
will give you integer value that you had set at particulate position, as you are setting integer in array with line:
table.set(i, (i * 4) + j + 1);
so get(i) gives you integer value only not a array or list
Yep. sorry.
You cannot access get(j) because the List is just a list (one dimension).
You should use an primitive Array[][]
This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 7 years ago.
I have a basic java question - I have an array and I need to do a multiplication of all the elements, so for input:
1 2 3
The output will be:
1 2 3
2 4 8
3 6 9
How can I print the 2d array from the main ?
PS - I want the method just to return the new 2d array, without printing it ( I know I can do it without the method and and print mat[i][j] within the nested loop)
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3};
System.out.println(matrix(array));
}
public static int[][] matrix(int[] array){
int[][] mat = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
mat[i][j] = array[i] * array[j];
}
}
return mat;
}
}
You have to print all the individual elements of the array, because if you just try to print an array, it will print all kinds of other stuff you might not want to see. So you cherry pick out what you want, and format it a little. In the below code you have each element printed, seperated on a space until it reaches a new row, where it then jumps to a new line.
int[][] matrixArray = matrix(array);
for(int i = 0, i < matrixArray.length; i++) {
for(int j = 0; j < matrixArray[0].length; j++) {
System.out.print(matrixArray[i][j] + " ");
}
System.out.println();
}
I have to list out 10 unique numbers between 1 and 20, but before storing the numbers, the program should check whether the number is in the list or not. If the number is already in the list, it should generate a new number. Also, the amount of numbers replaced must be counted.
This is what I have so far:
public static void main(String[] args)
{
int[] arrayA = {16, 14, 20, 3, 6, 3, 9, 1, 11, 2};
System.out.print("List: ");
for(int w = 0; w < arrayA.length; w++)
{
System.out.print(arrayA[w] + " ");
}
}
As you can see, there are two "3"s on the list, I have to output the same list but change one of the "3"s. Plus it has to be counted.
This is not hard to do, but what do you mean by change one of the threes?
You can add a boolean flag outside of your for loop that can tell if you've encountered a 3 or not and what the index of that 3 is.
Try something like this:
boolean changedThree = false;
int threeIndex = -1;
for(int i = 0; i < arrayA.length; i++){
if(arrayA[i] == 3 && !changedThree){
arrayA[i] = 4;
threeIndex = i;
changedThree = true;
}
System.out.println(arrayA[i] + " ");
}
I don't know for sure if that captures the information you need, but hopefully can give you a push in the right direction. Let me know if you have questions.
EDIT
To avoid any duplicate values, I recommend you create an array list, and add the unique values to it. Then, you can use the ArrayList.contains() method to see if a value exists already. So, I would recommend changing your code to this:
ArrayList<int> usedCharacters = new ArrayList<int>();
int changedCounter = 0;
Random rand = new Random();
for(int i = 0; i < arrayA.length; i++){
if(!usedCharacters.contains(arrayA[i])){ // If we haven't used this number yet
usedCharacters.add(arrayA[i]);
} else{
// Generate a new number - make sure we aren't creating a duplicate
int temp = rand.nextInt(20) + 1;
while(usedCharacters.contains(temp)){
temp = rand.nextInt(20) + 1;
}
// Assign new variable, increment counter
arrayA[i] = temp;
changedCounter++;
}
}
If you're not familiar with the random.nextInt() method, read this.
so if I understand you correctly you have to save the arrayA, right?
If that is the case, you can just make a new array, targetArray where you can save to numbers to, and then check using a for-loop if you already added it, and if so you can generate a new, random number.
The result would look something like this:
public static void main(String[] args) {
int[] arrayA = {16, 14, 20, 3, 6, 3, 9, 1, 11, 2};
int[] targetArray = new int[10];
int numbersReplaced = 0;
System.out.print("List: ");
for (int i = 0; i < arrayA.length; i++) {
for (int j = 0; j < targetArray.length; j++) {
if (arrayA[i] == targetArray[j]) {
targetArray[j] = (int)(Math.random() * 100);
numbersReplaced++;
} else {
targetArray[j] = arrayA[i];
}
}
}
System.out.println("Numbers replaced: " + numbersReplaced);
}
Hope that helped
You could use recursion to achieve your result.
This will keep looping until all values are unique
private void removeDoubles(int[] arr) {
for(int i = 0; i < arr.length; i++)
{
// iterate over the same list
for(int j = 0; j < arr.length; j++) {
// Now if both indexes are different, but the values are the same, you generate a new random and repeat the process
if(j != i && arr[i] == arr[j]) {
// Generate new random
arr[j] = random.nextInt(20);
// Repeat
removeDoubles(arr);
}
}
}
}
Note: This is the sort of question I prefer to give guidance answers rather than just paste in code.
You could walk the array backward looking at the preceding sublist. If it contain the current number you replace with a new one.
Get the sublist with something like Arrays.asList(array).subList(0, i) and then use .contains().
You logic for finding what number to add depends on lots of stuff, but at it simplest, you might need to walk the array once first to find the "available" numbers--and store them in a new list. Pull a new number from that list each time you need to replace.
EDIT: As suggested in the comments you can make use of Java Set here as well. See the Set docs.
A project I am doing requires me to find horizontal and vertical sums in 2 dimensional arrays. So pretty much its a word search (not using diagonals) but instead of finding words, the program looks for adjacent numbers that add up to int sumToFind. The code below is what I have come up with so far to find horizontal sums, and we are supposed to implement a public static int[][] verticalSums as well. Since I have not yet completed the program I was wondering, first of all, if what I have will work and, secondly, how the array verticalSums will differ from the code below. Thank you
public static int[][] horizontalSums(int[][] a, int sumToFind) {
int i;
int start;
int sum = 0;
int copy;
int [][] b = new int [a[0].length] [a.length];
for (int row = 0; row < a.length; row++) {
for ( start = 0; start < a.length; start++) {
i = start;
sum = i;
do {
i++;
sum = sum + a[row][start];
}
while (sum < sumToFind);
if(sum == sumToFind) {
for (copy = start; copy <= i; copy++) {
b[copy] = a[copy];
}
}
for (i = 0; i < a[0].length; i++) {
if (b[row][i] != a[row][i])
b[row][i] = 0;
}
}
}
return b;
}
Your code won't work.... (and your question is "if what I have will work?" so this is your answer).
You declare the int[][] b array as new int [a[0].length] [a.length] but I think you mean: new int [a.length] [a[0].length] because you base the row variable off a.length, and later use a[row][i].
So, if your array is 'rectangular' rather than square, you will have index-out-of-bounds problems on your b array.
Your comments are non-existent, and that makes your question/code hard to read.
Also, you have the following problems:
you set sum = i where i = start and start is the index in the array, not the array value. So, your sum will never be right because you are summing the index, not the array value.
in the do..while loop you increment i++ but you keep using sum = sum + a[row][start] so you just keep adding the value to itself, not the 'next' value.
At this point it is obvious that your code is horribly broken.
You need to get friendly with someone who can show you how the debugger works, and you can step through your problems in a more contained way.
Test is very simple
public static void main(String[] args) {
int[][] a = {{1, 2}, {1, 0}};
int[][] result = Stos.horizontalSums(a, 1);
System.out.println(Arrays.deepToString(result));
}
Result
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
When you fix this problem, then this should print something like this
[[1, 2], [1, 0]]