Mysterious error that only appears when declaring the last array - java

When declaring an array, the IDE (Eclipse) gives me an error. However, if I declare another array immediately after, the error shifts to the next array as if by magic. I can try to add more and more arrays, but I'll only be delaying the inevitable. This leaves me with 2 questions: why does error happen and how do I fix it?
import java.util.Arrays;
public class BattleshipGrid {
private char[][] arr1 = new char[10][10];
private char[][] arr2 = new char[10][10];
private char[][] arr3 = new char[10][10];
private char[][] arr4 = new char[10][10];//"Syntax error on token ";", { expected
for (char[] i: arr2) {
for(char j: i) {
i[j]='X';
}
}
public static void main (String[] args) {
}
}

Your for loop must reside in a method of some kind.

For loop itself can't be in a class. The class is just place for declarations, not for code. Code in Java is in methods only.
So you have 2 solutions. Either put your code inside the main method:
import java.util.Arrays;
public class BattleshipGrid {
private static char[][] arr1 = new char[10][10]; // Made it static so that
// it would be bound to the class object itself, so that you can see
// it from the main method which is also static and bound to the class
// object
private static char[][] arr2 = new char[10][10];
private static char[][] arr3 = new char[10][10];
private static char[][] arr4 = new char[10][10];
public static void main (String[] args) {
for (char[] i: arr2) {
for(char j: i) {
i[j]='X';
}
}
}
}
The other (which is the better) solution is to create an instance of the class inside the main method.
import java.util.Arrays;
public class BattleshipGrid {
private char[][] arr1 = new char[10][10];
private char[][] arr2 = new char[10][10];
private char[][] arr3 = new char[10][10];
private char[][] arr4 = new char[10][10];
public void initializeTheGrid() {
for (char[] i: arr2) {
for(char j: i) {
i[j]='X';
}
}
}
public static void main (String[] args) {
BattleshipGrid grid = new BattleshipGrid();
grid.initializeTheGrid();
}
}

Try something like this:
public class BattleshipGrid
{
private char[][] arr1 = new char[10][10];
private char[][] arr2 = new char[10][10];
private char[][] arr3 = new char[10][10];
private char[][] arr4 = new char[10][10];
public static void main ( String[] args )
{
for ( char[] i: arr2)
{
for ( char j: i)
{
j = 'X';
}
}
}
}

Related

Merge Two String array object using java

public class MergeNames {
public static void main(String[] args) {
String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
int na1 = names1.length;
int na2 = names2.length;
String [] result = new String[na1 + na2];
System.arraycopy(names1, 0, result, 0, na1);
System.arraycopy(names2, 0, result, na1, na2);
System.out.println(Arrays.toString(result));
}
}
I created Two Array Object String and Assign Same String values. After need to merge the two String array object into another String array Object.
Note: Without no duplication
I want output like
["Ava", "Emma", "Olivia", "Sophia", "Emma"]
You can use Java Stream API the Stream.of(). See the example for better understanding.
Reference Code
public class Main {
public static <T> Object[] mergeArray(T[] arr1, T[] arr2)
{
return Stream.of(arr1, arr2).flatMap(Stream::of).distinct().toArray();
}
public static void main(String[] args) {
String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
Object [] result = mergeArray(names1, names2);
System.out.println(Arrays.toString(result));
}
}
Output
[Ava, Emma, Olivia, Sophia]
You have small mistake
String [] result = new String[na1 + na2];
not int

access local variable of one method in another

/* This is a question for an online test where the student writes a function whose answer is validated by my 'correctfunction' which is hidden to the student. I want to compare the results of the two functions in main method.
*/
import java.util.Arrays;
class SortArr
{
static int[] arr = new int[10];
public int[] sortin(int[] ans)
{
Arrays.sort(ans);
System.out.println(Arrays.toString(ans));
return ans;
}
public int[] correctfunction(int[] sol)
{
Arrays.sort(sol);
System.out.println(Arrays.toString(sol));
return sol;
}
public static void main(String[] args)
{
arr = new int[] {4,8,3,15,2,21,6,19,11,7};
SortArr ob=new SortArr();
ob.correctfunction(arr);
ob.sortin(arr);
if(Arrays.equals(ob.sol == ob.ans)) //non-static method //equals(Object) cannot be referenced from a static context
//variable ob of type SortArr: cannot find symbol
System.out.println("correct");
else
System.out.println("incorrect");
}
}
First Arrays.equals(parameter1, parameter2) it takes two parameter, and what you did is totally wrong. To fix that see below code
public static void main(String[] args)
{
arr = new int[] {4,8,3,15,2,21,6,19,11,7};
SortArr ob=new SortArr();
int[] newSol = ob.correctfunction(arr);
int[] newAns = ob.sortin(arr);
if(Arrays.equals(newSol, newAns))
System.out.println("correct");
else
System.out.println("incorrect");
}
The function returns an array. So when you call the method ,save the returned arrays in some array variable!
I have made the required changes in your code. Hope they work for you.
import java.util.Arrays;
class SortArr
{
int arr1[];
int arr2[];
static int[] arr = new int[10];
public int[] sortin(int[] ans)
{
Arrays.sort(ans);
System.out.println(Arrays.toString(ans));
return ans;
}
public int[] correctfunction(int[] sol)
{
Arrays.sort(sol);
System.out.println(Arrays.toString(sol));
return sol;
}
public static void main(String[] args)
{
SortArr s = new SortArr(); //make an object of your class
arr = new int[] {4,8,3,15,2,21,6,19,11,7};
SortArr ob=new SortArr();
s.arr1 = ob.correctfunction(arr); // save the returned array
s.arr2 =ob.sortin(arr); // save the returned array
if(s.arr1 == s.arr2)
System.out.print("correct");
else
System.out.print("incorrect");
}
}

Card Game issue in Java

In my code I cannot find a way to assign my human and dealer variables in my method PlayGame() to their respective strings that are made from DealCards().
Whenever I run javac I get an error String[] cannot be converted to String. I don't understand this however because they are separate strings in the dealerOther array in the method DealCards(). Could someone please give me some help on this issue.
import java.util.Random;
public class GAME_8315085 {
static Random rand = new Random();
public static String[] MakeDeck() {
String[] deck=new String[51];
int k=0;
String[] suits={"\u2660", "\u2661", "\u2662", "\u2663"};
String[] ranks={"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
for (int i=0;i<suits.length;i++) {
for (int j=0;j<ranks.length;j++) {
if (suits[i].equals("\u2663") && ranks[j].equals("Q")) {
;
}
else {
deck[k]=ranks[j]+suits[i];
k++;
}
}
}
return deck;
}
public static void ShuffleDeck(String[] deck) {
for (int i=0;i<deck.length;i++) {
int random = rand.nextInt(deck.length);
String tmp=deck[i];
deck[i] = deck[random];
deck[random]=tmp;
}
}
public static String[][] DealCards(String[] deck) {
String[][] dealerOther = new String[2][26];
int j=0;
for (int i=0; i<=deck.length;i+=2) {
dealerOther[0][j]=deck[i];
j++;
}
j=0;
for (int i=1; i<deck.length;i+=2) {
dealerOther[1][j]=deck[i];
j++;
}
return dealerOther;
}
public static void PlayGame() {
String[] deck = MakeDeck();
ShuffleDeck(deck);
String[][] tmp=DealCards(deck);
String human=tmp[0];
String dealer=tmp[1];
}
public static void main(String[] args) {
PlayGame();
}
}
Problem is here
String[][] tmp=DealCards(deck);
String human=tmp[0];
String dealer=tmp[1];
Since tmp is array of arrays of string(kind of 2-D array), the human and dealer has to be array of strings.
Change it to
String[][] tmp=DealCards(deck);
String[] human=tmp[0];
String[] dealer=tmp[1];

How to pass a reference array into a setter?

Write a method called setTo5 which is passed a reference to an array of ints and sets the contents of that array to all 5s. This is what I have so far, and it's giving me an error on the second line after public static void main(...);. How to make a better setter?
public class Set5 {
private static int n = 8;
static int[] boop = new int[n];
public static void main(String[] args){
int[] roop = new int[n];
roop.setTo5(5);
}
public void setTo5(int poop){
for(int i = 0; i<n ; i++){
poop = boop[i];
}
}
}
Try something like this:
public class Set5 {
private static int n = 8;
static int[] boop = new int[n];
public static void main(String[] args){
int[] roop = new int[n];
//Create instance of Set5 class to call setter
Set5 set5reference = new Set5();
set5reference.setTo5(roop);
//All the values in roop will now be 5 as set by setter.
}
//change this method to accept array reference like this
public void setTo5(int[] poop){
for(int i = 0; i<n ; i++){
poop[i] = 5;
}
}
}
To fill an array entirely with some value use:
java.util.Arrays.fill(poop, 5)
In your case:
public class Set5 {
private static int n = 8;
//static int[] boop = new int[n]; // unused variable
public static void main(String[] args){
int[] roop = new int[n];
setTo5(roop);
print(roop);
}
public static void setTo5(int[] poop){
java.util.Arrays.fill(poop, 5)
// for(int i = 0; i<poop.length ; i++){
// poop[i]=5;
//}
}
public static void print(int[] poop){
for(int i = 0; i<poop.length ; i++){
System.out.println("array["+i+"] = "+poop[i]);
}
}
}

final 2D array in Java

If I initialize an array in a Java method like:
final double[][] myArray = new double[r][c];
Will I be allowed to do this later in the method?
myArray[0] = new double[c];
Yes you can. For more on arrays http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
I'll provide you an example of this:
public class Main {
public static void main(String[] args) {
final int[] finalArray = new int[5];
finalArray[0] = 10;
System.out.println(finalArray[0]);
finalArray[0] = 9001;
System.out.println(finalArray[0]);
finalArray = new int[5] //compile error!!!
}
}
This is because the final modifier will say that the reference to the array (the pointer) can't change, but the elements of the array (that could have another pointer) can change with no problem.
EDIT:
Another example with 2d array:
public class Main {
public static void main(String[] args) {
final int[][] array2d = new int[5][];
for(int i = 0; i < array2d.length;i++) {
array2d[i] = new int[6];
}
//the size of the rows can change with no problem.
array2d[0] = new int[8];
}
}

Categories