Syntax error when declaring array in java - java

I'm trying to declare an array in java as part of a tic-tac-toe game, but I get syntax error when I do this:
package tictactoe;
import java.util.Random;
import java.util.Scanner;
public String a[] = new String[9];
a[0]="";
public class Board {
I thought this was the correct way to declare an array, and all the examples I look at confirm it, so why do I get a syntax error?

You need to put the declaration of your array inside your class.
You also need to put the assignment of the array inside a method (inside your class). You could also place the assignment in the constructor.
So your code would look something like this:
package tictactoe;
import java.util.Random;
import java.util.Scanner;
public class Board {
public String[] a = new String[9];
public Board() {
a[0] = "";
}
}

You are tring to declear variable outside of class body that's not correct.
you should move your array definition inside of class and initilize it in class constructor (for example).
public class Board {
public String a[] = new String[9];
public Board() {
a[0] = "";
}
}

In java, everything has to be inside a class. You cant leave it outside the class and initialize it inside the constructor to make look more clean.
public class Board {
public String a[] = new String[9];
Board(){
a[0]=" ";
}
}
If you want to see the value initialized, then
public class Board {
public static String a[] = new String[9];
Board(){
a[0]=" ";
}
public static void main(String []args){
System.out.println(" Initialially :"+a[0]);
}
}

Everything (except the import statements) in Java MUST be inside a class. Then you need to write your code to be executed inside a method. Your declaration of an array outside a class has no meaning, because that way it's not a member of any class.
Java is not a scripting language. You cannot write code outside a class.
package tictactoe;
import java.util.Random;
import java.util.Scanner;
public class Board {
public String a[] = new String[9];
//methods here
}

Related

How do i make a static reference to a non-static method?

import java.util.Iterator;
import java.util.ArrayList;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
ArrayList<String> original = new ArrayList<>(Arrays.asList("afd", "asdf", "aavdd", "sajf", "adnf", "afd", "fjfn"));
String find = "afd";
String replaceWith = "asd";
System.out.println(replaceIt(original, find, replaceWith));
}
public ArrayList<String> replaceIt(ArrayList<String> original, String find, String replaceWith){
ArrayList<String> newList = new ArrayList<String>();
for(int y = 0; y<original.size(); i++){
if(!original.get(y).equals(find))
newList.set(y, original.get(y));
newList.set(y, replaceWith);
}
original = newList;
return original;
}
}
How do i call the replaceIt method? I'm confused and I need to make it so it prints the output of that function. I'm so confused somebody please help.
public ArrayList<String> replaceIt() is an instance method, it is only called from Main instances/objects.
public static void main is a static method of class Main, static methods can’t access instance methods and instance variables directly.
Therefor, to call replaceIt() method from static main method, make replaceIt() static.
public static ArrayList<String> replaceIt(/*arguments*/){
//your code goes here
}
Having non-static method in Main is a little odd. It's not like you are going to construct new instances of Main (say, the same way you would construct new instances of a Person class).
These type of generic helpers/utils functions usually go into some sort Utils.java or Helpers.java class, and are declared as static in these files. This way you would be able to invoke: Utils.replaceIt(original, find, replaceWith));
Because replaceIt() is an instance method, you simply need to create an instance of the Main class to call it -
public static void main(String[] args) {
...
Main m = new Main();
System.out.println(m.replaceIt(original, find, replaceWith));
}

Why can I not access an instance of class that is created in a constructor ( Java )

To preface the question, I'm very new to Java.
I have classes called, Game, Player, and SystemIO.
My main() is in the Game class. Below is it's code
public static void main(String[] args){
SystemIO systemIO = new SystemIO();
}
Once SystemIO is called, it's constructor creates an instance of Player with the line
Player player = new Player("Bob");
where the Player constructor takes 1 argument as a String.
Further down in the SystemIO class I have a method that accesses information from "player" the instance.
player.getName();
When I try to do this, the console reports
SystemIO.java:339: error: cannot find symbol
I have checked that I am not trying to reference the class name with a capital "Player."
Like I said, I'm extremely new to Java and just trying to wrap my head around it and I believe it's a scope issue...but I'm not sure.
Edit to add reproducible code:
Game.java
package com.myapps;
import com.myapps.system.SystemIO;
public class Game{
public static void main(String[] args){
SystemIO systemIO = new SystemIO();
}
}
Player.java
package com.myapps.player;
public class Player{
String name;
public Player(String playerName){
name = playerName;
}
}
public String getName(){
return name;
}
SystemIO.java
package com.myapps.system;
import com.myapps.player.Player;
public class SystemIO{
public SystemIO(){
Player player = new Player("Bob");
readPlayerName();
}
public void readPlayerName(){
System.out.println(player.getName());
}
}
Make player a class variable.
Put someone in your class:
Player player;
and change the code of your constructor to:
player = new Player("Bob");
This is called a scope error. A variable that you want to be accessable to ALL the methods of the class, should be declared IN the class and not in ONE specific method (in your case, you did it in the constructor)

Creating multiple Java objects inside Loop and using all outside

I want to create multiple objects inside while loop and access all objects outside in JAVA 8.
Currently using a list to store the obects, but all objects get replaced by one last object (last created).
I have tried initializing list inside try, outside try, nothing works.
Here is my test1.java,
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class test1 {
public static void main(String[] args){
try {
List<test2> objList=new ArrayList<>();
BufferedReader encReader = new BufferedReader(new FileReader("./asd.txt"));
String eachLine;
while ((eachLine = encReader.readLine()) != null) {
String[] data = eachLine.split("\\|");
if(true){
objList.add(new test2(data[0], data[1]));
}
} // While ends here
objList.forEach(x -> x.printEncLoc());
}catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my test2.java,
public class test2 {
private static String s1;
private static String s2;
test2(String s1new, String s2new){
s1=s1new;
s2=s2new;
}
public static void printEncLoc(){
System.out.println("s1:"+s1+" s2:"+s2);
}
}
Here is my input file example (asd.txt)
hello|123
qwe|klj
It calls only the last object's printEncLoc function each time in the forEach line.
It prints output as follows.
s1:qwe s2:klj
s1:qwe s2:klj
What is the problem here?
You made the properties in test2 static, this means all instances share the same properties. So when you change them for the 2nd row, the 1st row changes as well.
Remove the 'static' from s1 and s2, and from your printEncLoc() method and your code works.
EDIT: See https://www.baeldung.com/java-static for more on how static works

Class/Object/Method Organization Confusion

I'm beginning at Java, so the thinking behind organizing my code so it's cohesive isn't really coming naturally yet. Essentially, I have an ArrayList that has a method that populates it, another that shuffles it, and then a tester program to see if that even worked. My problem is organizing it. From my experience methods can't really see what's in each other, so I have it organized like so:
Class
ArrayList (named al)
Tester Method
Shuffle Method
ArrayList Population Method
My trouble is thusly; how do I, in the tester method, make the ArrayList undergo the actions defined for it in the methods. I've worked with Constructors and Objects, but they don't really seem to apply at least is what I've done so far. I thought it would be something like
al.Shuffle();
But it threw errors all over the place. Does anyone have any insight?
EDIT: as requested, here's the code
package deckofcards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class Deck{
ArrayList<String> al = new ArrayList<String>();
//test method
public void main(String[] args){
Scanner input = new Scanner(System.in);
al.Deck();
//didn't get any further, that threw a "cannot find symbol" error
}
}
private void Shuffle(){
Collections.shuffle(al);
}
private void Deck(){
al.add(0, "Ace of Spades");
//and this goes on for a deck of cards
}
}
In Your components, the class is the main component that holds the rest of your component, then the methods is a task or action that the class can do.
ArrayList is a data structure that holds a data with a specific structure. which the class can use it.
so you orginization could look like this:
class MyClass {
private ArrayList<String> list = new ArrayList<String>();
public static void main(String[] args) {//Tester Method is the main method, because the execution began from here
}
private void populate() {
//
}
private void shuffle() {
//
}
}
Define another class that extends ArrayList
public class MyArrayList extends ArrayList<Object> {
public MyArrayList(){
super();
}
public MyArrayList shuffle(MyArrayList mal){
Collections.shuffle(mal);
return mal;
}
}
And then define everything as MyArrayList. This will basically be the exact same class as ArrayList with extra functionality you want.
public class Deck {
static MyArrayList al = new MyArrayList();
//test method
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Deck();
al = al.shuffle(al);
//didn't get any further, that threw a "cannot find symbol" error
for(Object i : al)
System.out.println(i);
}
private static void Deck(){
al.add(0, "Ace of Spades");
al.add(1, "1");
al.add(2, "2");
al.add(3, "3");
//and this goes on for a deck of cards
}
}

Not finding variable

I am having problems with my program compiling to find a variable. I have two classes for this program currently and my variable lotteryNumbers is in the first class. It is an int array variable though so I am not sure how to insert it in this line of code. This program is a lottery program to let people pick their tickets. Here is the lines of code where I get my first problem of not finding the variable
import java.util.Scanner;
import java.util.InputMismatchException;
public class CashBallTest
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int kicker;
System.out.println("\t\t\t\tCashLottoBall");
System.out.println("Player picks four numbers from 1 to 33 called LottoCash Balls. LottoCash Ball numbers must be unique from all other LottoCash Balls.");
System.out.println();
System.out.println("The player must also pick a CashBall from 1 to 31.");
System.out.println();
System.out.println("Kicker is a brand new feature you can purchase with your CashBall ticket which lets you get in on an extra drawing.");
System.out.println();
System.out.println();
for(int index=0; index<lotteryNumbers.length; index++)
{
It is from the for(int..... line at the bottom.
Edit*
Here is the first class which is called CashBall and has the variable in it
import java.util.Scanner;
public class CashBall
{
Scanner keyboard = new Scanner(System.in);
int[] lotteryNumbers = new int[4];
int[] kicker = new int[4];
int[] kickerPowerBall = new int[1];
int yourNumbers;
int CashBallPick;
public CashBall(int yourNumbers, int CashBallPick)
{
this.yourNumbers=yourNumbers;
this.CashBallPick=CashBallPick;
}
public int getYourNumbers()
{
return yourNumbers;
}
public int getCashBallPick()
{
return CashBallPick;
}
public void setYourNumbers(int yourNumbers)
{
this.yourNumbers=yourNumbers;
}
public void setCashBallPick(int CashBallPick)
{
this.CashBallPick=CashBallPick;
}
}
You have no variable called lotteryNumbers.
have you defined lotteryNumbers as a protected or public variable in the class in which it is defined
Also you need to include the class int which the variable lotteryNumbers is defined if they are not in the same package
Or you can define a function get_lottery_Numbers() in the class in which it is defined and then call that method in other class.
There is an example here that can help
http://www.roseindia.net/java/javascript-array/call-method-another-class.shtml
In your other class you need to declare a getter for the lotteryNumbers field and then use the getter method to get that field in CashBallTest.
Here is an example. Let's assume your other class is named SomeClazz. It should look like below:-
public final class SomeClazz {
private final int[] lotteryNumbers;
public SomeClazz(int[] lotteryNumbers){
this.lotteryNumbers=lotteryNumbers;
}
public int[] getLotteryNumbers() {
return lotteryNumbers;
}
}
Then in your CashBallTest class, you should have something like below to access lotteryNumbers:-
int[] lotteryNumbers = {1,2,3};
SomeClazz clazz = new SomeClazz(lotteryNumbers);
for(int index=0; index<clazz.getLotteryNumbers().length; index++){
}
Now you have a way to access lotteryNumbers from your other class and hence no longer the unknown symbol error should appear.
If by "lotteryNumbers is in the first class" you mean that there is a field lotteryNumbers in the class CashBallTest, then the way to access it depends on how it's declared. If it is a static variable, you can refer to it by CashBallTest.lotteryNumbers. If it is not static, then you need to create an instance of CashBallTest (let's call it test), and then refer to it by test.lotteryNumbers.
So in your CashBall class, you need:
import java.util.Scanner;
import java.util.InputMismatchException;
public class CashBall
{
// you should probably initialize this variable in your constructor
private int[] lotteryNumbers;
public int[] getLotteryNumbers() { return lotteryNumbers; }
}
This defines a private variable internal to the class called lotteryNumbers and then creates a public method that exposes it to the testing class. Then you need to create a CashBall object in your CashBallTest, and access its lottery numbers. Like:
public class CashBallTest
{
public static void main(String[]args)
{
CashBall test = new CashBall();
for(int index=0; index < test.getLotteryNumbers().length; index++) ;
}
}
We do this to encapsulate the variable such that later we can change the internal variable CashBall uses to store the lotteryNumbers without forcing other classes that use CashBall to change all their code.
For example, I could change:
private int[] lotteryNumbers;
to
import java.util.collections.ArrayList
private ArrayList<Integer> lotteryNumbers;
public int[] getLotteryNumbers() {
int[] returned;
return lotteryNumbers.toArray(returned);
}
Encapsulation is good coding practice, so be sure you get in the habit of encapsulating your privates.
For extra credit, you probably don't want to iterate across the length of the array in your test. This is bad because your test becomes dependent on CashBall having an int[]. If CashBall changes, your test has to change.
To "do it right", you should add methods inside of CashBall that handle "picking lottery numbers" (which I assume is what this first loop is trying to do), "validating lottery numbers", and "playing with kicker. Then your testing class would become like this:
import java.util.Scanner;
import java.util.InputMismatchException;
public class CashBallTest
{
CashBall toTest;
public static void main(String[]args)
{
toTest = new CashBall(); // add parameters here as necessary
toTest.collectUserLotteryNumbers(); // put the Scanner stuff in here. Make the menu its own void method that's called from here
if(toTest.validateUserNumbers() == false) {
throw new InputMismatchException("Numbers must be between 1-31, and cannot be repeated");
}
}
}
As you gain more experience coding, you'll find yourself writing them like this:
public class CashBallTest
{
CashBall toTest;
public static void testUserCollection()
{
toTest = new CashBall(); // add parameters here as necessary
toTest.collectUserLotteryNumbers(); // put the Scanner stuff in here. Make the menu its own void method that's called from here
if(toTest.validateUserNumbers() == false) {
throw new InputMismatchException("Numbers must be between 1-31, and cannot be repeated");
}
public static void main(String[]args)
{
testUserCollection();
}
}
}
This allows you to break up each thing you're testing into its own particular method, making it easy to add individual tests or modify them without breaking other stuff in your main method. Once you get in this practice, you'll be ready to learn about Unit Testing frameworks like JUnit.

Categories

Resources