How to move values from a private class to another? - java

i'm a novice in java and i don't know how to call a variable from a private class to another.
Currently i'm using NetBeans 8.1 and here's the class from which i wanna take the values
public class Mars {
public static String name;
private static int fuel;
private static int AI;
private static int tecnology;
public void setName(String nm)
{
name = nm;
}
public void setFuel(int fl)
{
fuel = fl;
}
public void setAI(int ai)
{
AI = ai;
}
public void setTecnology(int tc)
{
tecnology = tc;
}
public String getName()
{
return name;
}
public int getFuel()
{
return fuel;
}
public int getAI()
{
return AI;
}
public int getTecnology()
{
return tecnology;
}
private static class name {
public name(){
name = "unknown";
}
}
private static class fuel{
public fuel() {
fuel = 50;
if ((fuel >100) || (fuel <0))
{System.out.println("\nError!");
System.exit(0);}}}
private static class AI {
public AI() {
AI = 5;
if ((AI >10) || (AI <1))
{System.out.println("\nError!");
System.exit(0);}}}
private static class tecnologiy {
public tecnologiy() {
tecnology = 5;
if ((tecnology >10) || (tecnology <1))
{System.out.println("\nError");
System.exit(0);}}}
}
And here is the class where i want to put the values:
public class Space_Battle {
public static void main(String[] args) {
Mars Call1 = new Mars();
System.out.println("\nThe alien named " + Mars.name + " joined the battle" );
}
}
Naturally every correction will be very appreciate! :-D
P.S. I'm sorry if this question is ridicoulos.

Change your code to this...
public class Space_Battle {
public static void main(String[] args) {
Mars mars = new Mars();
System.out.println("\nThe alien named " + mars.getName() + " joined the battle");
}
When you create an instance of an object, you should access it via secure accessors i.e. getter methods, getName(), etc.
And remove the static declaration from your private variables.

You cant directly set values to private variables from another class, thats why they are private.
You HAVE to instantiate an object of the said class.
Example:
Mars call1= new Mars();
then you can set values to that object.
call1.setName("whatever");
then to get the value of the object just use the getter.
call1.getName();
then to print it:
System.out.println("\nThe alien named " + call1.getName() + " joined the battle" );
Also, remove the static from your variables.
I would also encourage you to read about the "this" keyword.
I recommend you to read this documentation:
https://docs.oracle.com/javase/tutorial/java/concepts/object.html

Related

Why can't I call a sub-function?

I can't get this Java code to work. I have read multiple examples, but none explains why the code doesn't work.
The code:
class Main {
public static void main(String[] args) {
class UserInfo {
public String Name = "Example Name";
public int Age = 13;
static int GetAge() {
return (Age);
}
}
UserInfo.GetAge();
}
}
Please note I am very new to Java.
You cannot call non-static method from static context without creating new UserInfo object. You need to create new UserInfo object
class Main {
public static void main(String[] args) {
class UserInfo {
public String Name = "Example Name";
public int Age = 13;
int GetAge() {
return (Age);
}
}
UserInfo userInfo = new UserInfo();
userInfo.GetAge();
}
}
You cannot call a non-static method from a static context. I have moved the class outside of the method and made it static.
Try the code below:
class Main {
public static void main(String[] args) {
System.out.println(UserInfo.GetAge());
}
static class UserInfo {
public String Name = "Example Name";
static int Age = 13;
static int GetAge() {
return (Age);
}
}
}
However, if you want a dynamic class in where you can define the name and age, use this code below:
class Main {
public static void main(String[] args) {
UserInfo userInfo = new UserInfo("John", 13);
System.out.println(String.format("Name: %s Age: %s", userInfo.getName(), userInfo.getAge()));
}
static class UserInfo {
String name;
int age;
UserInfo(String name, int age){
this.name = name;
this.age = age;
}
int getAge() {
return age;
}
String getName() {
return name;
}
}
}
Error 1:
age is an instance variable. You can not use it inside the static method GetAge(), so either make Age static or make a getAge instance...
static int GetAge() {
return (Age);
}
Error 2: you can not access an instance variable GetAge() using a class name reference. To correct it, you have to create an object and use this reference to access it.
UserInfo.GetAge(); // Does not compile
Instead use:
UserInfo userInfo = new UserInfo();
userInfo.GetAge();
Generally, instance variables can not be used inside static methods and you can not use class reference to access an instance member in Java.
First of all, you cannot call a non-static method from a static context. You should need to move the inner class outside from the main method and make it static.
Try this one:
public class Main {
public static void main(String[] args) {
System.out.println(UserInfo.GetAge());
}
static class UserInfo {
public String Name = "Example Name";
public static int Age = 13;
static int GetAge() {
return (Age);
}
}
}

Can't get variable from GUI into main class

I am trying to use a getter to retrieve some variables that the user will input into a GUI, however it gives me an "non-static method cannot be referenced from a static context" error. I have tried making my getters and setters static and that did not work. I am not sure where to go from there. Here is my code:
Main:
public class creditInfoSystem {
String name = infoGUI.getName();
public static void main(String[] args) {
new infoGUI();
}
public void getData() {
}
}
Getters+Setters From GUI Class:
public void setName(String newName){
name = newName;
}
public String getName(){
return name;
}
public void setCustNum(double newCustNum){
custNum = newCustNum;
}
public double getCustNum(){
return custNum;
}
public void setCreditLimit(double newCreditLimit){
creditLimit = newCreditLimit;
}
public double getCreditLimit(){
return creditLimit;
}
public void setPrevBalance(double newPrevBalance){
prevBalance = newPrevBalance;
}
public double getPrevBalance(){
return prevBalance;
}
public void setCurrentPurchases(double newCurrentPurchases){
currentPurchases = newCurrentPurchases;
}
public double getCurrentPurchases(){
return currentPurchases;
}
public void setPayments(double newPayments){
payments = newPayments;
}
public double getPayments(){
return payments;
}
public void setCreditsReturns(double newCreditsReturns){
creditsReturns = newCreditsReturns;
}
public double getCreditsReturns(){
return creditsReturns;
}
public void setLateFees(double newLateFees){
lateFees = newLateFees;
}
public double getLateFees(){
return lateFees;
}
I can provide more parts of the code if needed.
The problem is that the creditInfoSystem class has no idea which infoGUI class you are referring to. Try and make infoGUI a parameter of creditInfoSystem and retrieve the data from there.
public class creditInfoSystem {
private InfoGUI infoGUI;
public creditInfoSystem(InfoGUI gui){
infoGUI = gui;
name = infoGUI.getName();
}
public static void main(String[] args) {
InfoGUI infoGUI = new infoGUI();
CreditInfoSystem sys = new creditInfoSystem(infoGUI);
}
}
If you are building a swing/FX GUI:
One problem I can predict is knowing when the name in the GUI is actually set. You should maybe consider making the GUI the main program where CreditInfoSystem is an attribute of the GUI. Then when a button is clicked or some other action, the input from the GUI is taken and passed to the CreditInfoSystem.
First of all, rename your classs InfoGUI and CreditInfoSystem, starting with an upper case, it is a Java convention.
Then, when you do InfoGUI.getName() you are trying to access a class method, which would have to be static. What you want to do is create an instance of InfoGUI and access it's instance method.
Also your name variable should be static because you use it in a static method, ie public static void main
public class CreditInfoSystem {
private static String name;
public static void main(String[] args) {
// Create an instance of your InfoGUI class
InfoGUI infoGuiInstance = new InfoGUI();
// Call the getter on the instance you just created
name = infoGuiInstance.getName();
}
}
And the renamed InfoGUI class:
class InfoGUI {
String name;
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
}

enum not getting called in constructor

I'm trying to build some Dota2-like classes, with simple details. I got stuck at one point where I need my hero's attribute in Main, but the constructor for it doesn't work. Here is the code for Hero class:
enum attribute {
Strength, Intelligence, Agility
};
public class Hero extends Unit {
private int level;
private static int str;
private static int intl;
private static int agi;
private static attribute heroAttribute;
public attribute getAttribute() {
return heroAttribute;
}
private static int attributeDamage() {
if (heroAttribute == attribute.Strength)
return str;
else if (heroAttribute == attribute.Intelligence)
return intl;
else
return agi;
}
public Hero(int level, int str, int intl, int agi, attribute heroAttribute) {
super(200 + 20 * str, attributeDamage());
System.out.println("A hero has been spawned.");
}
}
and the Main:
public class Main {
public static void main(String[] args) {
Hero h1= new Hero(25,400,30,30,attribute.Agility);
System.out.println(h1.getAttribute());
}
}
What I get is that I have null "attribute" value.
Try put this attributes without the static, and initiate these attributes...
private int str;
private int intl;
private int agi;
private attribute heroAttribute;
public Hero(int level, int str, int intl, int agi, attribute heroAttribute) {
this.str = str;
this.intl = intl;
this.ai = agi;
this.heroAttribute = heroAttribute;
super(200 + 20 * str, attributeDamage());
System.out.println("A hero has been spawned.");
}
i suggest you to create new enum class that containt those 3 attribute and then, implement them.
by the way, all enum entities should be upper case like: STRENGTH, AGILITY, INTELLIGENT
public enum HeroAttribute {
STRENGTH("str"),
AGILITY("agi"),
INTELLIGENT("intl");
private String literal;
HeroAttribute(String literal) {
this.literal = literal;
}
public String getLiteral() {
return literal;
}
}

Defining class field and calling parent's constructor

These are two classes of code that I wrote.. the problem here is I am not sure how to define class fields to represent Grass, fire and water as a Type using static..
Also I am not sure if I had used the super function the right way.. How do I properly call the parent's constructor so that I dont have to re define "knockedOut boolean" and be able to use Fire as the type?
Question could be confusing but I am not sure how to explain it better :( sorry
public abstract class Pokemon {
private String name;
private String type;
private int attack;
private int health;
private boolean knockedOut;
static private String Grass;
static private String Water;
static private String Fire;
public Pokemon (String n, String t, int a, int h) {
name = n;//state
type = t;//state
attack = a;//state
health = h;//state
knockedOut = false;
}
public abstract int takeDamage(Pokemon enemy);
public String toString() {
return "}";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public boolean isKnockedOut() {
return knockedOut;
}
public void setKnockedOut(boolean knockedOut) {
this.knockedOut = knockedOut;
}
}
public abstract class Charizard extends Pokemon {
private static String Fire;
private int attackFire;
private int healthFire;
private static String Water;
private static String Grass;
public Charizard(int a, int h) {
super("Charizard", Fire, a, h);
attackFire = a;
healthFire = h;
}
public int takeDamage(Pokemon enemy){
int enemyAttack = enemy.getAttack();
if(enemy.getType().equals(Water)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()*2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
}
else if(enemy.getType().equals(Fire)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()*2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
}
else if(enemy.getType().equals(Grass)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()/2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
if(healthFire <=0){
Charizard.set = true;
}
}
return enemyAttack;
}
}
You want to declare your different types like this:
static public final String GRASS= "Grass";
static public final String WATER = "Water";
static public final String FIRE = "Fire";
(I'm following the established convention here that fields declared static, public, and final should have names in all uppercase letters.)
By declaring these fields public, any other classes (including those that extend Pokemon, such as Charizard) that might need to test the type of a Pokemon can use them. By declaring them final, nobody can change them even though they are public. By giving them initial values, you make them actually useful for distinguishing different types of Pokemon, as well as avoid the inevitable NullPointerException that would happen the first time you executed something like p.getType().equals(Pokemon.FIRE)
As for knockedOut, it looks like you're handling it the right way. The field knockedOut is private in Pokemon but you've provided public getter and setter methods that other classes can (and do) use to access it.

How to acces a void method from another class?

how do I call a void method from another class to a new class with main?
I have two classes, but I don't see the error I am making.
public class Person {
private int age;
private String name;
public Person(int a, String n) {
a = age;
n = name;
}
public void printInfo() {
System.out.println(age + name);
}
//
public class Main {
public static void main(String[] args) {
Person obj1 = new Person(22, "Dan");
obj1.printInfo();
}
}
EDIT: Move the main method to a different class and done.
TestPerson.java
public class TestPerson {
public static void main(String[] args) {
Person obj1 = new Person(22, "Dan");
obj1.printInfo();
}
}
You have few mistakes in your code. It should be like as follows :
public class Person {
private int age;
private String name;
//Your constructor was wrong
public Person(int a, String n) {
age = a;
name = n;
}
public void printInfo() {
System.out.println(age + name);
}
}

Categories