I have taken all of my classes from my intro to java college in highschool class, and put them into a package called gameChoices. I then made a class that would call these classes when the user asks for them, this is called whichGame. I've imported the classes I want called using import gameChoices."whatever game it is";. How do I call these classes in whichGame? I also have them all as public static main(string [] args), which ones shouldn't have that(I think it's just whichGame that should..)? And what would I put instead? Thanks for helping a newbie out :)
The simplest way to do it is probably to set up a big if/then statement.
if(input.equals("t"))
thisOne.start();
else if(input.equals("a"))
anotherOne.start();
else if(input.equals("y"))
yetAnotherOne.start();
And so on. Might be a pain if you have a lot of classes, or if they start with the same letter.
Not sure exactly what you want to achieve, but if you need to access a class by its name you can try Class.forName() and check for exceptions thrown (particularly, ClassNotFoundException).
Using case-insensitive String equality for the name check, if would allow you to access any existing class of your ClassLoader through reflection.
Edit
Here's your main class:
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class Main {
// initializes your map of letter->game class
private static final Map<String, Class<?>> GAMES = new HashMap<String, Class<?>>();
// constant name of main method for your games
private static final String MAIN_METHOD_NAME = "main";
// add your games
static {
GAMES.put("c", Chess.class);
GAMES.put("d", Doom.class);
// TODO moar gamez
}
public static void main(String[] args) {
try {
// prompts the user
System.out.println("Enter the game's name or starting letter: ");
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
// gets the response
String input = br.readLine();
br.close();
// iterates over your games' first letters
for (String gameName : GAMES.keySet()) {
// the input starts with one game's first letter...
if (gameName.startsWith(input.toLowerCase())) {
// gets the class
GAMES.get(gameName)
// gets its main method (typical signature is String[] args)
.getMethod(MAIN_METHOD_NAME, String[].class)
// invokes its main method with no arguments
.invoke((Object) null, (Object) null);
}
}
// handles any disaster
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Now here are two "game" classes:
package test;
public class Chess {
public static void main(String[] args) {
System.out.println("You've chosen Chess!");
}
}
... and...
package test;
public class Doom {
public static void main(String[] args) {
System.out.println("You've chosen Doom!");
}
}
Now set your "Main" class as your... main class.
When you launch the application, it will query you for an initial letter.
If you choose "c" or "d", it will print out: "You've chosen [Chess/Doom]!"
I hope this helps you getting started.
Related
Basically, I am running a few tests for a simple CLI game I am making, and initially all of my variables/objects were declared at the beginning of the main() method. I now have to create a new method that uses some of the same objects/variables, so I decided to move all of my variables out of main() and make them static/global. In doing so, I've run into a problem: despite main() throwing FileNotFoundException, I was getting the following error message:
Tests.java:14: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
static Scanner boardReader = new Scanner(board);
Here was my code, up to the problematic line:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
class Tests {
// GAME OBJECTS AND VARIABLES
// The following is used for reading, displaying, and writing to the game board.
static File board = new File("Board.txt");
static Scanner boardReader = new Scanner(board);
static FileWriter boardWriter = null;
static StringBuilder boardBuilder = new StringBuilder((int)board.length());
static String boardDisplay = null; // This String allows boardContents to print in a more readable way.
static String boardContents = null; // This is Board.txt represented as a String.
// There are more variables here than shown, but these are the ones relevant to my problem.
// GAMEPLAY
public static void main(String[] args) throws FileNotFoundException, IOException {
boolean gameIsOngoing = true;
while(gameIsOngoing) {
// boardContents String from boardBuilder StringBuilder
while (boardReader.hasNextLine()) {
boardContents = (boardBuilder.append(boardReader.nextLine() + System.lineSeparator()).toString());
}
// More irrelevant code here.
}
}
}
In trying to fix the problem, I tried to put the code utilizing boardReader inside a proper try-catch as shown here:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
class Tests {
// GAME OBJECTS AND VARIABLES
// The following is used for reading, displaying, and writing to the game board.
static File board = new File("Board.txt");
static FileWriter boardWriter = null;
static StringBuilder boardBuilder = new StringBuilder((int)board.length());
static String boardDisplay = null; // This String allows boardContents to print in a more readable way.
static String boardContents = null; // This is Board.txt represented as a String.
// There are more variables here than shown, but these are the ones relevant to my problem.
// GAMEPLAY
public static void main(String[] args) throws IOException {
boolean gameIsOngoing = true;
while(gameIsOngoing) {
// boardContents String from boardBuilder StringBuilder
try (Scanner boardReader = new Scanner(board)) {
while (boardReader.hasNextLine()) {
boardContents = (boardBuilder.append(boardReader.nextLine() + System.lineSeparator()).toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// More irrelevant code here.
}
}
}
Which works, but it makes my code feel less readable, as the Scanner object is no longer listed with all of the other objects. I guess my question is, why didn't the first code work? Is it possible for something resembling it more to work?
I also want to mention quick that in researching for this question, I saw some things saying it is generally bad practice to have Scanner objects be global/static. I figured that because this particular Scanner isn't gathering user input (and me having no plans on maintaining this relatively simple project post-completion), it wouldn't be too problematic.
Edit: I don't know why but the editor isn't letting me put a "Hello" at the beginning of this post, so here it is... hello everyone :)
There is error because the exception is not caught. The Scanner instance is created in context of the Tests class, main method is something different, therefore catching it there won't solve the issue.
If you want a work-around, you can try something like this:
static {
try {
boardReader = new Scanner(board);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
So I have looked at numerous posts on classes, references and methods, set and get for a couple days now. I can't seem to comprehend how it all works.
Disclaimer yes this is for classwork, the poor example below is an attempt to illustrate. I would appreciate your help.
I already have a working (albeit very rudimentary and inefficient program). However everything I have is in my main method of my Primary class and I need to put part of it in a separate class and have it all still work.
With the main method the user inputs a clear text password (clearText) wherein a provided snippet of code hashes the password into (hashText). Which is then used for other things.
What I wish to accomplish is to separate the snippet of code that hashes the password out of the main method of my primary class, into a separate secondary class.
What I cannot figure out is how to do that. How to import clearText into secondary class, then output hashText back to the main method in the primary class.
Thank you.
import java.util.*;
import java.io.*;
public class Primary {
public static void main(String[] args) throws Exception {
String clearText = ("");
System.out.print("Type Text");
clearText = scnr.next();
//Somehow export clearText to the secondary class
//Somehow import hashText into the main method for further use
System.out.println(hashText);
}
}
public class Secondary {
String hashText = ("");
//Somehow import clearText value inputted but the user
//here is where clearText gets hashed(I have that)
//Somehow export hashText for use in the main method
}
Welcome to programming. One thing to think about here is it seems that you think your Secondary class is an entity that is immutable and runs alongside your program. It isn't. You're creating an object that contains data and functionality that you want to use elsewhere in your program.
Your Secondary object can be instantiated and then used to perform tasks. You could also do this from another method created inside of your base class, but that would have to be static as well.
I don't see much point in your secondary class containing an instance of the hash, and that question has been answered already. I would suggest you think about creating it as a service.
import java.util.*;
import java.io.*;
public class Primary {
public static void main(String[] args) throws Exception {
String clearText = ("");
// Collect user input
System.out.print("Type Text");
clearText = scnr.next();
// Create hash and display
String hashText = HashService.generateHash(clearText);
System.out.println(hashText);
}
}
public class HashService {
public static String generateHash(String fromText){
// implementation here
return null;
}
}
Edit: It looks like someone erased the object answer. If you for some reason want to maintain your hashed password as an object you could do it like this
import java.util.*;
import java.io.*;
public class Primary {
public static void main(String[] args) throws Exception {
String clearText = ("");
// Collect user input
System.out.print("Type Text");
clearText = scnr.next();
// Create hash and display
HashedPassword hash = new HashedPassword(clearText);
String hashText = hash.getHashedPW();
System.out.println(hashText);
}
}
public class HashedPassword {
private String hashedPW = ""
public HashedPassword(String fromText){
// Assign hashedPW with some logic
hashedPW = fromText;
}
public getHashedPW(){
return hashedPW;
}
}
Simple create a method in second class which accepts your cleartext and returns the hash value and then call this method on the second class's object from the main method
public static void main(String[] args) throws Exception {
String clearText = ("");
System.out.print("Type Text");
clearText = scnr.next();
// Somehow export clearText to the secondary class
// Somehow import hashText into the main method for further use
System.out.println(Secondary.stringToHash(clearText));
}
publicclass Secondary {
public static long stringToHash(String input) {
// some transformation
}
// Somehow import clearText value inputted but the user
// here is where clearText gets hashed(I have that)
// Somehow export hashText for use in the main method
}
This should work, but you don't really need another class, you can just create a static method.
You can do the following:
import java.util.*;
import java.io.*;
public class Primary {
public static void main(String[] args) throws Exception {
String clearText = ("");
System.out.print("Type Text");
clearText = scnr.next();
String hashText = Secondary.hashText(clearText);
System.out.println(hashText);
}
}
public class Secondary {
public static String hashText(String clearText) {
// TODO return the hash
return null;
}
}
Or if you have some non-static thing in your secondary class, then you can make an instance of it (by Secondary secondary = new Secondary()) and then call secondary.hashText() (also make hashText non-static) :)
So, if you need two separate classes keep in mind that each class has to be in separate files. YOu need to import the second class in the first one like this:
import YourPackageName.YourClassName;
then in the main class you can do like this:
public class Primary {
public static void main(String[] args) throws Exception {
String clearText = ("");
System.out.print("Type Text");
clearText = scnr.next();
Secondary secondClass = new Secondary();
String hashText = secondClass.hash(clearText);
System.out.println(hashText);
}
}
Meanwhile in Secondary calss:
public class Secondary {
public String hash (String clearText){
//doHash
}
}
This question already has answers here:
Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args) [duplicate]
(5 answers)
Closed 8 years ago.
Error: Main method not found in class MovieDatabase, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
import java.io.FileInputStream;
import java.util.Scanner;
import java.util.Arrays;
public class MovieDatabase {
private int[] analysis;
//creating the contructor
public MovieDatabase(String file){
analysis = new int[2015];
this.load(file);
}
//uses the load(String file) method from downstairs to do all of the work
public void load(String file){
Scanner theScanner = null;
try{
//inputing the into the scanner
theScanner = new Scanner(new FileInputStream(file));
}
catch(Exception ex){
ex.printStackTrace();
}
// as long as the scanner has another line
while(theScanner.hasNextLine())
{
String Line = theScanner.nextLine();
//make an array called split and allocated different elements based on a seperation of ##
String split[] = Line.split("##");
int year = Integer.valueOf(split[1]);
analysis[year] ++;
}
}
//print out the array in the synchronous format
public void print(){
System.out.printf("%1$-30s %2$10s %3$10s %4$10s ", "Year", "Occurances", "", "");
//go through the array
for (int i =0;i < analysis.length ;i++ ) {
if(analysis[i] >0){
for (int j =i;j < analysis.length ;i++ ){
System.out.printf("%1$-30s %2$10s %3$10s %4$10s ", j, analysis[j], "", "");
}
}
}
}
}
How do I fix this error message?
Ive read other similar questions but just say to make the classes public. Mine are public.
main() method in Java is an standard method which is used by JVM to start execution of any Java program. main method is referred as entry point of Java application which is true in case of core java application
You have missed it. Add following main() method
public static void main(String[] args) {
MovieDatabase db = new MovieDatabase("file/path/goes/here");
db.print();
}
In the Java programming language, every application must contain a
main method whose signature is:
public static void main(String[] args)
As the error suggests, if its non FX project, just define something like:
public static void main(String args[]) {
...
}
Or else change you class definition so it extends Application, something like:
public class MovieDatabase extends Application
To invoke any application JVM need main() method, and which should have following access specifiers and modifiers,
public static void main(String args[])
public - It should be accessible to all
static - JVM not able to create instance of your class so method should be static
void - method not returning anything
For each java application main method is entry point, so your application should have atleast one main method to start execution of application.
It's because you have forgot to add the main method. The error clearly says:
please define the main method as: public static void main(String[]
args)
So add the main:
public static void main(String[] args) {
MovieDatabase m = new MovieDatabase("Your File Path");
m.print();
}
public class QuestionBank {
public static void main(String[] args) {
int k = 0;
String Bank[][] = {{"The sun is hot.","A. True","B. Flase","A"},
{"Cats can fly.","A. True","B. False","B"}};
}
}
Above is my QuestionBank class that creates a 2X4 string array. First column being the question, 2nd and 3rd being the answer choices, and 4th being the correct answer.
Below is my RealDeal class.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class RealDeal {
public static void main(String[] args) {
input = JOptionPane.showInputDialog(Bank[0][0]\nBank[0][1]\nBank[0][2]);
if (input == Bank[0][3]) {
input = 10;
} else {
input = 0;
}
total = input/1;
JOptionPane.showMessageDialog(null,"You scored a " + total + " out of 10. Great job!");
System.exit(0);
}
}
What I'm trying to do is to get Bank[0][0], Bank[0][1], and Bank[0][2] to output on my RealDeal class and then to check whether Bank[0][3] matches with the users input. Can anyone please help me with this. Im really new to java so if anyone could actually draw out the answer and explain it to me that would be great.
I think the best way is reading a good Java book and become familiar with the language itself and then try to solve this by your own. If you then have a real question there is no problem asking it here again. But your code is... not really working at all.
I don't think this portal is a "please do my work for me" portal.
To call anything from another class you will need to either setup a method for a return or make the variables public.
So:
public class Class1
{
// for method 1
public String s1 = "This is a string"
// for method 2
public Class1 {}
public returnString()
{
return s1;
}
}
public class CLASS2
{
public static void main(String args[])
{
// get the class
cls1 = new Class1();
// retrieving - method 1
String str = cls1.s1;
// retrieving - method2
str = cls1.returnString();
}
}
How can I count my messages? I have both classes in the same folder and I compile them in the terminal. I don't want to install an IDE and create a package.
My counting class:
import java.util.ArrayList;
public class countMessages{
public static void main(String args[]){
int count = messages.size();
}
}
My message containing class:
import java.util.ArrayList;
public class SampleDataBase {
public static ArrayList<String> messages;
static {
messages = new ArrayList<String>(12);
messages.add("A "+"message "+"with "+"pineapples.");
messages.add("A "+"message "+"with "+"grapes.");
messages.add("A "+"message "+"with "+"watermelons.");
}
}
To create a package just create a folder (name it for example myPackage) and put both classes in it. Also include a first line in both class files: package myPackage;. Remember to name the class files with the names of the classes.
To make your example work just change messages.size(); to SampleDataBase.messages.size();.
And you really should name the class CountMessages with a capital letter.
It's unclear what you are trying to do but what I think you are looking for is a main static method(?)
import java.util.ArrayList;
public class SampleDataBase
{
public static void main(String[] args)
{
ArrayList<String> messages = new ArrayList<>();
messages.Add("things...");
for(String message : messages)
{
System.out.println(message);
}
System.out.println("The number of messages is : " + messages.size());
}
}
in the terminal, to use:
Compile javac *.java
Execute java SampleDataBase
If you want to keep two classes, use this on your test class(that contains main method).
public class countMessages{
public static void main(String args[]){
// You must instantiate the other class
SampleDataBase sdb = new SampleDataBase();
// here you will get the total messages in your arrayList
int count = sdb.messages.size();
}