Coding Issue with Java game - java

I'm writing some code for a text based game for my Computer Science class, but I'm having some problems with this code
(java code).
The all the code works until I put in the if/else statements, so I want to know where I should be putting the statements at.
(Error Message)
Code:
import java.util.Scanner;
import java.util.ArrayList;
class Progress {
public String udc;
public String u = "up";
public String d = "down";
public void start() {
System.out.println("Hello.");
}
public void c1() {
Scanner name=new Scanner(System.in);
System.out.println("What's your name?");
System.out.println("Hello "+name.nextLine()+".");
}
public void uod() {
Scanner ud = new Scanner(System.in);
System.out.println("Up or down?");
udc = ud.nextLine();
}
public void uodc() {
System.out.println("going "+udc+".");
}
public void end() {
System.out.println("Press any key to exit");
}
}
public class APGame {
public static void main(String[] args) {
Progress p =new Progress();
p.start();
p.c1();
p.uod();
if (u.equals(udc)) {p.uodc();}
else {p.oud();}
p.end();
}}

u and udc variables are defined inside another class, that is Progress, and should be accessed (as they are public), by p.u and p.udc.
if (p.u.equals(p.udc)) ...

udc and u are instance variables of the class Progress. So the problem with the if-else statement is that you are not referencing udc from any object of the Progress class. To fix it do:
if(p.u.equals(p.udc) {
p.uodc();
}else{
p.uod();
}

Related

Cannot resolve symbol 'execute' when executing AsyncTask [duplicate]

What's the issue here?
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
UserInput input = new UserInput();
input.name();
}
This complains:
<identifier> expected
input.name();
Put your code in a method.
Try this:
public class MyClass {
public static void main(String[] args) {
UserInput input = new UserInput();
input.name();
}
}
Then "run" the class from your IDE
You can't call methods outside a method. Code like this cannot float around in the class.
You need something like:
public class MyClass {
UserInput input = new UserInput();
public void foo() {
input.name();
}
}
or inside a constructor:
public class MyClass {
UserInput input = new UserInput();
public MyClass() {
input.name();
}
}
input.name() needs to be inside a function; classes contain declarations, not random code.
Try it like this instead, move your myclass items inside a main method:
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
public static void main( String args[] )
{
UserInput input = new UserInput();
input.name();
}
}
I saw this error with code that WAS in a method; However, it was in a try-with-resources block.
The following code is illegal:
try (testResource r = getTestResource();
System.out.println("Hello!");
resource2 = getResource2(r)) { ...
The print statement is what makes this illegal. The 2 lines before and after the print statement are part of the resource initialization section, so they are fine. But no other code can be inside of those parentheses. Read more about "try-with-resources" here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Java accessing another class not working

I am making a game that requires an update class to access a game class and a main class to access both of those. The problem I am having is that I need the update class to have an updated object of the game class but I get an error whenever I try and access the game class from the Update class [error occurs on newGame.test();]
ERROR: Exception in thread "main" java.lang.NullPointerException
at Updates.updateStats(Updates.java:17)
at Game.gameLoop(Game.java:24)
at Main.main(Main.java:14)
import java.util.Scanner;
public class Main
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Game newGame = new Game();
//Updates getUpdates = new Updates();
newGame.setupGame();
Game.isRunning=true;
newGame.gameLoop();
}
}
import java.util.Scanner;
public class Game {
static Scanner input = new Scanner(System.in);
Updates getUpdates = new Updates();
public Game(){
}
String goverment;
int happyness;
double money;
int population = 1000000;
public static boolean isRunning;
private int turn = 0;
public void gameLoop(){
while (isRunning){
getUpdates.updateStats();
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
public void setupGame()
{
System.out.println("Goverment: 1=Democracy 2=monarchy 3=dictatorship");
goverment = input.nextLine();
while (!goverment.equals("1")||!goverment.equals("2")||!goverment.equals("3")){
if (goverment.equals("1")){
happyness = 75;
money = 250000.0;
break;
}
else if (goverment.equals("2")){
happyness = 50;
money = 500000.0;
break;
}
else if (goverment.equals("3")){
happyness = 25;
money = 750000.0;
break;
}
else{
System.out.println("ENTER A VALID VALUE");
goverment = input.nextLine();
}
}
System.out.println("1");
}
public int getHappyness(){
return happyness;
}
public void test(){
System.out.println("MY NAME IS BOB");
}
}
import java.util.Scanner;
public class Updates {
static Scanner input = new Scanner(System.in);
public Updates(){
}
public Updates(Game newGame){
this.newGame = newGame;
}
Game newGame;
public void updateStats(){
newGame.test();
}
}
I'm sorry if this isn't very much help, but it's my first time answering a question on here.
I put your code into a test project to see where the issue was, and it seems you have a few errors.
I'll start with the Main class as it has the smallest issues.
You don't need to declare the scanner object here as it's never used. You're just allocating memory to an empty object.
Now, onto the Updates class.
Again, no need to declare a scanner here.
To use the object "newGame" you need to make sure you're making use of the Constructor:
public Updates(Game newGame){
this.newGame = newGame;
}
And not:
public Updates(){
}
Because the latter one won't set the Game object for you, and any time you access it you will get a nullpointer.
Finally, the Game class:
I'd make both the Scanner and the Updates objects private, as they're never used outside the class. If they are, make use of getters and setters.
In your Game constructor, you can actually create both the getUpdates and input objects, like so:
public Game() {
this.input = new Scanner(System.in);
this.getUpdates = new Updates(this);
}
That way whenever your game is initialized, you'll have them at the ready. As you can see, I put
new Updates(this)
which uses the Updates constructor I mentioned before. This should ultimately solve your issue.
For reference, here are the files I used/edited and it worked on my end:
Pastebin link

Java variable 'never used'

I am learning Java and currently attempting to combine if statements and multiple class files.
It is a simple I/O program with a twist, if userName = JDoe I want the program to say something other than the standard saying.
From main.java:
import java.util.Scanner;
import java.lang.String;
class main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
UInput uInput = new UInput();
System.out.println("What is your name: ");
uInput.setName(input.nextLine());
uInput.saying();
}
}
class ifMain {
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
From UInput.java:
public class UInput {
private String userName;
public void setName(String name){
userName = name;
}
public String getName(){
return userName;
}
public void saying(){
System.out.printf("Hello %s", getName());
}
}
However, in class ifMain{}, IntelliJ is saying "Variable userName never used", what am I missing?
See comments:
class ifMain {
public static void main(String[] args){
String userName = "JDoe"; // <=== Declared here
if (test.matches("JDoe")) { // <=== Not used here
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
The local variable userName is never used in the main method of the ifMain class.
You probably meant:
if (test.matches(userName)) {
Side note: The overwhelming convention in Java is that class names start with an uppercase character. So IfMain, not ifMain.
Your program wouldn't even compile in first place. I believe that you are new to Java. But still, look at this code.
class ifMain {//Please change the class name to CamelCase convention
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {// Compile error. Variable test is not declared.
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
Are you trying in a notepad and executing it? You can try using eclipse/NetBeans/IntelliJ IDEs in that case to help you better.

Event listener/ Scanner in Gridworld

I'm trying to control Bugs in GridWorld. I have tried two ways of doing this, neither of which have actually moved or turned the bug. They both compile but nothing happens.
Here is the Bug that will be controlled:
package info.gridworld.actor;
import info.gridworld.grid.*;
import info.gridworld.grid.Location;
import java.awt.Color;
public class MazeBug extends Bug {
public MazeBug() {
super(Color.blue);
}
public void forward(){
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
public void turnRight(){
setDirection(getDirection() + Location.RIGHT);
}
public void turnLeft(){
setDirection(getDirection() + Location.LEFT);
}
}
Here is the first way that I tried controlling the bugs with the keys W,A, and D using Scanner (not sure if I used scanner correctly)
package info.gridworld.actor;
import java.util.Scanner;
import info.gridworld.grid.*;
public class KeyTests extends Actor
{
public static ActorWorld world = new ActorWorld(new BoundedGrid<Actor>(20, 20));
public static MazeBug currentBug;
public static void main(String[] args) {
world.show();
world.add(new Location(1,11),new MazeBug());
while(true){
Scanner k = new Scanner(System.in);
String buttonpress = k.nextLine();
if (buttonpress.equals("w"))
currentBug.forward();
if (buttonpress.equals("d"))
currentBug.turnRight();
if (buttonpress.equals("a"))
currentBug.turnLeft();
}
}
}
Here is the 2nd way I tried to control the bug
package info.gridworld.actor;
import info.gridworld.grid.*;
public class KeyTests extends Actor
{
public static ActorWorld world = new ActorWorld(new BoundedGrid<Actor>(20, 20));
public static MazeBug currentBug;
public static void main(String[] args) {
world.add(new Location(1,11),new MazeBug());
java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new java.awt.KeyEventDispatcher() {
public boolean dispatchKeyEvent(java.awt.event.KeyEvent event) {
String key = javax.swing.KeyStroke.getKeyStrokeForEvent(event).toString();
if (key.equals("w"))
currentBug.forward();
if (key.equals("d"))
currentBug.turnRight();
if (key.equals("a"))
currentBug.turnLeft();
world.show();
return true;
}
});
world.show();
}
}
Thanks for any help in advanced
I am almost positive that your problem is that you put your controlling code in the Runner instead of your Bug's act method.
When GridWorld steps all it does is call each Actor's act method, so if your Actor has an unpopulated method it will just call the parent, or do nothing. Your runner, since it is not an 'Actor' has no act method, and after the first run is never looked at again.
Try this in your MazeBug:
public void act()
{
java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new java.awt.KeyEventDispatcher() {
public boolean dispatchKeyEvent(java.awt.event.KeyEvent event) {
String key = javax.swing.KeyStroke.getKeyStrokeForEvent(event).toString();
if (key.equals("w"))
forward();
if (key.equals("d"))
turnRight();
if (key.equals("a"))
turnLeft();
return true;
}
});
}
Note: I have never used EventListeners so can't help with that code.

Java: Identifier expected

What's the issue here?
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
UserInput input = new UserInput();
input.name();
}
This complains:
<identifier> expected
input.name();
Put your code in a method.
Try this:
public class MyClass {
public static void main(String[] args) {
UserInput input = new UserInput();
input.name();
}
}
Then "run" the class from your IDE
You can't call methods outside a method. Code like this cannot float around in the class.
You need something like:
public class MyClass {
UserInput input = new UserInput();
public void foo() {
input.name();
}
}
or inside a constructor:
public class MyClass {
UserInput input = new UserInput();
public MyClass() {
input.name();
}
}
input.name() needs to be inside a function; classes contain declarations, not random code.
Try it like this instead, move your myclass items inside a main method:
class UserInput {
public void name() {
System.out.println("This is a test.");
}
}
public class MyClass {
public static void main( String args[] )
{
UserInput input = new UserInput();
input.name();
}
}
I saw this error with code that WAS in a method; However, it was in a try-with-resources block.
The following code is illegal:
try (testResource r = getTestResource();
System.out.println("Hello!");
resource2 = getResource2(r)) { ...
The print statement is what makes this illegal. The 2 lines before and after the print statement are part of the resource initialization section, so they are fine. But no other code can be inside of those parentheses. Read more about "try-with-resources" here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Categories