Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I just started learning Java and I have a problem with defining a class.
I defined some variables in a class, but everywhere I wrote a command for printing a value of a string (or other variables) I got an error that says "cannot find symbol". Does that mean I can't use a print command in a class? Can you do a favor and simply explain me what to do?
Here is my codes (it's just for testing):
class Variable {
int m = 15;
boolean myb = true;
double mon = 2.4;
}
if you have
class Variable {
public int m = 15;
public boolean myb = true;
public double mon = 2.4;
}
iv'e added public modifier so fields are accessible
then your print code should be
public static void main(String[] args) {
Variable object=new Vairable(); //create instance of class
System.out.println(object.m);
System.out.println(object.myb);
System.out.println(object.mon);
}
You would need to print from a method within the class, not just in the class.
class Variable {
int m = 15;
boolean myb = true;
double mon = 2.4;
public void printVars() {
System.out.println("m: " + m);
System.out.println("myb: " + myb);
System.out.println("mon: " + mon);
}
}
After that, you would create a new Variable and call it's printVars() method.
Or, if this class is what you're trying to run, you could put your main in here.
class Variable {
static int m = 15;
static boolean myb = true;
static double mon = 2.4;
public static void main(String[] args) {
System.out.println("m: " + m);
System.out.println("myb: " + myb);
System.out.println("mon: " + mon);
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to java, trying to learn by making mini projects right now. I have two classes and when I run my program I have this error : Cannot make a static reference to the non-static field Game.balance.
Not quite sure why I am getting it and wondering if anyone knows any fixes.
import java.util.Random;
import java.util.Scanner;
public class Mainone {
public static void main(String[] args) {
System.out.println("You have $1000. I hope you make good choices!");
Scanner user = new Scanner(System.in);
Game print = new Game(1000,0,0,true);
System.out.print(Game.operation);
}
}
this is the second class below (new file)
import java.util.Random;
public class Game {
int balance = 1000;
int operationAmount;
int randOperation;
boolean ad = true;
public Game(int b, int o, int r, boolean a) {
balance = b;
operationAmount = o;
randOperation = r;
ad = a;
}
}
System.out.print(Game.operation);
change to
System.out.print(print.operation);
In java, you can't access Object field values by Class directly. But you can access the static field by using Class.
public class Game {
public static String ABC = "1"; // can access by Game.ABC
int balance = 1000;
int operationAmount;
int randOperation;
boolean ad = true;
public Game(int b, int o, int r, boolean a) {
balance = b;
operationAmount = o;
randOperation = r;
ad = a;
}
}
public static void main(String[] args) {
System.out.println("You have $1000. I hope you make good choices!");
Scanner user = new Scanner(System.in);
Game print = new Game(1000,0,0,true);
System.out.print(Game.ABC); // here you can access the static field
}
you are trying to call Game.operation. Instead of this try print.operation.
I assume operation is function in class Game.
Here the state is managed by the print object of Game class.
Please call System.out.print(print.operation);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I just accepted that all my programs I made have to start with this. Then I was looking at a example #2 here regarding generation of a random number.
import java.util.Random;
/** Generate random integers in a certain range. */
public final class RandomRange {
public static final void main(String... aArgs){
log("Generating random integers in the range 1..10.");
int START = 1;
int END = 10;
Random random = new Random();
for (int idx = 1; idx <= 10; ++idx){
showRandomInteger(START, END, random);
}
log("Done.");
}
private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
log("Generated : " + randomNumber);
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}
I noticed that this had a public static void and a private static void. Why not just combine the code into one thing under public static void? More importantly, what do these mean? I did research and saw the word "class" pop up often. What is a class? I hope my question meets the guidelines, this is my first time posting here. Thanks.
I will assume you asked here because you wanted a concise answer that gives you some intuition, rather than a deep dive into OOP which you can pull from the tutorial.
A class is a template from which objects are built. However, until you understand OOP, the class is just a necessary wrapper around the imperative code you are writing because Java requires all code to live inside a class.
public means the method is publicly accessible. Methods which are defined in classes other than this one can access it. private has the opposite meaning.
static means that this is a class-level function that is not tied to any particular instance of the class.
void means the method returns nothing.
You can certainly put all the code under a single method, but that carries at least the following problems.
Code is harder to read because the intent of the code is hidden by the details of the implementation.
Code is harder to reuse because you have to copy and paste whenever you need the same functionality in multiple places.
The following is not fully correct, it is very simplified:
Mostly one class equals one file. Even so they can access each other (if in the same project/folder) Here are 3 example classes:
Class withe the main method:
package ooexample;
public class OOExample {
public static void main(String[] args) {
int min = 2;
int max = 101;
// use of static method
int randomNumberA = MyMath.generateRandomNumber(min, max);
// use of non static method
RandomNumberGenerator generator = new RandomNumberGenerator();
int randomNumberB = generator.randomNumber(min, max);
/**
* does not work, method is private, can not be accessed from an outise class
* only RandomNumberGenerator can access it
*/
// generator.printSomeNumber(123);
}
}
Class with a static method. The method can be access by writing classname.nameOfStaticMethod(...) see main method.
package ooexample;
public class MyMath {
public static int generateRandomNumber(int min, int max) {
return min + (int) (Math.random() * ((max - min) + 1));
}
}
Class without static method. You have to create the class in the main method, using the new operator and assign the created class to a variable. Then you can use the variable to access PUBLIC methods of that class. You can not access private methods anywhere else but inside of the class itself. See main method.
package ooexample;
public class RandomNumberGenerator {
public RandomNumberGenerator() {
}
public int randomNumber(int min, int max) {
int randomNumber = min + (int) (Math.random() * ((max - min) + 1));
printSomeNumber(randomNumber);
return randomNumber;
}
private void printSomeNumber(int number) {
System.out.println(number);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Disclaimer: I'm a beginner so feel free to point stuff out...
I have a superclass composed by an array of int with 8 values, now i want to create a subclass to randomly pick 4 items in the array and store them in another Object.
Superclass:
public class SideDeck{
public static final int MaxValue = 6;
public static final int MinValue = -6;
public static final int MaxArrayValue = 8;
public final int[] sidecards = new int[MaxArrayValue];
public SideDeck(){
for(int i=0;i<MaxArrayValue;i++){
sidecards[i]=0;
}
}
public SideDeck(int sidecards1,int sidecards2,int sidecards3,int sidecards4,int sidecards5,int sidecards6, int sidecards7, int sidecards8){
sidecards[0]=sidecards1;
sidecards[1]=sidecards2;
sidecards[2]=sidecards3;
sidecards[3]=sidecards4;
sidecards[4]=sidecards5;
sidecards[5]=sidecards6;
sidecards[6]=sidecards7;
sidecards[7]=sidecards8;
}
public boolean ValidSidedeck(){
int check=0;
if (sidecards[0]!=0) {
for(int i=0;i<MaxArrayValue;i++){
if ((sidecards[i] > MinValue) && (sidecards[i] < MaxValue)){
check=1;
} else{
check=0;
break;
}
}
} else {
check=0;
}
if (check==1){
return true;
} else {
return false;
}
}
public String toString(){
String s="";
for(int i=0;i<MaxArrayValue;i++){
s+=(" || Card n° " + (i+1) + " = " + sidecards[i]);
}
return s;
}
public void ResetSidedeck(){
if (sidecards[0]!=0) {//why check it? what if we just run it?
for(int i=0;i<MaxArrayValue;i++){
sidecards[i]=0;
}
}
}
}
Subclass: (Not really sure what to do here… ) Basically it should pick 4 random positions from the .super and store them here, just that i have no clue how to create the object this way. And passing the super as constructor doesn't seem right since it's gonna pass the Object and not the array(and i don't need the full array anyway). Main thing is that i wanna keep the superclss like that, maybe just adding a method there so extract the 4 values..and passing them as arguments…?
import java.lang.Math;
public final class PlayableSideDeck extends SideDeck{
private final static int MaxCArrayValue=4;
public final int[] sidecardsPlay = new int[MaxCArrayValue];
public PlayableSideDeck(SideDeck sidecards){
/* sidecardsPlay[0]=0;
sidecardsPlay[1]=0;
sidecardsPlay[2]=0;
sidecardsPlay[3]=0;*/
// SetDeck();//<-Can i call a private method in the constructor
}
public void SetDeck(){
/* for(int j=0;j<4;j++){
int position=(super.sidecards[PickDeck()]);//<--this is the main problem.. since it's gonna call the object i guess.
sidecards[j]=position;
System.out.println(/*"i= " + i + *//* " ||| j= " + j + "|||| new sidecard= " + sidecards[j] + " |||| old sidecard=" + super.sidecards[PickDeck()]);
}*/
for(int j=0;j<MaxCArrayValue;j++){
sidecardsPlay[j]=(super.sidecards[PickDeck()]);
System.out.println(/*"i= " + i + */ " ||| j= " + j + "|||| new sidecard= " + sidecardsPlay[j] + " |||| old sidecard=" + super.sidecards[PickDeck()] + "|| random= " + PickDeck());
}
}
public int PickDeck(){
return ((int)(Math.random() * 8));
}
public String toString(){
String s="";
for(int i=0;i<MaxCArrayValue;i++){
s+=(" || Card n° " + (i+1) + " = " + sidecards[i]);
}
return s;
}
}
Thanks.
I'm not sure how you plan to use PlayableSideDeck, so I'll answer answer this two ways and you can pick the most fitting answer.
First, as the book Effective Java (by Josh Bloch) points out, you should favor composition over inheritance. By using composition you have your answer to the question of whether you should pass an instance of SideDeck to the constructor of PlayableSideDeck - you will have to since you won't be inheriting any access to SideDeck. Anyway, I'd recommend reading Item 16 in the book (google for it, there are copies available online) and see if composition doesn't better fit your needs.
Second, if you decide to go with inheritance, you don't need to pass an instance of SideDeck to the constructor of PlayableSideDeck. This is because when you create an instance of PlayableSideDeck you are automatically creating an instance of SideDeck along with it. All constructors in Java will implicitly call super() (which is the superclasses's default constructor) if you don't explicitly provide another such call yourself. For example, you could prevent the implicit call to super() like so:
public class BaseClass {
protected String strValue;
public BaseClass () {
strValue = "";
}
public BaseClass (String str) {
strValue = str;
}
}
public class SubClass extends BaseClass {
private int intValue;
SubClass (String str, int i) {
super (str);
intValue = i;
// note that since strValue is protected, SubClass can access directly
System.out.println ("strValue = " + strValue);
}
}
In this example, if you call new SubClass ("foobar") then you will see strValue = foobar printed on the console.
If BaseClass didn't have a zero argument constructor you would, in fact, be required to call super(str) since the compiler wouldn't be able to figure out how to do it for you.
Also, since you asked, here are a few other tips and pointers:
In the constructor SideDeck() you explicitly initialize all values of the array to 0, which isn't necessary. They will already all be 0. If you needed to init them to 0 then you'd be better off avoiding code duplication by calling ResetSideDeck. Speaking of which, you can shorten that code to Arrays.fill (sidecards, 0); (be sure to import java.util.Arrays).
Yes, you can call private methods from a constructor - but only private methods that are part of the local class, not any of the superclasses (you can, however, call protected methods of superclasses).
You're right about not checking sidecards[0] == 0 since there's little efficiency to be gained unless MaxArrayValue becomes very large.
Your class member variables such as sidecards should be private (or maybe protected if you need to access them from a subclass). Use getter/setter methods to access them.
Lastly, Java naming conventions would tell you to use a lower-case letter for method names (e.g. setDeck, pickDeck, resetDeck, etc.), and for even more idiomatic Java you could rename ValidaDeck to isValidDeck (since it returns a boolean). For the constants such as MaxArrayValue the convention is to use all upper-case with underscores between words, e.g. MAX_ARRAY_VALUE.
Hope this all helps!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am working on the following assignment: An attempt to moveOn or backUp or to evaluate seesCD when it is illegal causes an abrupt System.exit(0) without explanation. The user would appreciate a tracing output in such cases. Revise these three methods to call a private method that explains the problem (with showMessageDialog) and then terminates.
I wrote the following code (please scroll down the code):
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Vic extends Object
{
private static final String NONE = "0";
/////////////////////////////////
private String itsSequence = "";
private int itsPos = 1;
private final int itsID; // assigned by the constructor
private void trace (String action)
{
System.out.println ("Vic# " + itsID + ": " + action
+ itsPos + "; sequence= " + itsSequence);
} //======================
public void backUp()
{
if (itsPos == 1)
error("Could not backUp");
itsPos--;
trace ("backUp to slot ");
} //======================
public void moveOn()
{
if ( ! seesSlot())
error("Could not moveOn");
itsPos++;
trace ("moveOn to slot ");
} //======================
public boolean seesSlot()
{
return itsPos < itsSequence.length();
} //======================
public boolean seesCD()
{
if ( ! seesSlot())
error("Can't see CD, there is no slot");
String s = itsSequence.substring (itsPos, itsPos + 1);
return ! s.equals (NONE);
} //======================
private void error(String message)
{
JOptionPane.showMessageDialog(null, "ERROR: " + message);
System.exit(0);
}
}
When I compile I receive the following error message:
"variable itsID might not have been initialized".
and this line is highlighted."public class Vic extends Object"
The problem is that you have a final instance variable (which means that it has to be assigned a value exactly once during construction), but you don't have a constructor actually assigning it anywhere.
There's a comment that says assigned by the constructor on that field, but there's no explicit constructor. Perhaps you're supposed to write one, or it got removed at some point in the process of turning this code into an assignment.
itsId isn't set anywhere, that explains your error.
But in general, this type of problem is solved with try and catch blocks and thrown errors. I'm sure you are about to learn about those.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
class Demo2
{
int i=1,j=2;
void fun1()
{
i=i+1;
j=j+1;
}
public static void main(String[] args)
{
Demo2 d1=new Demo2();
d1.fun1();
d1.fun1();
d1.fun1();
System.out.println("Hello World!");
}
}
symbol cannot find and func cant be applied errors are showing Please help me i am a basic learner....
There are several errors in the code. I've commented and suggested some working code.
class Demo2
{
void fun1()
{
i=i+1; //i has not been initialized
j=j+1; //j has not been initialized
}
public static void main(String[] args)
{
Demo2 d1=new Demo2();
d1.fun1(1);//"fun1" does not accept a parameter.
d1.fun1();
d1.fun1();
System.out.println("Hello World!");
}
}
Here is a working Demo2 class that may help you along:
class Demo2
{
int i = 0;
int j = 0;
public void fun1(int param)
{
i=i+param;
j=j+param;
}
public static void main(String[] args)
{
Demo2 d = new Demo2();
d.fun1(1);//adds 1 to both i and j
d.fun1(2);//adds 2 to both i and j
System.out.println("i is equal to " + i);
System.out.println("j is equal to " + j);
}
}
You Does not declare i and j and doesnot defined a method fun1 with one argument
It's very important to understand why your code does not compile, or you will not be able to do anything else even if it gets fixed.
For starters, declare i and j by putting them right under your class declaration
class Demo2 {
int i = 0;
int j = 0;
Now look at where you defined void fun1(). You don't allow it to accept any parameters. So d1.fun1(); is allowed but d1.fun1(1); is not. You did not define a function named fun1 that accepts an int as a parameter. You would have to define it like so:
void fun1(int input) {
// Whatever you wanted this function to do
}