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);
Related
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);
My goal is currently to take a string looking like
"######
# #
# # ##"
# is here my "character" and "#" is walls that should be avoided, I want my character to get out of the box and return the pathway, I realize my example is pretty bad but I hope you understand. The idea I have currently is to read in a text-file with that String, then creating an array as a 2-D grid and then work from there, the code I have currently is:
package soko;
import java.io.*;
import java.util.*;
public class Sokoban2 {
static File file;
Scanner input;
static int b;
static int c;
static String[][] array;
public Sokoban2() {
//array = new String [9][9];
}
public int readFile() throws Exception{
Scanner input = new Scanner(System.in);
file = new File("C:/Users/joaki/Desktop/sokoban/readin.txt");
input = new Scanner(file);
while (input.hasNext()) {
b = b + 1;
String line = input.nextLine();
System.out.println(line);
}
input.close();
return b;
//array = new String[5][5];
}
public void insertStuff() {
//array[1][1]="2";
}
public void printStuff() {
for (int r = 0; r<2;r++){
String line2 = "";
for (int d = 0; d <2;d++){
line2+="["+array[d][r]+"]";
}
System.out.println(line2);
}
}
public static void main(String[] args) throws Exception{
Sokoban g = new Sokoban();
g.readFile();
//g.insertStuff();
//g.printStuff();
//g.creatingGrid(c,b);
//System.out.println(b);
}
}
I really want to print my b, at least check it's value, but my program wont return any value, it's not even returning a null or 0, I've tried to print it as well, no luck there either, ideas ?
You aren't returning the value to any variable, I just ran your code and it works fine, it counts the lines in the file.
int b = g.readFile();
System.out.println(b);
If you don't return the value to a variable you won't have access to the value of b in your main because it's out of scope, more about that here:
https://www.cs.umd.edu/~clin/MoreJava/Objects/local.html
Edit:
I actually just realized that you declared b in your class as static and I decided to run it as you have it above, I still get it printing out the amount of lines.
g.readFile();
System.out.println(b);
If you are going to have your function return a value and you don't plan on storing b then get rid of the static declaration in your class and just declare it in the function that returns b.
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 !!
The array with the names of strings of the instrument is a required field in the Instrument class, but in order to simplify the program, I will accept solutions in which tuning of an instrument is not done separately on each string. However, if you want to work with each string, a good example is found in the Week 8 Additional Notes, in which another class of instruments represented by Tuba is considered.
Please use Listings 8.3 and 8.4 as models to organize your code for Project 3 in two separate classes, one for defining the instrument, and the other one to test instruments.
Make the methods in the Instrument class to return String, unlike the example in the requirements, where such methods write directly to standard output. This is necessary because it is required that output of the test class be written to a file specified by the user on the command line.
In the test class you must have an array with 10 elements of Instrument type, populate the array with instances of the Instrument class (by using the new operator on the class constructor), and the use a while or for loop to perform tests (i.e. call Intrument class methods) on each array element.
As specified in the requirements, the test class must be started with an argument in the command line:
java Mynamep3tst myfilename.txt
where myfilename.txt is the file where all output must go. This file name should be used in the program as follows (see Listing 14.13):
java.io.File file = new java.io.File(args[0]);
java.io.PrintWriter output = new java.io.PrintWriter(file);
and when you have a message to be sent to the file,
output.println(message);
*My question is every time I try to create a new object of the instrument class within my for loop with the use of the array instrumentContent it causes an error. I cannot understand if I am not allowed to create new objects in this fashion. If I am not allowed to do it this way what is the proper way to do it so that each of my arrays are used?*
class StringInstrument {//begin class
//declare variables
boolean isTuned;
boolean isPlaying;
boolean band;
public String nameOfInstrument;
int numberOfStrings;
String nameofStringsInInstrument[] = {"E", "A", "D", "G", "B"}; //an array of string names
public StringInstrument() {//begin contructor
numberOfStrings = 5;
isTuned = false;
isPlaying = false;
band = false;
}//end constructor
public int NumberOfStrings(int stringNumber){//begin method
System.out.println("The number of strings for the " + nameOfInstrument + " is " + stringNumber );
return this.numberOfStrings = stringNumber;
}//end method
public String InstrumentNameGet() {//begin method
return nameOfInstrument;
}//end method
public void SetInstrumentName (String instrumentName) {//begin getter method
nameOfInstrument = instrumentName;
}//end method
public String InstrumentNameDisplay() {//begin method
System.out.println("Your instrument is the " + nameOfInstrument);
return nameOfInstrument;
}//end method
public boolean PlayInstrument(){//begin method
System.out.println("You are playing your " + nameOfInstrument);
return isPlaying = true;
}//end method
public boolean TuneInstrument(){//begin method
System.out.println("Tune " + nameOfInstrument);
return isTuned = true;
}//end method
public boolean stopTuneInstrument() {//begin method
System.out.println("The" + nameOfInstrument + " is out of tune.");
return isTuned = false;
}//end method
public boolean StopPlayInstrument() {//begin method
System.out.println("The " + nameOfInstrument + " has stopped playing");
return isTuned = false;
}//end method
public boolean PlayInstrumentBand() {//begin method
System.out.println("The " + nameOfInstrument + " is playing in a band");
return band = true;
}//end method
public boolean StopPlayInstrumentBand() {//begin method
System.out.println("The " + nameOfInstrument + " has stoped playing with the band");
System.out.println("\n");
return band = false;
}//end method
}//end class
public class RandyGilmanP3 {//begin class
public static void main(String[] args) throws Exception{//begin main
java.io.File file = new java.io.File("RandyGilmanP3.txt");
//create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
//Declaring, creating, and intialize arrays
String[] instrumentList = new String [10];
String[] instrumentContent = new String [10];
int[] stringNumber = new int [10];
//input string names into array
instrumentList[0] = "Guitar";
instrumentList[1] = "Violin";
instrumentList[2] = "Bass Guitar";
instrumentList[3] = "Cello";
instrumentList[4] = "Banjo";
instrumentList[5] = "Sitar";
instrumentList[6] = "Rabab";
instrumentList[7] = "Viola";
instrumentList[8] = "Harp";
instrumentList[9] = "Ukulele";
//input string amounts into array
stringNumber[0] = 5;
stringNumber[1] = 4;
stringNumber[2] = 5;
stringNumber[3] = 4;
stringNumber[4] = 5;
stringNumber[5] = 18;
stringNumber[6] = 3;
stringNumber[7] = 4;
stringNumber[8] = 47;
stringNumber[9] = 4;
for (int i = 0; i < instrumentContent.length; i++){//begin for loop
StringInstrument instrumentList[i] = new StringInstrument();
output.println(instrumentList[i].InstrumentNameDisplay());
output.println(instrumentList[i].NumberOfStrings(stringNumber[i]));
output.println(instrumentList[i].TuneInstrument());
output.println(instrumentList[i].PlayInstrument());
output.println(instrumentList[i].PlayInstrumentBand());
output.println(instrumentList[i].StopPlayInstrument());
}//end for loop
}//end main
}//end class
You've declared instrumentList[] as an array of Strings. Your for loop attempts calling the following method on these Strings:
InstrumentNameDisplay()
NumberOfStrings(String)
TuneInstrument()
`PlayInstrument()
PlayInstrumentBand()
StopPlayInstrument()
None of these are methods of the String class.
It looks like what you might be trying to do is build an array of Instruments...
For my program I have a static class which uses a Boolean statement. I would like to use this variable in my main in the instance of the user winning or losing the game.
However if I try to reference the variable it says it can not be found.
Here is a fraction of my code
boolean playerWin;
Dice.playerWin = false;
is there any reason why the symbol can not be found?
Thanks.
EDIT:
class Dice
{
static NumberFormat fmt = NumberFormat.getCurrencyInstance();
public static String playRound(double playerBet)
{
boolean playerWin;
double amountWon = 0;
if(playerWin = false)
{
Wallet.playerBalance -= playerBet;
amountWon = 0;
return fmt.format(amountWon);
}
else
{
Wallet.playerBalance *= 2;
amountWon = 1d/2d * Wallet.playerBalance;
return fmt.format(amountWon);
}
}
and in the main class
public class Game
{
public static void main(String[] args)
{
String playerName;
int playerBet;
Dice die = new Dice();
System.out.print("How much would you like to bet? ");
while(playerBet != -1 && playerBet > 0)
{
playerDie.roll();
playerDie2.roll();
computerDie.roll();
computerDie2.roll();
if(computerDie.equals(computerDie2));
{
System.out.print("Sorry you lost");
Dice.playerWin = false;
}
System.out.println();
System.out.print("How much would you like to bet on this round? ");
playerBet = in.nextInt();
The variable is in a static class and it is being used in the main method, what am I doing wrong?
Hopefully this extra bit helps.
Static class is not same as Static variable.
A static class can only be an nested class and it only means that it can exist without instance of parent class.
A static variable is entirely different concept. You need to make your variable static, just having a static class is not sufficient.