Not finding variable - java

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.

Related

What wrong with my beginner code?

I cant understand whats wrong with my code. In this code i getting errors like this when im trying to assign a value to a variable within a class. Also System.out.println doesnt work in this classes:
1.Identifier expected
2.Unexpected token
3.Unknown class "windows"
public static void main(String[] args) {
}
class building{
int apart_num;
apart_num = 3;
}
class apartments{
double area;
int lightbulb;
int windows;
windows = 4;
}
interface construct_building{
}
interface construct_apartments{
}
You are declaring an instance member on one line :
int apart_num;
and then assign a value to it :
apart_num = 3;
The problem is that this is done outside a method, those statement can't be separated, you can't assign a variable previously declare outside a block statement so.
Do it in a one line (declaration and assignation) :
class building{
int apart_num = 3;
}
or with a constructor
class building{
int apart_num;
public building(){
apart_num = 3;
}
}
or in a block statement
int windows;
{ //a block statement
windows = 4;
}
Then, if this code is not a class, you need to do it.
public MyClass{
public static void main(String[] args){ ... }
...
class Building { //inner class (will exist only inside of a MyClass instance
}
static class Apartment { // a nested class, exist whitout a MyClass instance
}
}
class Level { //A class that have nothing to do with MyClass and that can not be public.
}
Where MyClass is the name of the file (MyClass.java)

Syntax error when declaring array in 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
}

Return a Reference to a Class with Static Methods and Static Fields Without Instantiation

I want to create a wrapper class that calls static methods and member fields from a class that is provided by a library I am unable to view the code.
This is to avoid boilerplate setting code of the global member fields when I need to use a static method in a specific context.
I want to try to avoid creating wrapper methods for each static method.
My question:
Is it possible to return a class with static methods from a method to access just the static methods without instantiating it?
Code is below with comments in-line.
The code is used to demonstrate a change in a static value when the method getMath() is invoked.
I want to avoid the setting of the value before calling the static method.
StaticMath.setFirstNumber(1);
StaticMath.calc(1);
StaticMath.setFirstNumber(2);
StaticMath.calc(1);
I am using the Eclipse IDE and it comes up with Warnings, which I understand, but want to avoid.
I tried searching for something on this subject, so if anyone can provide a link I can close this.
public class Demo {
// Static Methods in a class library I don't have access to.
static class StaticMath {
private static int firstNum;
private StaticMath() {
}
public static int calc(int secondNum) {
return firstNum + secondNum;
}
public static void setFirstNumber(int firstNum) {
StaticMath.firstNum = firstNum;
}
}
// Concrete Class
static class MathBook {
private int firstNum;
public MathBook(int firstNum) {
this.firstNum = firstNum;
}
// Non-static method that gets the class with the static methods.
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
// I don't want to instantiate the class.
return new StaticMath();
}
}
public static void main(String... args) {
MathBook m1 = new MathBook(1);
MathBook m2 = new MathBook(2);
// I want to avoid the "static-access" warning.
// Answer is 2
System.out.println(String.valueOf(m1.getMath().calc(1)));
// Answer is 3
System.out.println(String.valueOf(m2.getMath().calc(1)));
}
}
I'd just wrap it to make for an atomic operation:
public static class MyMath{
public static synchronized int myCalc( int num1 , int num2 ){
StaticMath.setFirstNum(num1);
return StaticMath.calc(num2);
}
}
Drawback: You'll have to make sure, StaticMath is not used avoiding this "bridging" class.
Usage:
int result1 = MyMath.myCalc( 1, 1 );
int result1 = MyMath.myCalc( 2, 1 );
You shouldnt call a static method through an object reference. You should directly use class reference to call a static method like this:
StaticMath.calc(1)
But if you still need it for some reason, you can return null in getMath method, but you will still get warning in Eclipse:
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
return null;
}
I infer that question is not properly asked if the answer is not
StaticMath.calc(1)
Other issue you may be facing due to package visibility to static inner classes. Which is a design choice by the writer of Demo class. If you can mark your classes MathBook and StaticMath public then you can access them like below:
Demo.StaticMath.calc(1);

How to call a function with array parameters in main application?

I've been doing some tutorial on inheritance abstract class, and I pass an array to a function for a calculation of total price. But then, when I tried to call the function in the main, it didn't work and I've got some error according the method call.
Here is my calculation code in subclasses :
public double calcPrice(String[] a, int[] qty, int num){
int i =0;
for(i=0;i<=num;i++) {
if (a[i]=="a")
price=24.90;
}
double tot=price+qty[i];
return tot;
}
This is my method call in the for loop. I don't know how to call the method as the error says "non-static method calcPrice() cannot be referenced from a static context"
for(int i=0;i<=num;i++) {
System.out.println("\t"+a[i]+"\t\t\t"+qty[i]+" "+calcPrice());
}
The main method is static, and can't call non-static code. You have 2 solutions.
Create an instance of the class performing the calculation, and call calcPrice on that instance.
make calcPrice static.
I suggest option one as you've been doing research on classes. This would be good practice for you.
Also do not compare variable a to "a" with ==. Use .equals instead. Check this link for why.
Edit:
I'm not sure how an abstract class plays into this as you have no abstract methods needing implementation.
public class CalcClass{
public double calcPrice(String[] a, int[] qty, int num){
int i =0;
for(i=0;i<=num;i++) {
if ("a".equals(a[i]))
price=24.90;
}
double tot=price+qty[i];
return tot;
}
}
public class MainClass{
public static void main(String[] args){
//create instance of calc class
CalcClass c = new CalcClass();
//call calc price method on calcclass
c.calcPrice(a, new int[]{1}, 1};
}
}
Changed to-
public static double calcPrice(String[] a, int[] qty, int num){
...
}
You should create an object before you do a call from main. Say you have a class-
public class Test {
public void someMethod(){
}
public static void main(String... args){
// Create an object first
Test t = new Test();
// Now you can use that non-static method someMethod
t.someMethod();
}
}
For static method, they exist on load.
You will need to create instance in order to call you method since your method is not static.
making you methos static will enable you to use it without creating instance of the class.
you may want to read about Static Methods here

Get the number of instantiated objects in Java [duplicate]

This question already has answers here:
Is this a valid way to count instances of objects?
(2 answers)
Closed 9 years ago.
class Clasa {...}
class Test {
public static void main(String[] args){
Clasa x = new Clasa();
System.out.println(x.getNo());//displays 1
Clasa[] y = new Clasa[10];
for(int i = 0; i<4; i++)
y[i]=new Clasa();
System.out.println(y[0].getNo()); //displays 5
}
}
How can I replace those three dots, so GetNo() method call to return the number of instantiated objects of class Clasa. Test class should not be changed.
Add a static variable which acts as a counter and increment it inside the constructor and getNo returns the value of the static variable.
Static variable have their values kept across all instances of a class
class Clasa {
private static int nbInstances = 0;
public Clasa () {
nbInstances++;
}
public int getNo() {
return nbInstances;
}
}
I agree with Brian , on that the above code is not considering the GC. So I would like to replace your code with the below code snippet
package com.instance.main;
import com.instance.target.Clasa;
public class Test{
public static void main(String[] args) {
Clasa targetClass;
Object[] object=new Object[10];
for(int i=0;i<object.length;i++){
object[i]=new Clasa();
}
System.out.println("Number of Instantiate Object {Before Calling GC}: "+Clasa .getNumberOfInstatiateObj());
/* Here I am trying to deallocate the memory of Object at index no 9, so that GC called this unused object to deallocate it from memory*/
for(int i=0;i<object.length;i++){
if(i==8){
object[i]=object[i+1];
object[i+1]=null;
System.runFinalization();
System.gc();
}
}
}
}
just put the above code beneath the main method and also you have to modify your Clasa code from the below code
package com.instance.target;
class Clasa {
private static int nbInstances = 0;
public Clasa () {
nbInstances++;
}
public int getNo() {
return nbInstances;
}
public void finalize(){
nbInstances --;
System.out.println("Number of Instantiate Object {After Calling GC}: "+nbInstances );
}
}
After modifying your code by following the above steps , your code will give you your desired output.
Please let me correct if I am wrong some where.
Hi Dany I modified my code , so according to the above code ,you have to create your class under different package which written in the class code . And let me know if you are getting problem still.

Categories

Resources