I am facing a roadblock with static methods.
How do I call this method ?
How do Pass the array to another class , so I can edit the array.
Thank you
import java.util.Scanner;
class getArray {
public static void change(String x[]){
Scanner keyboard = new Scanner(System.in);
String dayName[] = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
String[] day = new String[7];
for(int i=0;i<7;i++){
System.out.print(dayName[i]+ " ");
day[i] = keyboard.nextLine();
String str = (dayName[i]+" "+day[i]);
x[i] = str;
}
System.out.println(" ");
for(int j=0;j<7;j++){
System.out.println(x[j]);
}
}
}
class toParse{//would parse the integer out from String[x]
}
class averageTemp{//calculate average of weather
}
public class UniSeven2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
As pointed out in the comment, try not using static method. That said:
import java.util.Scanner;
class getArray {
public String change(String x[]){
Scanner keyboard = new Scanner(System.in);
String dayName[] = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
String[] day = new String[7];
String str;
for(int i=0;i<7;i++){
System.out.print(dayName[i]+ " ");
day[i] = keyboard.nextLine();
str = (dayName[i]+" "+day[i]);
x[i] = str;
}
return str;
}
}
You can now access the "modified" String from whatever class you want.
Static methods belong to the Class itself, rather than the instances created by the class. Hence, when calling static method from outside it's class you would call it at the class level.
So, say we have the following..
MyClass {
public static void myStaticMethod(int[] myIntArray) {
//Do something
}
public void myNonStaticMehtod(int[] myIntArray) {
//Do something
}
}
When calling these methods from another class they would be called in the following ways..
Non static method
Because the non static method belongs to a given instance of a class, we must first make an instance of the class and call the method from the instance.
int[] myIntArray = new int[4];
MyClass myClass = new MyClass();
myClass.myNonStaticMethod(myIntArray);
Static method
The Static method belongs to the Class itself and should be called from the class level rather than from an instance of the class.
int[] myIntArray = new int[4];
MyClass.myStaticMethod(myIntArray);
On an unrelated note, the classes you are creating seem that they should be methods instead. Thinking in terms of object oriented programming, a class is the framework for an object, such as a car or person. The methods of that class should represent some action that these objects can perform. for example car.speedUp() speeds up a car, or car.getSpeed(), which gets the current speed of the car.
Hope this was helpful!
Edit: Added arrays as method parameters to help answer your second question.
Related
I try to assign an array of numbers from 1 to 10 using the code below. Basically I am stuck on how to return an array. Do I need a toString method ?
package arrays1;
import java.util.Arrays;
public class Arrays1 {
/**
* #param args the command line arguments
*/
private int[] numbers;
private int DEFAULT_SIZE = 10;
public Arrays1(int size){
numbers = new int[DEFAULT_SIZE];
}
public int[] add(int[] n)
{
for(int i=0; i<numbers.length; i++){
numbers[i]=n[i];}
return numbers;
}
public int[] getValues(){
return numbers;
}
public static void main(String[] args) {
// TODO code application logic here
Arrays1 A = new Arrays1(9);
System.out.println(A.getValues());
}
}
How do I return contents of an array from this code? Do I need to create a new object?
A.getValues() is returning a pointer to the integer array numbers object, which is probably the output you're seeing. You don't need a new object, just use the one you made, Arrays1 A, and iterate over its contents, so something like this:
public static void main(String[] args) {
// TODO code application logic here
Arrays1 A = new Arrays1(9);
for (int i = 0; i < A.getValues().length; i++){
System.out.println(A.numbers[i]);
}
}
Yes, a toString method would be useful to serialize the contents of the numbers array to a String. But in this case, you should call it like this:
Arrays1 a = new Arrays1(9);
System.out.println(a); // it is an implicit call to toString()
Another acceptable alternative is to let the serialization to the client's responsibility. In this case, the client should rely on the getValues() method, and serialize it by itself:
Arrays1 a = new Arrays1(9);
System.out.println(Arrays.toString(a.getValues()));
Another lesser detail: Review your constructor: It does not use the parameter size, and that can be confusing.
I'm trying to create a program that reads user input and stores it and then calculates the area of a polygon. When I try and compile it it gives me one error which is the one about .toString being non static.
import java.util.Scanner;
class regularpoTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean finished = false;
double s;
double n;
double area;
//starts loop to record data
do {
s =0;
n =0;
System.out.println("Enter the side length, or anything else to quit: ");
s = in.nextDouble();
in.nextLine();
if (in.hasNextDouble()) {
System.out.println("Enter number of sides");
n = in.nextDouble();
area = (s*s*n)/(4*Math.tan(Math.PI/n));
} else {
finished = true;
}
} while(!finished);
//This prints out the student details
System.out.println(regularpo.toString());
}
}
public class regularpo {
private double side;
private double numberOf;
private double area;
public regularpo(double side, double numberOf){
side = 0;
numberOf = 0;
area = 0;
}
public double getSide(){
return side;
}
public double getNumberOf(){
return numberOf;
}
public String toString(){
return ("area = " + area+ " side length "+side+ " number of sides "+numberOf);
}
}
You are trying to call a method of a class, when that method has been defined for (and only makes sense as) a method of an instance of that class. Maybe you mean to make an object of that class, and call its toString method, although I can't be sure from your code.
You can not access non-static methods by using classname.nonStaticMethodName. You need to instantiate your object using the new keyword. Basically, you create an instance of your object by regularpo r = new regularpo(2.0, 2.0). After that you can invoke r.toString();
Check out this SO-question for more info.
And this Oracle-tutorial explains class members well.
Suggestions:
1) Eliminate "regularpoTest". Just move "main()" into "regularpo".
2) Capitalize "RegularPo" (by convention, class names should start with a capital letter).
3) Make the RegularPo constructor actually save the initial values (not just set them to zero).
... and, most important ...
4) Your main should call RegularPo regularPo = new RegularPo (...).
Then reference object instance "regularPo".
Try to make a object of class regularpo and call toString over that object
regularpo obj=new regularpo();
obj.toString();
Also as per conventions a class name must start with Upper case,so name your class asRegularpo
toString() is a non static method in regularpro class , and we know that the non static belongs to an object so we need to create and object of same class and call it.
toString() is belongs to Object class so its non static method.
regularpo obj=new regularpo();
obj.toString();
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 6 years ago.
public class Test{
int Trails;
int Days
public static void main (String []args){
if(args.length!=0){
numT = Integer.parseInt(args[0]);
numD = Integer.parseInt(args[1]);
}
Trails=numT;
Days=numD;
}
}
I am trying to get input from the command line and then store them into globals but because they are being done in the main, it wants me to make everything static. Is there another way I should be doing this so that I can then do things with the data?
The main(String[] args) method gets invoked by the JVM "statically" and no actual object gets created. But there isn't any reason against creating an object of the enclosing class as such:
public class Test{
int Trails;
int Days
public static void main (String[] args){
//Create object of type Test
Test t = new Test();
if(args.length!=0){
t.Trails = Integer.parseInt(args[0]);
t.Days = Integer.parseInt(args[1]);
}
}
}
Of course, you can also pass the parameters through a constructor as such:
public class Test{
int Trails;
int Days
public Test(int numT, int numD){
Trails = numT;
Days = numD;
}
public static void main (String[] args){
int numT;
int numD;
if(args.length!=0){
numT = Integer.parseInt(args[0]);
numD = Integer.parseInt(args[1]);
//Create object here
Test t = new Test(numT, numD);
}
}
}
public class Test{
int Trails;
int Days
public static void main (String []args){
if(args.length!=0){
Test test = new Test();
test.Trails= Integer.parseInt(args[0]);
test.Days= Integer.parseInt(args[1]);
}
}
You need an object to work with instance variables
You need to pass them to an object instance that has a constructor or a method that accepts those command line args, then sets its instance variables (say, trails and days) in the constructor or method. The only way to have instance variables is to have an instance of an object. Also, note that you shouldn't capitalize variable names. The convention is to use camelCase with the first letter being lowercase. Class names start with a capital letter.
You're confusing the object notion with the static method concept:
you can have many instances of objects like Test (test2, test2, etc...) each instance will have its own life: in real life the analogy is having many cars (instances) of the class (toyota corolla) for example: all cars are made as described by the model sepecification (the class)
Then you have static methods which are methods that do not use a concrete instance: for example: security ckecks can be a static method: many cars come through a unique security check (that is not a function you can launch from within your car: it's not depending on the instance)
You can use this sample to understand better
public class Test{
int trails;
int days;
public String toString() {
return "trails :"+ trails +", days : "+ days;
}
}
public class Launcher{
public static void main (String []args){
if(args.length!=0){
Test test = new Test();
test.trails= Integer.parseInt(args[0]);
test.days= Integer.parseInt(args[1]);
Test test2 = new Test();
test2.trails= 5;
test2.days= 2;
Command cmd = new Command();
cmd.doSomething(test);
cmd.doSomething(test2);
cmd.doSomething(test);
}
}
}
public class Command {
Test lastTested;
public void doSomething(Test data) {
lastTested = data;
System.out.println( "working with "+ lastTested );
}
}
In the example above, you create an instance of Test that you fill with data.
Then you create an instance of Command, that will save in its state the last executed Test instance, then print the test instance data through its toString() method.
You can create a second instance of Test with other data and pass it to the same cmd (Command instance's method doSomething()). You will then see that the instance that is inside cmd changed, but getting back to your first instance test kept the values as expected
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 9 years ago.
I've read the Oracle documents regarding scope and controlling access yet it just isn't sticking, so I'm assuming that my issue comes from my failure to understand... Anyways Here's my code. I'm trying to access the unique Player objects created in an array, and change their unique variables like their balances, using methods from the Player class. Any solutions and ESPECIALLY explanations are welcome!
public class Player
{
private int currentBal;
private String myName;
private int rollOne;
private int rollTwo;
private int rollTotal;
private int doublesCount;
private int currentPosition;
private int currentDoubles;
private int move;
private int moveMult;
private int newBal;
private boolean rollAgain;
private boolean inJail;
public Player(String userName, int changeInMoney)
{
myName = userName;
currentBal -= changeBalance(changeInMoney);
}
public int changeBalance(int changeInMoney){newBal -= changeInMoney; return newBal;}
public int viewBalance(){return currentBal;}
Here is my PlayerArray class.
public class PlayerArray
{
Scanner scan = new Scanner(System.in);
private int numbHuman;
private Player[] arr;
private String[] userName;
private int startingMoney;
public PlayerArray()
{
Scanner scan = new Scanner(System.in);
System.out.println("There will be 4 players, how many do you wish to be human? 0><4");
numbHuman = scan.nextInt();
while (numbHuman < 1 || numbHuman > 4)
{
System.out.println("Invalid entry, try again.");
numbHuman = scan.nextInt();
}
arr = new Player[numbHuman];
userName = new String[numbHuman];
startingMoney = 1500;
for(int i = 0; i < arr.length; i++)
{
System.out.println("Player " + (i + 1) + ", Please enter your first name:");
userName[i] = scan.next();
arr[i] = new Player(userName[i],startingMoney);
}
}
public Player[] getPlayerArray()
{
int charge = 500;
arr[0].changeBalance(charge);
System.out.println(arr[0].viewBalance()); //look here as example
return arr;
}
}
this is my player class, minus some methods I can't use till later. Bellow is my main method to call it,
import java.util.Scanner;
import java.util.Random;
public class Launcher
{
private Planet myTest;
private PlanetInfo myPlanetInfo;
private static Player[] arr;
public static void main(String[] args)
{
Launcher testLauncher = new Launcher();
PlayerArray myArray = new PlayerArray();
Pay myCharge = new Pay(); // continue work on charges
myArray.getPlayerArray();
//STILL TRYING TO GET BELLOW LINE TO WORK LAST NIGHT!!!
int testBal = arr[0].viewBalance(); //ERROR HERE
System.out.println("player 1's balance: " + testBal);
}
}
Error "Java.lang.NullPointerException: null"
Your main method is a static method. It actually exists before any object is created from your class, and thus cannot access instance variables and methods directly. You cannot access non static methods or variables from the same class unless you create an object for the class, i.e Launcher launcher = new Launcher();.
In this case, your player array arr is not static. You either need to make this static or create a Launcher object and access the variable from there. In the latter case, you will need to make the arr array public.
The first option requires you to change your player array declaration to private static Player arr;.
The second requires you to change the access of the arr array to public and access it like so: launcher.arr.
Regarding your second error, you need to either do this: arr = myArray.getPlayerArray();
or just access the array directly like this: myArray.getPlayerArray()[0] (for the first item in that array).
Variable 'Player[] arr' is instance variable, i.e. it should belongs to particular instance. Static method 'main' can't directly access an instance variable from the class it's in, because it doesn't have an explicit reference to any particular instance of the class (simply said at this point, you don't have an instance to whom your Player[] arr belongs).
Make your variables static, since main is a static method, you can't reference non-static methods.
so make your variables on top something like:
private static Player[] arr;
Since your Launcher has no instance none of its non static members exist. Static method main cannot access such - in this case your arr does not exist. You may want to make it static to make it work.
Read static and instance members
I have 2 classes right now, the first class has the arraylist in it. But on the second class when I try to access the arraylist it keeps giving me the red line underneath saying that the variable doesn't exist.
Here is class one...
public class BankMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
BankMain main = new BankMain();
menu();
}
public static void cardNumbers(){
ArrayList<Integer> cardNum = new ArrayList<Integer>();
Scanner cards = new Scanner(System.in);
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
System.out.println("Please select a 5 digit card number");
cardNum.add(input.nextInt());
System.out.println("Thank you! You're card number is " +cardNum);
System.out.println("Type 'c' to go back to main menu.");
String value = keyboard.next();
if(value.equalsIgnoreCase("c")){
menu();
}
else if (!keyboard.equals('c')){
System.out.println("Invalid Entry!");
}
}
public static void menu(){
System.out.println("What Would you like to do today?");
System.out.println();
System.out.println("Create Account = 1");
System.out.println("Login = 2");
System.out.println("Exit = 3");
query();
}
public static void query(){
Scanner keyboard = new Scanner(System.in);
double input = keyboard.nextInt();
if (input == 2){
BankMainPart2 main2 = new BankMainPart2();
System.out.println("Please enter your 5 digit card number.");
main2.loginCard();
}
else if (input == 1){
cardNumbers();
}
else if (input == 3){
System.out.println("Thank you, have a nice day!");
System.exit(0);
}
}
}
Here is the second class...
public class BankMainPart2 {
public static void loginCard(){
if (cardNum.contains(name)) {
}
}
}
I know I haven't entered anything in the if statement yet on the second class but I'm just trying to get my array list to work on both classes.
The code looks very naive. A very simple answer to your question is
You have not declared any cardNum in BankMainPart2 as global variable or in loginCard as local variable, how do you think it will be available in the loginCard method?
ArrayList<Integer> cardNum = new ArrayList<Integer>();
is local to cardNumbers method.
How can you access it from other class?
A local variable cannot be accessed from outside the method, so first thing, make cardNum class level variable
Make the variable public if you want other classes to be able to access it directly, else make the variable private and create getter method (setter if required).
You can also send the variable when calling the method as argument
If this is class level variable, make it static and use Classname.variable.
--Edit--
As you have asked for details let me give you a quick overview of the different approaches.
A variable declared inside a method is local. as name suggest "local", no one but the method knows there is such a variable. No other method in the class knows about existence of this variable, let alone some outside class.
I say you can make it static, but static should strictly be used for class level storage, not object level. Say a list which is modified by multiple objects of the same class (I hope you know concepts of objects, else go to the basics otherwise it will not be clear). Now as per your example, I guess this is not what you want.
A public variable is generally no - no, only in few cases it will be useful (for example in android programming where performance is utmost important). Normally we will create a variable and provide getter setters. A getter or setter is used normally when we want to give access to the variable, which again does not look like what you want.
Last, the variable is private to you class, but if you want some method to do something about it, you can pass it as argument, this looks the case for you.
Step by step
take the variable out of method and add to class level, note that I removed static from method names
public class BankMain {
private ArrayList<Integer> cardNum = new ArrayList<Integer>();
// rest of code as it is
..
..
BankMain main = new BankMain();
//change
main.menu();
//no need foe static
public void cardNumbers(){
//no need here now
//ArrayList<Integer> cardNum = new ArrayList<Integer>();
Scanner cards = new Scanner(System.in);
Scanner input = new Scanner(System.in);
..
..
//public static void menu(){
public void menu(){
//send the list
//I see there are confusion at times regarding calling of static method.
//please note objectname.staticMethod() or classname.staticMethod() is one
//and same thing. Just that classname.staticMethod() is more clear
BankMainPart2.loginCard(cardNum);
}
and
public class BankMainPart2 {
public static void loginCard(ArrayList<Integer> cardNum){
if (cardNum.contains(name)) {
}
}
}
Your method, BankMainPart2.loginCard has not context of "cardNum", it doesn't know what it is (type or value).
In order for the method to be able to act on the array list, you must pass a reference to it, something like...
public class BankMainPart2 {
public static void loginCard(ArrayList<Integer> cardNum){
if (cardNum.contains(name)) {
}
}
}
make the cardnum arraylist as an instance variable in BankMain class and extend BankMain in BankMainClass2 and using reference of BankMain you would be able to access cardNum like this
Class BankMain {
public ArrayList<String> cardNum = new ArrayList<String>();
}
Class BankMain2 extends BankMain {
public void method() {
BankMain2 main = new BankMain2();
sysout(main.cardNum.size());
}
}
but the above scenario would only work when cardNum ArrayList in BankMain class is either marked public,protected or default(Nomodifier). it wouldnt work if its marked as private and other non access modifier such as static and final
You can try any one of these
1.Declare the Arraylist as public then import the first class and use the cardNum in the second class
2.Make the cardNum a static var and use it directly in second class as BankMain.cardNum
3.Pass the Arraylist as argument to the second class.
The key problem is in the the way you are trying to create your classes. Your current problem can be solved by answer given by #MadProgrammer. But you should definitly have a look into the Object Oriented Programming Concepts. This section on How to identify and design a Class? should give you some clear pointers.