How to execute different classes in one class - java

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();
//.....
}
}
}

Related

Function Called Multiple Times

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);
}
}

How can I test multiple inputs from console?

I need to test input from console in my program:
Main.java - class with main logic.
public class Main {
public static void main(final String[] args) {
final Integer dividend = new IntegerReader().fetchIntegerNumber("Input dividend: ");
final Integer divisor = new IntegerReader().fetchIntegerNumber("Input divisor: ");
System.out.println(dividend);
System.out.println(divisor);
}
}
IntegerReader.java - reads integer number from input.
import java.util.Scanner;
public class IntegerReader {
public Integer fetchIntegerNumber(final String message) {
System.out.print(message);
final Scanner scanner = new Scanner(System.in);
final String inputString = scanner.nextLine();
scanner.close();
return Integer.valueOf(inputString);
}
}
MainTest.java - test of Main.java class.
class MainTest {
private final InputStream testInputStream = new ByteArrayInputStream("2\n3".getBytes());
private final ByteArrayOutputStream testOutputStream = new ByteArrayOutputStream();
private InputStream initialInputStream = System.in;
private PrintStream initialOutputStream = System.out;
#BeforeEach
void setUpStreams() {
System.setIn(testInputStream);
System.setOut(new PrintStream(testOutputStream));
}
#AfterEach
void restoreDefaultStreams() {
System.setIn(initialInputStream);
System.setOut(initialOutputStream);
System.out.println("Test initial output stream");
}
#Test
void fetchesTextFromInput() {
Main.main(new String[]{});
final String actual = testOutputStream.toString();
assertThat(actual, is("Input dividend: Input divisor: 2\n3"));
}
}
When I run test, I get exception: java.util.NoSuchElementException: No line found.
This exception is thrown, if I try to read second number (divisor) on line:
final String inputString = scanner.nextLine();
How can I fix test, so that exception will not occur?
I would design the IntegerReader in the way that it accepts a scanner:
public class IntegerReader {
private final Scanner scanner;
public IntegerReader(Scanner theScanner) {
this.scanner = theScanner;
}
public Integer fetchIntegerNumber(final String message) {
System.out.print(message);
final String inputString = scanner.nextLine();
return Integer.valueOf(inputString);
}
}
The main class would look like this:
public class Main {
private Scanner scanner;
public Main(Scanner theScanner) {
this.scanner = theScanner;
}
public static void main(final String[] args) {
new Main(new Scanner(System.in)).process();
}
public void process() {
final Integer dividend = new IntegerReader(scanner).fetchIntegerNumber("Input dividend: ");
final Integer divisor = new IntegerReader(scanner).fetchIntegerNumber("Input divisor: ");
System.out.println(dividend);
System.out.println(divisor);
}
}
The test then looks the following way:
// this test still fails, but. ..
public class MainTest {
private final InputStream testInputStream = new ByteArrayInputStream("2\n3\n".getBytes());
private final ByteArrayOutputStream testOutputStream = new ByteArrayOutputStream();
private PrintStream initialOutputStream = System.out;
#Before
public void setUpStreams() {
System.setOut(new PrintStream(testOutputStream));
}
#After
public void restoreDefaultStreams() {
System.setOut(initialOutputStream);
System.out.println("Test initial output stream");
}
#Test
public void fetchesTextFromInput() {
Scanner scanner = new Scanner(testInputStream);
Main main = new Main(scanner);
main.process();
final String actual = testOutputStream.toString();
Assert.assertEquals("Input dividend: Input divisor: 2\n3", actual);
}
}
In this way the scanner is not closed.
Note that the test is not green. I used JUnit, I don't know which technology you used.
Please note:
If I design a class I would not make it dependend on System.*, but give it some stream to work with. This eases testing.
if you use new anywhere in your code you need to know whether the class has the concern to do this or if someone else, a builder or factory should rather create this instance.
You don't want to invoke scanner.close(); because Scanner.close() will close the underlying Closable instance, here System.in and so your dummy test inputstream will be discarded.
Besides even by removing the explicit closing operation it will still fails at runtime :
public Integer fetchIntegerNumber(final String message) {
System.out.print(message);
final Scanner scanner = new Scanner(System.in);
final String inputString = scanner.nextLine();
// REMOVED scanner.close();
return Integer.valueOf(inputString);
}
because the method return will make the scanner eligible to be GC and so System.in will still be closed.
What you want is that System.in.close() be not invoked.
You have two simple ways : Prevent this invocation from the scanner instance or from the underlying resource instance directly (System.in).
You could decorate System.in with FilterInputStream.
For example :
InputStream inWithoutClose = new FilterInputStream(System.in) {
#Override
public void close() throws IOException {
}
}
Then modify the method to test to make it accept this object.

Java Check user input against variables in another class

I am building an easy Knock Knock game. I have it finished but I would like to add a small feature. It is currently set to accept only a few words/phrases as the correct response and everything else it produces an "error" of sorts. I want to create a class with a list of acceptable works or phrases and have the users input checked against that class.
Here is the test class I created to play with.
import java.util.*;
public class test
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Choose a word");
String userEntry = sc.next().toLowerCase();
if (userEntry.equals(test1.*))
{
System.out.println("We found a match");
}
else if (!userEntry.equals(test1.*))
{
System.out.println("We did not find a match");
}
}
}
The code is of the class that will house the variables.
public class test1
{
public static String a = "yes";
public static String b = "hello";
public static String c = "boo";
}
In the first class, I tried using a wild card to call all of the variables in the class but it produces an error. Any help would be greatly appreciated.
You can't do a wildcard search like that in Java.
You really don't need another class, you can just put all the words/phrases in a List and check against the List.
Example:
import java.util.*;
public class test
{
static Scanner sc = new Scanner(System.in);
// add all the words you need into this array
static String [] wordArr = new String[] { "yes", "hello", "boo" };
// this converts the array to a List
static final List<String> WORDS
= new ArrayList<String>(Arrays.asList(wordArr));
public static void main(String[] args)
{
System.out.println("Choose a word");
String userEntry = sc.next().toLowerCase();
// check if the word is in the list
if (WORDS.contains(userEntry))
{
System.out.println("We found a match");
}
else
{
System.out.println("We did not find a match");
}
}
}
Side Note: You should consider creating the Scanner in the main method and close the scanner when you are done with it.
try this
class test1
{
public static list<String> addElement(){
List<String> list=new ArrayList<>();
list.add("yes");
list.add("boo");
list.add("hello");
}
}
class test{
public static void main(String[] args0)
{
Scanner sc=new Scanner(System.in);
String match=sc.next();
ArrayList<String> list=test1.addElement();
for(String test : list)
{
if(test.equels(match)
print("we have found match");
else
print("no match found"):
}
}
}

How to use method showMessage()?

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);
}
}

Use a string from an outside class to the main class

I have a main class file that calls methods as objects from other outside class files.
I'm having a hard time using a string in the main class file that was defined in an outside class file.
This is the main class:
import java.util.Scanner;
public class TW5K
{
public static void main(String[] args)
{
CiteNum citenumber = new CiteNum();
PlateNum platenumber = new PlateNum();
DateNum datenumber = new DateNum();
citenumber.CiteEnt();
platenumber.PlateEnt();
datenumber.DateEnt();
System.out.println(); // I want to print the string "dateld" here, from the outside class.
}
}
This is the outside class:
import java.util.Scanner;
public class DateNum
{
public void DateEnt()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter date of violation: ");
String dateld = input.nextLine();
System.out.println();
}
}
Return the value:
public String DateEnt()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter date of violation: ");
String dateld = input.nextLine();
System.out.println();
return dateld;
}
Then:
String dateld = datenumber.DateEnt();
System.out.println(dateld);

Categories

Resources