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.
Related
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
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);
}
}
Say I have the following class
class Application {
public Application() {...}
public void doSomething(final String logs) {
final String[] lines = logs.split("\\n");
for (final String line: lines) {
// Pass the line to every single checkForProp# item and do something with the response
}
}
private Optional<Action> checkForProp1(final String line) {
// Check if line has certain thing
// If so return an Action
}
// More of these "checks" here
}
Let's say every single response, would be added to a queue, and then returned something is done on that queue.
So instead of I calling each method manually, I want to have maybe an array of checker methods, and automatically loop through them, pass in the line, and add the response to a queue.
Can this be achieved?
You can implement your Action as interface:
public interface Action{
public void fireAction();
}
Those classes which implement Action will then override the method defined in the interface, such as checking a String.
Add the instances of Action to the list and you loop them accordingly.
Example:
for(Action a : actions)
a.fireAction();
If i understood your question correctly then following code may be help you.
import java.lang.reflect.Method;
public class AClass {
private void aMethod(){
System.out.println(" in a");
}
private void bMethod(){
System.out.println(" in b");
}
private void cMethod(){
System.out.println(" in c");
}
private void dMethod(){
System.out.println(" in d");
}
//50 more methods.
//method call the rest
public void callAll() {
Method[] methods = this.getClass().getDeclaredMethods();
try{
for (Method m : methods) {
if (m.getName().endsWith("Method")) {
//do stuff..
m.invoke(this,null);
}
}
}catch(Exception e){
}
}
public static void main(String[] args) {
AClass a=new AClass();
a.callAll();
}
}
Here Java Reflection is used.
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);
}
}
Hi and hope someone can help. I'm doing a short Java course and need to set up 3 classes that basically communicate between each other but I'm failing.
You'll spot from the code below that I'm trying to split the tasks of reading user's input and doing whatever maths is required into different classes but something's wrong
Any ideas? Thanks for your interest.
Here's the simple Main class:-
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.start();
}
}
The Calculator class (or part of it):-
public class Calculator {
private Reader reader;
public void Calculator(Reader reader) {
this.reader = reader;
System.out.println("Calculator set up.");
}
public void start() {
while (true) {
System.out.print("command: ");
String command = reader.readString(); // It fails here:
if (command.equals("end")) {
break;
}
if (command.equals("sum")) {
sum();
} else if (command.equals("difference")) {
difference();
} else if (command.equals("product")) {
product();
}
}
And finally the Reader class:-
public class Reader {
private Scanner input;
public void Reader(Scanner input) {
this.input = input;
System.out.println("Reader set up.");
}
public String readString() {
return input.nextLine();
}
public int readInteger() {
return Integer.parseInt(input.nextLine());
}
}
You have an issue with all the constructors you are using. Constructors are special methods with no return type, so in your case, public void Calculator(Reader reader) needs to be public Calculator(Reader reader) (remove void). The same applies to the other constructors.
Once you do that, you would need to make amendments on how you are instantiating your Calculator class:
Calculator calculator = new Calculator();
Should become:
Calculator calculator = new Calculator(new Reader(new Scanner(System.in)));
provide constructor not mothod.
Calculator(Reader reader) {
this.reader = reader;
System.out.println("Calculator set up.");
}
after that you can change your main method with #subhrajyoti suggested.
apart from above suggestion ,
1> your constructors (Reader and Calculator) is returning void. But constructor cannot return any value. So, remove void keyword.
you have to import Scanner class (i.e. java.util.scanner).