Java Assignment, add value to variable in different class - java

currently doing an assignemnt but i'm new to programming so was wondering how you add a value to a variable in a different class which already has an existing class
class OtherClass {
int a;
}
public class Main Class{
public static void main(String[] args) {
int b = 7;
OtherClass temp = new OtherClass();
OtherClass.a = 5
OtherClass.put(b) //this is where I'm not sure how to add b to a
}
Actual Code
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("Enter amount of money you have: ");
Scanner input = new Scanner(System.in);
Wallet bettersWallet = new Wallet();
bettersWallet.moneyAvailable = input.nextDouble(); //then had a function which played out a bet and added/took away winnings from the bet
int winnings = 5;
bettersWallet.moneyAvailable +=winnings; //Will setMoneyAvailable function work in this scenario aswell?
}
class Wallet {
double moneyAvailable;
double openingCash;
public void setMoneyAvailable()
{
moneyAvailable += ChuckALuckDiceGame.winnings;
}

int b = 7;
OtherClass temp = new OtherClass();
temp.a = 5;
temp.a += b; //Same as temp.a = temp.a + b;
System.out.println(temp.a);
What we are doing here,
We are creating an object of class OtherClass, the name of the object is temp.
Then we are assigning the value 5 in the attribute a of object temp
Then we are adding the value of primitive variable b into the variable temp.a.
The sum of the above equation is being assigned to the value of temp.a
Then I am printing the sum at the end through System.out.println(temp.a);

Related

How to run a method from a different class - JAVA [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to call the toh method from my main class(Driver). When I make the call it gives me a null pointer exception. How can I call the toh method in Hanoi from the driver class? When I combine the classes into one it works fine but I need them to be two separate classes. Also, I included the global variables I am using in both classes is that necessary? Any help is welcome. Thanks!
public class Hanoi {
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void toh(int n)
{
for (int d = n; d > 0; d--)
tower[1].push(d);
display();
move(n, 1, 2, 3);
}
/* Recursive Function to move disks */
public static void move(int n, int a, int b, int c)
{
if (n > 0)
{
move(n-1, a, c, b);
int d = tower[a].pop();
tower[c].push(d);
display();
move(n-1, b, a, c);
}
}
/* Function to display */
public static void display()
{
System.out.println("T"+cycle + " Pillar 1 | Pillar 2 | Pillar 3");
System.out.println("-------------------------------------");
for(int i = N - 1; i >= 0; i--)
{
String d1 = " ", d2 = " ", d3 = " ";
try
{
d1 = String.valueOf(tower[1].get(i));
}
catch (Exception e){
}
try
{
d2 = String.valueOf(tower[2].get(i));
}
catch(Exception e){
}
try
{
d3 = String.valueOf(tower[3].get(i));
}
catch (Exception e){
}
System.out.println(" "+d1+" | "+d2+" | "+d3);
}
System.out.println("\n");
cycle++;
}
}
Main class(driver):
public class Driver{
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void main(String[] args)
{
int num = 0;
Scanner scan = new Scanner(System.in);
tower[1] = new Stack<>();
tower[2] = new Stack<>();
tower[3] = new Stack<>();
/* Accepting number of disks */
while(num <=0){
System.out.println("Enter number of disks(greater than 0):");
num = scan.nextInt();
}
N = num;
Hanoi.toh(num);
}
}
You are initializing your tower array inside your Driver class, however, you have not initialized it in your Hanoi class.
As I said in my comment, please do not write global variables twice, in different classes. This is because the different classes DO NOT share the same global variables. (when we say global variable, we mean that they are global to the Driver class only. To access those variables, use the dot operator)
For example, get rid of the N cycle and tower declarations from your Hanoi class
Then access those variables using the dot operator.
tower would become Driver.tower and N would become Driver.N and so forth.
Note: this only works if your Driver class is static, otherwise you would need to access it as an object attribute.
Try to initialize the tower array, something like this:
public static Stack<Integer>[] tower;
public static void toh( int n )
{
tower = new Stack[n];
for ( int d = 0 ; d < n ; d++ )
{
tower[d]=new Stack<>();
}
delete duplicated static values in a class (either Driver or Hanoi)
then in the class that no longer has the static values and add that class to the beginning of all the missing classes.
Ex:
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public static int MyVar;
public void bMethod(){
++MyVar;
}
}
↓ to ↓
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public void bMethod(){
++A.MyVar;
}
}

Loop not recognizing variables previously defined

I'm working on a Guessing Game that will uses arrays to store both the names of all the players and their guesses. I'm fairly new to arrays, so my plan to get user input into the array was to get them to enter the amount of people playing, set that up as a variable and then use a loop to keep asking for names until I reached the necessary amount of names for the stated number of players. However, I am running into what probably is a very simple problem with the loop. Here's a small bit of my code thus far:
public class GuessGame {
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
The problem is, I'm getting an error regarding the variables in my loop, w and j. The error statement says something to the effect of it cannot find the symbols for class w or class j. I don't intend for them to be classes, and I've run similar code in other projects without a hitch, so I really don't know what's going wrong here. I'm sure it's something stupidly simple, but *'ve been stuck at this wall for some time now and can't really progress until I get this sorted. This is part of a project with three separate classes. The class posted here, a Player class, and a Tester class, which is my main method. I had the whole thing working in a more simplified form earlier, but now I need to adjust it for actual player input and the arrays. Regardless, the tester class is supposed to be my main class. I am using Netbeans if it matters. Thank you. Here are the other two classes for reference:
package GuessGame;
public class GameLauncher {
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
and
package GuessGame;
import java.util.Random;
public class Player {
int number = 0; //where guess goes
String name;
public void guess() {
Random r = new Random();
number = 1 + r.nextInt(21);
System.out.println("I'm guessing " + number);
}
}
All your code needs to be in a method. You cannot have anything except variable declarations at the class level. Move all this into a method, for example public static void main(String[] args) main method.
public class GuessGame {
public static void main (String[] args)
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}
public class GuessGame {
public void getPlayerName()
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
public static void main (String[] args)
{
GuessGame gg = new GuessGame();
g.getPlayerName();
}}
You can put in the methos as well and execute in the main method. But, if you declaring any variable inside the method (local variable), the variable must be initialised. Refer here for more details.
public class GuessGame
{
static int w = 0;
int[] Players = new int[100];
static String[] PlayerNames = new String[100];
public static void main(String[] args) {
// TODO Auto-generated method stub
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}
Everything should be in a method except variables.Class is template for variables and methods !!

How to make an Array Accessible from instantiation in main class? Accessible to all classes in same class

I want to run a method that returns an array. Code such as this:
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println(
"Please input the integer for position " + (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
I have researched that you can make a variable like so int[] data = getArray();
How would I make it so that data can be accessible to other methods in the same class so I could do something like
public static int linearSearch(data) {
}
without having to constantly be re-entering the values for the array?
You can try out to introduce private variable of int[] and provide a lazy initialization for it, something like this:
class aClass {
int[] data; // default to the null
private int[] getArray() {
if (data == null) {
// your console logic for initialization
}
return data;
}
public static int linearSearch() {
int[] localData = getArray();
}
}
But in this case you can change the contents of data field in your methods across the class.
This can be done two ways:
- Either declaring the variable as class-level variable
- Or declaring it as local variable inside main method
public class ReturnIntArraysSO {
/**
* #param args
*/
public static void main(String[] args) {
int[] data = getArray();
for(int i : data){
System.out.print(i+" ");
}
linearSearch(data);
}
/**
*
* #return
*/
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Please input the integer for position "
+ (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
/**
*
* #param data
* #return
*/
public static void linearSearch(int[] data) {
for(int a : data){
if(a == 5){
System.out.println("\nFound 5!!");
}
}
}
}
You need to declare i your array like this:
public YourClass {
public static int[] square = new int[5];
}
This way you can access this array from any other class and it will remain with the exact array (that's what static for). Example:
From Class1 - YourClass.square
From Class2 - YourClass.square
Both are the same array instance

Method undefined for type method?

I have a program to find pythagorean triples. in it, i have an object that needs to be used to call methods. Said object is broken. Errors are " The method Triples(int) is undefined for the type Triples" and "The method greatesCommonFactor() is undefined for the type Triples" mind you, not everything in Triples does useful stuff atm. It isn't completely finished yet.
public class TriplesRunner
{
public static void main(String args[])
{
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the natural number :: ");
number=keyboard.nextInt();
Triples test = new Triples();
test.Triples(number);
test.greatestCommonFactor(number);
System.out.println(test.toString());
}
}
public class Triples
{
public int number;
public Triples(int num)
{
setNum(number);
}
public void setNum(int num)
{
int a = 0;
int b = 0;
int c = 0;
}
public int greatestCommonFactor(int a, int b, int c)
{
int max = 0;
for(a=1; a<=number-2; a++)
{
for(b=a+1; b<=number-1; b++)
{
for(c=b+1; c<=number; c++)
{
if(a*a + b*b == c*c);
}
}
}
return 1;
}
public String toString()
{
String output="";
output+="a + b + c";
return output+"\n";
}
}
you are trying to call the constructor as a method,
Change this part:
Triples test = new Triples();
test.Triples(number);
to
Triples.test = new Triples(number);
Triples isn't a method - it's your constructor, meaning it's invoked with the new operator:
Triples test = new Triples(number);
greatestCommonFactor is not defined properly. It currently takes three int arguments, instead of taking none and using Triples' data members:
public int greatestCommonFactor()

NullPointerException but compiling?

I'm writing a simple command line game.
I've got many functions and all, and will only post the essential here.
Problem: The program compiles but when levelup() is called and a number is chosen, I get this:
You have 5 skill points to spend.
What would you like to upgrade?
[1:] STR [2:] DEF
1
Exception in thread "main" java.lang.NullPointerException
at Game.levelup(cmdquest.java:300)
at Game.start(cmdquest.java:336)
at Menu.show_menu(cmdquest.java:195)
at cmdquest.main(cmdquest.java:263)
Here is my code:
class Player{
String name;
int hp;
int str;
int def;
String eff;
Player(String n) {
name = n;
hp = 100;
str = 1;
def = 1;
eff = "none";
}
}
class Game{
static Player p;
static void levelup(){
while (points > 0){
System.out.println("\t[1:]\tSTR\t\t\t[2:]\tDEF");
int lvlup = kb.nextInt();
switch (lvlup){
case 1: p.str++;
break;
case 2: p.def++;
break;
}
points--;
}
//variables
static Scanner kb = new Scanner(System.in);
static int points = 5;
}
static void start(){
System.out.print("\t\t\t\tAnd so our adventure starts.....");
System.out.print("\tWhat's your name: ");
String nome = kb.next();
Player p = new Player(nome);
System.out.println("\tHello " + p.name);
System.out.println("\tYou have 5 skill points to spend.\n\tWhat would you like to upgrade?");
levelup();
}
class cmdquest{
public static void main(String args[]) throws Exception{
Scanner kb = new Scanner(System.in);
//Importing foes.txt to create objects of foes
java.io.File file = new java.io.File("foes.txt");
Scanner imp = new Scanner(file);
for(int i =0; i<3; i++){
foes[i]=foe.leDados(imp);
}
//____________________________________________
Game.start();
}
}
Can anyone point me in the right direction here?
What am I doing wrong? I sense it's a class problem with the class "Player" and the object being created in the "Game" class.
You get a NullPointerException because p is null. What you've done here:
Player p = new Player(nome);
is declare a local variable p. The static class variable p is untouched, so it remains null.
This is called shadowing (JLS, Section 6.4.1):
Some declarations may be shadowed in part of their scope by another
declaration of the same name, in which case a simple name cannot be
used to refer to the declared entity.
...
A declaration d of a type named n shadows the declarations of any
other types named n that are in scope at the point where d occurs
throughout the scope of d.
Remove Player, so the reference to the static class variable p is what you want:
p = new Player(nome);

Categories

Resources