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);
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'm trying to pass a simple array into a constructor of a class and kept getting a "cannot convert double[] to int" error. I'm really lost as to why.
import java.util.*;
public class Demo {
public static void main(String[] args) {
double[] data = {1,2,3,4,5,6,7,8,9,10,11,12};
Rainfall[] rain = new Rainfall[data];
}
}
import java.util.*;
public class Rainfall {
private double[] monthlyRain;
public Rainfall(double [] array) {
monthlyRain = array;
}
}
My IDE kept showing a red squiggly line underneath the "data" in
Rainfall[] rain = new Rainfall[data];
in the main method.
Use this instead...you are invoking constructor wrongly... with Rainfall[] rain = new Rainfall[data];
public class Demo {
public static void main(String[] args) {
double[] data = {1,2,3,4,5,6,7,8,9,10,11,12};
// Rainfall[] rain = new Rainfall[data]; wrong...
Rainfall[] rain = new Rainfall[]{new Rainfall(data) }; // correct
}
}
The thing is... Rainfal[] only holds an array of Rainfall objects...not one..
So thats..the correct way...sorry for error...
This question already has answers here:
Java how to call method in another class
(3 answers)
Calling static method from another java class
(3 answers)
Closed 2 years ago.
I know this is a repeated question but I don't really understand how to call upon the functions or the utility of all the privates etc... So what I'm trying to do is "build a bear" where u pick the size and colour in a different class while the main class calls it, like this:
Size
import java.util.Scanner;
public class BABSize
{
public static String size()
{
Scanner input = new Scanner(System.in);
System.out.println("Would you like a small, medium or big bear?");
String size = input.nextLine();
input.close();
return size;
}
}
Colour
import java.util.Scanner;
public class BABColour
{
public static String Colour()
{
Scanner input = new Scanner(System.in);
System.out.println("What colour would u like your bear?");
String colour = input.nextLine();
input.close();
return colour;
}
}
Main
public class MainFunction
{
public static void main(String[] args)
{
BABColour c = new Colourr();
BABSize g = new Size();
System.out.println("Your " + g + "," + c + " bear will be ready in a moment:)");
}
}
Since you are making static functions, you dont need to create instance of those classes and directly call the static methods.
Not suggested but you can still have a call after creating instance of it and using that reference to call the method.
Try to observe what you are returning fron that function and have that reference in calling method.
For example: For asking which beer, you are returning String.
So, in main method have that reference of String.
String beer = BABSize.size();
Similarly for colour you are retuning String so have that in main method.
change it like this
public static void main(String[] args)
{
BABColour c = new BABColour();//here you create a variable of type Colour
BABSize g = new BABSize();
String color = c.Colour();//Here you call the method color
String size = g.Size();//Here you call the method to get the size
System.out.println("Your " + color + "," + size + " bear will be ready in a moment:)");
}
(Im open to any question you have obout this)
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 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);
}
}
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 9 years ago.
Improve this question
I am doing some mathematical operation on a data set. As per the requirement of the project, the mathematical formula/logic can be changed at any time. So I am thinking to keep these formals out from the Java code, may be in config file. Below is the sample config file-
formula.properties file-
formula_a=(a+b)/(7*c+b^2)
formula_b=(a^(1/2)-formula_a*13)
formula_c=spilt_time(formula_b,a,b)
Calculator.java (A dummy Java file, which may not be correct as Its for demo purpose only)
public class Calculator
{
private final static String FORMULA_A = "formula_a";
private final static String FORMULA_B = "formula_b";
private final static String FORMULA_C = "formula_c";
public static void main(String[] args)
{
long a = 1738342634L;
long b = 273562347895L;
long c = 89346755249L;
long ansFromFormulaA = applyFormulaFromConfig(FORMULA_A, new long[] { a, b, c });
long ansFromFormulaB = applyFormulaFromConfig(FORMULA_B, new long[] { a, b, c });
long ansFromFormulaC = applyFormulaFromConfig(FORMULA_C, new long[] { a, b });
}
// spilt_time is used in formula_c
public static long[] spilt_time(long[] params)
{
final long[] split = new long[2];
// Some logic here which is applied on params array and answer is pushed
// into split array
return split;
}
private static long applyFormulaFromConfig(String formulaName, long[] params)
{
long ans = 0L;
// Read formula from property file here and apply the params over it and
// return the answer
return ans;
}
}
Please help me to design a solution for this.
Ok here is one:
Define your functions in JavaScript in a separate js-file outside your application. Might look like this:
function myFunction1(x, y, z) {
return x * y + z;
}
Now you can evaluate these script via the Java ScriptEngine and call those functions by name, passing them your params.
Have a look: http://www.wondee.info/2013/10/30/the-scriptengine-bindings/
edit:
Propeterties file:
function1=x + y * z
function2=x * x
read the functions into formula variable... and...
You can put your functions in a String and put it inside a function body like that:
String formula = readFromProperties("function1");
String myFunctionScript = String.format("function myFunction(x, y, z) { return %s ;}", formula);