Trying to code a text game and when asking for GameSettings class input, the function gets called 3 times. I am trying to send the code back and forth between the classes, the reason why I am using different classes to make the code a bit more clean so that when I am sending the monsterHealth...etc it is readable.
Game.Java
package src;
import java.io.IOException;
public class Game {
public static void main(String[] args) throws IOException {
GameSettings GameSettings = new GameSettings();
GameSettings.init();
// GameSettings.Classes();
GameSettings.StartLogic();
if (src.GameSettings.Classes().equals("mage")) {
System.out.println("mage");
}
else if (src.GameSettings.Classes().equals("warrior")) {
System.out.println("warrior");
}
else if (src.GameSettings.Classes().equals("archer")) {
System.out.println("archer");
}
else {
System.out.println("Non valid");
}
}
}
GameSettings.Java
package src;
import java.util.Scanner;
public class GameSettings extends Game {
public interface classChoice {
}
public int playerHp;
private static Scanner scanner;
private static String nameInput;
private static String classChoice;
private String mage;
private String archer;
private String warrior;
public void init() {
scanner = new Scanner(System.in);
System.out.println("Welcome To Fizzle's Text Based RPG\nWhat Is Your
Name?");
nameInput = scanner.nextLine();
}
public static String Classes() {
System.out.println("Welcome " + nameInput + " What Class Would You Like
To Be?\n(mage)\n(warrior)\n(archer)");
classChoice = scanner.nextLine();
return classChoice;
}
public void StartLogic() {
playerHp = 10;
System.out.println(classChoice);
}
}
I see your problem. In the
GameSettings.StartLogic();
if (src.GameSettings.Classes().equals("mage")) {
System.out.println("mage");
}
else if (src.GameSettings.Classes().equals("warrior")) {
System.out.println("warrior");
}
else if (src.GameSettings.Classes().equals("archer")) {
System.out.println("archer");
}
else {
System.out.println("Non valid");
}
You're calling the GameSettings.Classes().equals() method three times. Instead of doing this, define a String variable before the if/else block like this:
GameSettings.StartLogic();
String input = src.GameSettings.Classes();
if (input.equals("mage")) {
System.out.println("mage");
}
else if (input.equals("warrior")) {
System.out.println("warrior");
}
else if (input.equals("archer")) {
System.out.println("archer");
}
else {
System.out.println("Non valid");
}
This is because when you use the if/else statement, you shouldn't call methods that rely on luck or user input inside of the statement, but define them as variables beforehand and pass those in as arguments to the if/else statement. Hope this helps!
Hello Fizzle! :)
Please clarify your question.
I added a few comments to your code:
Game.java
import java.io.IOException;
public class Game {
public static void main(String[] args) throws IOException {
GameSettings GameSettings = new GameSettings();
GameSettings.init();
GameSettings.StartLogic(); //returns null
if (GameSettings.Classes().equals("mage")) {
System.out.println("mage");
} else if (GameSettings.Classes().equals("warrior")) {
System.out.println("warrior");
} else if (GameSettings.Classes().equals("archer")) {
System.out.println("archer");
} else {
System.out.println("Non valid");
}
}
}
GameSettings.java
import java.util.Scanner;
public class GameSettings extends Game {
//why did you declare an Interface?
public interface classChoice {
}
public int playerHp;
private static Scanner scanner;
private static String nameInput;
private static String classChoice;
public void init() {
scanner = new Scanner(System.in);
System.out.println("Welcome To Fizzles Text Based RPG What Is Your Name?");
nameInput = scanner.nextLine();
}
public static String Classes() {
System.out.println("Welcome " + nameInput + " What Class Would You Like To Be?\n(mage)\n(warrior)\n(archer)");
classChoice = scanner.nextLine();
return classChoice;
}
//why are you calling this method beforehand?
public void StartLogic() {
playerHp = 10;
System.out.println("Your Class:" + classChoice);
}
}
Related
How do I ignore the sysout statement while testing the following method?
public int inputBoardSize() {
System.out.print("Enter the number of grids you want to play with:");
while (flag) {
try {
boardSize = validateBoardSize(Integer.parseInt(scan.nextLine()));
} catch (NumberFormatException e) {
System.err.println("Please enter a number");
}
}
printBoard(boardSize);
return boardSize;
}
So when I am testing this method, I get a prompt asking me to enter the number of grids. How do I solve this?
You need to mock the resource. Therefore create a wrapping interface like
public interface LineProvider {
String nextLine();
}
and implementing classes, first the class that you will use in the actual program:
public class UserInput implements LineProvider {
private Scanner mScanner;
public UserInput(Scanner scanner) {
mScanner = scanner;
}
#Override
public String nextLine() {
return mScanner.nextLine();
}
}
And then your mock that you will use for tests:
public class UserInputMock implements LineProvider {
private String mLineToReturn;
public UserInputMock(String initialLine) {
mLineToReturn = initialLine;
}
public void setLineToReturn(String lineToReturn) {
mLineToReturn = lineToReturn;
}
#Override
public String nextLine() {
return mLineToReturn;
}
}
Now let your method accept the resource as parameter:
public int inputBoardSize(LineProvider provider) {
...
boardSize = validateBoardSize(Integer.parseInt(provider.nextLine()));
...
}
And in your main program you use an UserInput like
UserInput userInput = new UserInput(scan);
...
inputBoardSize(userInput);
whereas in your test you use the mock:
UserInputMock mock = new UserInputMock("hello world");
inputBoardSize(mock); // Not valid
mock.setLineToReturn("5");
inputBoardSize(mock); // Valid
Note that there are frameworks to make stuff like that easier.
My current issue is that I need to be able to know the status of the basic player instance at all times. This would require a thread to get the status while the scanner waits for input from the user. The status would be used to automatically play the next audio file. Things I have done. First I made sure that this code that works inline. Next I tried to it in the thread, to no avail. I think it has to do with syncing the object between both threads
I tried making a synchronized getter of the basic player instance but it did not work
public class Player implements Runnable {
private String song;
private boolean comp = false;
private String path;
private final BasicPlayer player;
public Player () {
player = new BasicPlayer();
path = System.getProperty("user.dir") +"/src/Music/";
}
public void setSongName (String songName) {
song = songName;
}
public String getSongName() {
return song;
}
public void play () {
try {
player.open(new URL("file:///" + path + song));
player.play();
new Thread(new Player()).start();
} catch (BasicPlayerException | MalformedURLException e) {
e.printStackTrace();
}
}
private synchronized boolean isComplete () {
return getStatus() == 2;
}
public synchronized int getStatus(){
synchronized (player) {
return getPlayer().getStatus();
}
}
public synchronized boolean getComplete() {
return comp;
}
public synchronized void setComp(boolean comp) {
this.comp = comp;
}
private synchronized BasicPlayer getPlayer() {
synchronized (player) {
return player;
}
}
#Override
public void run() {
while (!isComplete()) {
BackendUtils.sleep(1000);
System.out.println(getStatus());
setComp(false);
}
setComp(true);
}
}
In this piece of code I am attempting to update a synchronized boolean to know then the audio is finished labeled comp. I try by using a synchronized player instance. The following code demonstrates how I tested if the threading was work or not.
import java.util.Scanner;
public class BackendTesting {
private static Scanner scanner = new Scanner(System.in);
private static Player player = new Player();
public static void main(String[] args) {
while (true) {
String input = input("$ ");
if (input.contains("ply play")) {
player.setSongName(input.substring(input.lastIndexOf(" ") + 1) + ".mp3");
player.play();
}
}
}
private static String input (String prompt) {
System.out.print(prompt);
return scanner.nextLine();
}
}
Try something like this:
In the thread class
public void run() {
MainClass.getInstance().playNextSong();
}
In the main class
public void playNextSong(){
synchronized(lock)
{
while (!isComplete()) {
lock.wait();
}
setComp(true);
lock.notifyAll();
}
}
Definitely you have to update it according to your needs.
Hope that helps.
In class we learned about methods, but I'm having a bit of trouble using them.
In a package called util, I wrote a class called IO.
public class IO {
public static float getFloat(){
String str = JOptionPane.showInputDialog("Enter a real number");
return Float.parseFloat(str);
}
public static void showMessage(Scanner s){
System.out.println(s);
JOptionPane.showMessageDialog(null, s);
}
public static Scanner getInput (String prompt){
String s = JOptionPane.showInputDialog(prompt);
return new Scanner(s);
}
}
Also in package util, I have my program, called Program 4.
public class Program4 {
public static void main(String[] args) {
IO.getInput("enter 2 integers");
IO.showMessage(Scanner(s));
}
}
What I don't understand is how do I display the 2 integers entered? One is a scanner object and one is string. How do I use the method getInput to show convert the scanner into a string? Am I going to have to write a new method and use parse?
You can get user input without using Scanner. Here is example:
IO Class
public class IO {
public static float getFloat() {
String str = JOptionPane.showInputDialog("Enter a real number");
return Float.parseFloat(str);
}
public static void showMessage(String s) {
System.out.println(s);
JOptionPane.showMessageDialog(null, s);
}
public static String getInput(String prompt) {
// JOptionPane.showInputDialog() return user input String
String input = JOptionPane.showInputDialog(prompt);
return input;
}
}
Program4 Class
public class Program4 {
public static void main(String[] args) {
// IO.getInput() return stored input String
String input = IO.getInput("enter 2 integers");
IO.showMessage(input);
}
}
I want to create a program that can do all the stuff from another code, depending on user input. Something like this:
import java.util.Scanner;
public class Main_Programm1 {
public static void main(String args[]) {
String something = "something";
String something2 = "something2";
Scanner userInput = new Scanner(System.in);
String action = userInput.next();
if (action.equals(something)) {
//here i want to execute all the code from class Main_Programm2
} else if (action.equals(something2)) {
//here i want to execute all the code from class Main_Programm3 and so on
}
}
}
How do i do it?
Actually, you've got it all done, only creates the Objects that you need ;-)
import java.util.Scanner;
// imports classes;
public class Main_Programm1
{
public static void main(String args[])
{
String something = "something";
String something2 = "something2";
Main_Programm main_prog;
Main_Programm2 main_prog2;
Scanner userInput = new Scanner(System.in);
String action = userInput.next();
if (action.equals(something))
{
main_prog = new Main_Programm();
//.....
}
else if (action.equals(something2))
{
main_prog2 = new Main_Programm2();
//.....
}
}
}
I have a text file which contains the list of all public method names. I require a Java program which reads each method name from the text file and create a method(template) for each public method name.
Say,
My text file contains, 3 methods
public static void A()
public static void B()
public static void C()
I need a output like this.
public class class_name
{
public void A_test()
{
System.out.println("Method A");
}
public void B_test()
{
System.out.println("Method B");
}
public void C_test()
{
System.out.println("Method C");
}
}
Kindly give your suggestions.
Following your example above the code below will generate a similar output. Note there is no package. NOTE As your example the generator strips static
public class ClassBuilder
{
public static String buildClass(String className,ArrayList<String> methods)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(String.format("public class %s \n{", className)).append("\n");
for (String method: methods)
{
stringBuilder.append(String.format(" %s \n {", method.trim().replace("static ","").replace("()","_test()"))).append("\n }\n\n");
}
stringBuilder.append("}");
return stringBuilder.toString();
}
public static void main(String[] args)
{
Scanner scanner = null;
try
{
scanner = new Scanner(new File("d:\\testFile.txt"));
ArrayList<String> methods = new ArrayList<String>();
while (scanner.hasNext())
{
methods.add(scanner.nextLine());
}
scanner.close();
String javaClass = buildClass("className", methods);
System.out.println(javaClass);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
output
public class className
{
public void A_test()
{
}
public void B_test()
{
}
public void C_test()
{
}
}