Going back to main class - java

Here I have my terminal project, and inside the terminal, I can type "create", which will take me to the create prompt, where I can create a program. My problem right now is the fact that I can't get back to the Main class (Where I can select a command to run). I had the idea of trying to use the System.exit(0); but, as I didn't realise, it just kills the entire program. If anyone is able to help me, my file is below. I can post any other files if requested.
import java.util.*;
import java.io.*;
public class commandCreate {
boolean _active = true;
String _username = System.getProperty("user.name").toLowerCase();
String _os = System.getProperty("os.name").trim().toLowerCase();
String fileName, create, option;
public commandCreate() {
try {
while(_active) {
System.out.print(_username + "#" + _os + ":~/create$ ");
Scanner kbd = new Scanner(System.in);
String userLine = kbd.nextLine();
if(java.util.regex.Pattern.matches(".*\\S\\s+\\S.*", userLine)) {
Scanner read = new Scanner(userLine);
option = read.next();
fileName = read.next();
}
FileWriter create = new FileWriter(new File("Created Files/" + fileName + ".java"));
if(userLine.equals(option + " " + fileName)) {
if(option.equals("-a")) {
// Option = -a, creates standard file with main class.
create.write("public class " + fileName + " {\n");
create.write(" public static void main(String[] args) {\n");
create.write(" System.out.println(\"Welcome to your new program!\");\n");
create.write(" }\n");
create.write("}");
} else if(option.equals("-c")) {
// Option = -c , creates standard file with overloaded constructor & main class.
create.write("public class " + fileName + " {\n");
create.write(" public " + fileName + "() {\n");
create.write(" System.out.println(\"Welcome to your new program!\");\n");
create.write(" }\n");
create.write("\n");
create.write(" public static void main(String[] args) {\n");
create.write(" new " + fileName + "();\n");
create.write(" }\n");
create.write("}");
} else if(option.equals("-j")) {
// Option = -j, creates GUI within constructor w/ single JLabel.
create.write("import javax.swing.*;\n");
create.write("import java.awt.*;\n");
create.write("import java.awt.event.*;\n");
create.write("\n");
create.write("public class " + fileName + " extends JFrame {\n");
create.write(" private static final int HEIGHT = 50;\n");
create.write(" private static final int WIDTH = 400;\n");
create.write("\n");
create.write(" private JLabel welcomeJ;\n");
create.write("\n");
create.write(" public " + fileName + "() {\n");
create.write(" super(\"Welcome to your program - " + fileName + "\");\n");
create.write(" Container pane = getContentPane();\n");
create.write(" setLayout(new FlowLayout());\n");
create.write("\n");
create.write(" welcomeJ = new JLabel(\"Welcome To Your Program!\", SwingConstants.CENTER);\n");
create.write("\n");
create.write(" pane.add(welcomeJ);\n");
create.write("\n");
create.write(" setSize(WIDTH, HEIGHT);\n");
create.write(" setVisible(true);\n");
create.write(" setResizable(false);\n");
create.write(" setDefaultCloseOperation(EXIT_ON_CLOSE);\n");
create.write(" }\n");
create.write("\n");
create.write(" public static void main(String[] args) {\n");
create.write(" new " + fileName + "();\n");
create.write(" }\n");
create.write("}");
}
} else if(userLine.equalsIgnoreCase("help")) {
System.out.println("Commands");
System.out.println(" Syntax: [-option] [filename]");
System.out.println(" -a [filename] [Program: main class]");
System.out.println(" -c [filename] [Program: overloaded constructor, main class]");
System.out.println(" -j [filename] [Program: GUI: overloaded constructor, main class]");
} else if(userLine.equalsIgnoreCase("exit")) {
System.exit(0);
} else {
System.out.println("Error in syntax. Please review the \"help\" menu");
}
create.close();
}
} catch(IOException e) {
System.out.println("There was an error: " + e);
} catch(InputMismatchException ex) {
System.out.println("There was an error: " + ex);
}
}
public static void main(String[] args) {
new commandCreate();
}
}

The simple answer is to get the commandCreate constructor to return, or throw / propagate an exception. Indeed, I think this will happen already if the user enters an EOF.
(There are numerous other things wrong with your code, but it is probably better if you figure that out for yourself. I will point out however, that "commandCreate" or "CommandCreate" is a really poor choice for a class name. A class name is typically a noun.)

Your problem seems to be that you are stuck in an infinite while loop, there is no condition that sets the value _active to false.
} else if(userLine.equalsIgnoreCase("exit")) {
System.exit(0);
} else {
with
} else if(userLine.equalsIgnoreCase("exit")) {
_active = false;
} else {
That pretty much solves the problem of not being able exit. A return; statement would work equally well. I think Exceptions would be overkill in this particular instance.
On a side note (and something that most people seem to have pointed out), I would put the code in it's own method, run() for instance, and then use the call new commandCreate().run() in your main method.

Related

JavaFX retrieve TextView value outside Controller

Edit: For any future person reading this, you need to add parameters to the method I have shown in the post.
Instead of doing + textview +, you do +with parameter+ and then in the controller, you make integers/strings for the parameters and set them = to textview.getText(), then you put those integers/strings inside the method parameters of the method you are getting from the instance in the controller class.
Original Post
How do I get the value from a TextView in a method in another class outside the Controller class?
I cannot use textview.getText(); outside the Controller class or it will just give me NullPointerException.
Here is my method from my other class:
Controller c;
public void createRecipes() throws SQLException {
openDB();
if (connectionDB != null) {
Statement st = this.connectionDB.createStatement();
String insert = "INSERT INTO recipes "
+ " (ID, name, temperature, fan, redlight, bluelight, addwater) " + " VALUES "
+ " ( " + c.createID.getText() + ", " + c.createName.getText() + ", " +c. createTemperature.getText() + ", " + c.createFan.getText() + ", " + c.createRedLight.getText() + ", " + c.createBlueLight.getText() + ", " + c.createWaterLevel.getText() + " ) ;";
st.executeUpdate(insert);
} else {
System.out.println("No connection established to the database.");
}
closeDB();
}
This is the textfield I am getting from my controller class:
c.createBlueLight.getText()
You shouldn't use fx components outside of you controller! You should always separate logic and ui. So just pass the text content to the method.
This is an example of the right way to access controllers that are generated by parsing FXML files from FXMLLoader
public class Controller {
#FXML
private TextField textField;
public TextField getTextField() {
return textField;
}
public String getTextFieldValue() {
return textField.getText();
}
}
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
So the controller is initialized correctly (the textField field is not null) and we can use it without problem, for example
TextField textField = controller.getTextField();
or
String value = controller.getTextFieldValue();

How do I make a list of new elements?

I want to make a list of elements create with user input. Can I directly store an element into a list, or do I have to create a reference? I found how to make a list of premade variables, but I want to create te variables with user input.
The goal of my project is to store dataset and recall them at a later moment.
First I understand the concept of lists. Therefore I don't think its useful to copy my code at this moment.
import java.util.*;
public class Database {
public Database () {
}
public static int numberOfSpawnpoints = 0;
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Add a new spawnpoint.\n");
System.out.println("State the name of this spawnpoint: ");
Spawnpoints Sp1 = new Spawnpoints(getSpawnName());
System.out.println("Name: " + Sp1.getSpawnName());
System.out.println("Location: " + Sp1.getLocation());
System.out.println("Pokemon: " + Sp1.getPokemon());
System.out.println("Spawntime: " + Sp1.getSpawntime());
System.out.println("The pokemon is currently spawned: " + Sp1.isSpawned());
numberOfSpawnpoints++;
}
public static String spawnName;
public static String getSpawnName() {
spawnName = userInput.next();
return spawnName;
}
public void setSpawnName(String spawnName) {
Database.spawnName = spawnName;
}
}
Hope this helps
import java.util.*;
public class Database {
public Database () {
}
public static int numberOfSpawnpoints = 0;
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Add a new spawnpoint.\n");
System.out.println("State the name of this spawnpoint: ");
ArrayList<Spawnpoints> SPlist = new ArrayList<Spawnpoints>();
SPlist.add(new Spawnpoints(getSpawnName()));
// the above line will create an object of Spawnpoints and store it in list
System.out.println("Name: " + SPlist.get[0].getSpawnName());
System.out.println("Location: " + SPlist.get[0].getLocation());
System.out.println("Pokemon: " + SPlist.get[0].getPokemon());
System.out.println("Spawntime: " + SPlist.get[0].getSpawntime());
System.out.println("The pokemon is currently spawned: " + SPlist.get[0].isSpawned());
numberOfSpawnpoints++;
}
public static String spawnName;
public static String getSpawnName() {
spawnName = userInput.next();
return spawnName;
}
public void setSpawnName(String spawnName) {
Database.spawnName = spawnName;
}
}
You can try adding this code:
ArrayList<String> items = new ArrayList<String>();
while (!userInput.equals("exit")){
items.add(userInput.next());
}

Config questions

I would like to know how to send a player a list of their shops when they type /shoplist. Also, I would like to know how to change the name of a shop depending on what they type so if they use /shopname Shop1 Pie it would change the name of Shop1 to pie. Or if they do not have a shop called shop1 then it would say a message if they don't have any shops when they make a shop then it builds a new section in the config for them.
Here is my main file:
public class Shops extends JavaPlugin implements Listener {
public void onEnable() {
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getLogger().info("*Shops Plugin Enabled *");
Bukkit.getServer().getLogger().info("*Shops by McMatt *");
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getPluginManager().registerEvents(new Signs(), this);
getConfig().options().copyDefaults(true);
saveConfig();
}
public void onDisable() {
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getLogger().info("*Shops Plugin Disabled *");
Bukkit.getServer().getLogger().info("*Shops by McMatt *");
Bukkit.getServer().getLogger().info("************************");
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("shops")) {
if (!(sender instanceof Player)) {
sender.sendMessage("You must be a player to run this command");
return true;
}
Player player = (Player) sender;
if (!player.hasPermission("shops.shops")) {
player.sendMessage(ChatColor.RED + "You do not have to permission (shops.shops)");
return true;
} else {
player.sendMessage(ChatColor.GOLD + "Shops:");
player.sendMessage(ChatColor.RED + "---" + ChatColor.GOLD + "Commands" + ChatColor.RED + "---");
player.sendMessage(ChatColor.DARK_GREEN + "/shops" + ChatColor.GREEN + " Displays this");
player.sendMessage(ChatColor.DARK_GREEN + "/shopslist" + ChatColor.GREEN + " Used to list shops");
player.sendMessage(ChatColor.RED + "---" + ChatColor.GOLD + "Signs" + "---");
player.sendMessage(ChatColor.DARK_GREEN + "First line:" + ChatColor.GREEN + " [shop]");
player.sendMessage(ChatColor.DARK_GREEN + "Second line:" + ChatColor.GREEN + " {Open or Closed}");
}
}
return true;
}
public boolean onCommand1(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("shopslist")) {
sender.sendMessage("Getting shops info!");
sender.sendMessage(getConfig().getString("" + sender.getName()));
return true;
}
return false;
}
}
Here's my listener file
public class Signs implements Listener {
#EventHandler
public void onSignChange(SignChangeEvent e) {
if (e.getLine(0).equalsIgnoreCase("[shop]")) {
Block attached = e.getBlock().getRelative(0, -1, 0);
String name = e.getPlayer().getDisplayName();
if (!(attached.getType() == Material.CHEST))
e.getPlayer().sendMessage(ChatColor.RED + "Please place the shop on a chest!");
else {
if (!e.getPlayer().hasPermission("shops.create"))
e.getPlayer().sendMessage(ChatColor.RED + "You don't have permission to create a shop! (shops.create)");
else {
if (!Arrays.asList("open", "closed").contains(e.getLine(1).toLowerCase())) {
e.getPlayer().sendMessage(ChatColor.RED + "You must specify if the shop is open or closed on the second line!");
} else {
boolean closed = true;
if ("open".equalsIgnoreCase(e.getLine(1))) {
closed = false;
}
String lineThree = closed ? "§cClosed" : "§aOpen";
e.setLine(3, lineThree);
e.setLine(0, "§9[Shop]");
e.setLine(1, "§b" + name + "'s");
e.setLine(2, "§bShop");
e.getPlayer().sendMessage(ChatColor.GREEN + "Shop Created!");
e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.LEVEL_UP, 10, 10);
//if(getConfig().equals(null)){
//int shopAmount = 0;
//shopAmount = shopAmount + 1;
//getConfig().createSection(name);
//getConfig().addDefault(name + ":.Shops:", "Shop" + shopAmount);
}
}
}
}
}
#EventHandler
public void onPlayerInteract(PlayerInteractEvent e) {
if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Player p = e.getPlayer();
Block b = e.getClickedBlock();
Material m = b.getType();
if (!(m == Material.SIGN_POST)) {
return;
} else {
Sign sign = (Sign) e.getClickedBlock().getState();
if ((sign.getLine(0).equalsIgnoreCase("§9[Shop]"))) {
if ((sign.getLine(3).equalsIgnoreCase("§aOpen"))) {
p.sendMessage("I opened the shop!");
}
}
}
}
}
}
And here's my configuration file
McMatt:
- Shop1
You could get the List<String> of all of the player's shops by using
config.getStringList(playerName);
So, for example, if your config looked like this:
McMatt:
- "Shop1"
- "Awesome Shop"
jojodmo:
- "Jojo Shop"
using
config.getStringList("McMatt");
Would return a List<String> containing the strings Shop1 and Awesome Shop.
Also, to avoid a NullPointerException, you should make sure the player has shops in the config by using
if(config.contains(playerName))
and send the player a message telling them that they have no shops.
So, your code could look something like this:
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
if(cmd.getName().equalsIgnoreCase("shops")){
//your code
if(sender instanceof Player){
Player player = (Player) sender;
String name = player.getName();
if(config.contains(name)){
List<String> shops = config.getStringList(name);
for(String shop : shops){
//do something with the shop
}
}
else{
//the user has no shops
}
}
//...
}
}

java tagmaker program (clear scanner and tester class)

instructions:
write a class called TagMaker that prints out tags. supply methods to (a) set the name (b) set the organization (c) print tag with the name and organization (d) clear the name and organization (e) print a blank tag. then write a TagTester class to test the TagMaker class.
so i got the code to accept the user input and print out a tag...but i did it without a tester class (i'm scared of those, and it wasn't working when i tried using one. any suggestions there?) and i've tried experimenting with codes that would clear the scanner to print out a blank tag also but it kept messing up the program so i took it out.
this is what i have so far:
import java.util.Scanner;
//import java.util.Locale;
//import java.io.*;
public class TagMaker {
public static void main (String[] args)
{
Scanner scannerObject = new Scanner( System.in );
System.out.print("This program will print out a name tag");
System.out.println("for each delegate.");
System.out.println("Please enter first name:");
String first = scannerObject.next();
System.out.println("Please enter last name:");
String last = scannerObject.next();
System.out.println("Please enter organization or affilation:");
String org = scannerObject.next();
System.out.println("###### " + "Annual Conference" + " ######");
System.out.println("### NAME: " + first + " " + last + " ###");
System.out.println("################################");
System.out.println("### ORGANIZATION:" + org + "###");
System.out.println("###############################");
String junk = scannerObject.next();
}
}
public class TagMaker {
private String tagName;
private String organization;
public void setTagName(String tagName){
this.tagName = tagName;
}
public void setOrganization(String organization){
this.organization = organization;
}
public void clearTagName(){
this.tagName = "";
}
public void clearOrganization(){
this.organization = "";
}
#Override
public String toString() {
return "Tag [Name=" + tagName + "\n Organization="
+ organization + "]";
}
}
class TagTester{
public static void main(String args[]){
TagMaker customTag = new TagMaker(); //Creates a new tag
customTag.setTagName("Custom Name"); //Sets tag name to Custom Name
customTag.setOrganization("Custom Organization"); //Sets tag organization to Custom organization
customTag.clearTagName(); //Clears tag name
customTag.clearOrganization(); //Clears organization
System.out.println(customTag); //Prints tag name and organization
}
}

Why am I getting this exception?

i'm running my program, and trying to launch the "help" menu from the program being run from that program (if that makes any sense!). But I'm getting a "NoSuchElement" exception, one that isn't even called in my try {} catch(), in either program!
What I'm doing is;
Running the program. Typing "create" to launch the commandCreate class. I then type in "help" to launch the help menu. But I get the NoSuchElement exception. If anyone is able to help me with this, my two programs are below. Thank you.
main.java
// main.java
import java.io.*;
public class Main extends API {
boolean _active = true;
String _username = System.getProperty("user.name").toLowerCase();
String _os = System.getProperty("os.name").trim().toLowerCase();
public Main() {
try {
while(_active) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
print(_username + "#" + _os + ":~$ ");
String command = br.readLine();
if(command.equalsIgnoreCase("create")) {
new commandCreate();
/*} else if(command.equals("compile")) {
new commandCompile();*/
} else if(command.equalsIgnoreCase("help")) {
println("Commands");
println(" create - Creates .java files, does not compile.");
//println(" compile - Creates .java files, compiles on creation.");
println(" exit - Exits program");
println(" help - Shows help documentation.");
} else if(command.equalsIgnoreCase("exit")) {
print("Are you sure you want to exit? (Y/N) ");
String exit = br.readLine();
if(exit.equalsIgnoreCase("y")) {
exit();
} else {
println("Cancelled!");
}
} else if(command.isEmpty()) {
} else {
println("\"" + command + "\" does not exist. Please review the \"help\" menu");
}
}
} catch(Exception ex) {
println("There was a problem: " + ex);
}
}
public static void main(String[] args) {
new Main();
}
}
commandCreate.java
// commandCreate.java
import java.util.*;
import java.io.*;
public class commandCreate {
boolean _active = true;
String _username = System.getProperty("user.name").toLowerCase();
String _os = System.getProperty("os.name").trim().toLowerCase();
String fileName, create, option;
public commandCreate() {
try {
System.out.print(_username + "#" + _os + ":~/create$ ");
Scanner kbd = new Scanner(System.in);
String userLine = kbd.nextLine();
Scanner read = new Scanner(userLine);
option = read.next();
fileName = read.next();
FileWriter create = new FileWriter(new File("Created Files/" + fileName + ".java"));
if(userLine.equals(option + " " + fileName)) {
if(option.equals("-a")) {
// Option = -a, creates standard file with main class.
create.write("public class " + fileName + " {\n");
create.write(" public static void main(String[] args) {\n");
create.write(" System.out.println(\"Welcome to your new program!\");\n");
create.write(" }\n");
create.write("}");
} else if(option.equals("-c")) {
// Option = -c , creates standard file with overloaded constructor & main class.
create.write("public class " + fileName + " {\n");
create.write(" public " + fileName + "() {\n");
create.write(" System.out.println(\"Welcome to your new program!\");\n");
create.write(" }\n");
create.write("\n");
create.write(" public static void main(String[] args) {\n");
create.write(" new " + fileName + "();\n");
create.write(" }\n");
create.write("}");
} else if(option.equals("-j")) {
// Option = -j, creates GUI within constructor w/ single JLabel.
create.write("import javax.swing.*;\n");
create.write("import java.awt.*;\n");
create.write("import java.awt.event.*;\n");
create.write("\n");
create.write("public class " + fileName + " extends JFrame {\n");
create.write(" private static final int HEIGHT = 50;\n");
create.write(" private static final int WIDTH = 400;\n");
create.write("\n");
create.write(" private JLabel welcomeJ;\n");
create.write("\n");
create.write(" public " + fileName + "() {\n");
create.write(" super(\"Welcome to your program - " + fileName + "\");\n");
create.write(" Container pane = getContentPane();\n");
create.write(" setLayout(new FlowLayout());\n");
create.write("\n");
create.write(" welcomeJ = new JLabel(\"Welcome To Your Program!\", SwingConstants.CENTER);\n");
create.write("\n");
create.write(" pane.add(welcomeJ);\n");
create.write("\n");
create.write(" setSize(WIDTH, HEIGHT);\n");
create.write(" setVisible(true);\n");
create.write(" setResizable(false);\n");
create.write(" setDefaultCloseOperation(EXIT_ON_CLOSE);\n");
create.write(" }\n");
create.write("\n");
create.write(" public static void main(String[] args) {\n");
create.write(" new " + fileName + "();\n");
create.write(" }\n");
create.write("}");
}
} else if(userLine.equalsIgnoreCase("help")) {
System.out.println("Commands");
System.out.println(" Syntax: [-option] [filename]");
System.out.println(" -a [filename] [Program: main class]");
System.out.println(" -c [filename] [Program: overloaded constructor, main class]");
System.out.println(" -j [filename] [Program: GUI: overloaded constructor, main class]");
} else {
System.out.println("Error in syntax. Please review the \"help\" menu");
}
create.close();
} catch(IOException e) {
System.out.println("There was an error: " + e);
} catch(InputMismatchException ex) {
System.out.println("There was an error: " + ex);
}
}
public static void main(String[] args) {
new commandCreate();
}
}
According to your stack-trace, the problem is here:
Scanner kbd = new Scanner(System.in);
String userLine = kbd.nextLine();
Scanner read = new Scanner(userLine);
option = read.next();
fileName = read.next(); // <--- exception here
What this bit of code does is this:
it reads a line from standard-input, and saves it in userLine.
it reads two whitespace-delimited tokens from userLine, and saves them as option and filename.
So the problem is that the line from standard-input doesn't actually have two whitespace-delimited tokens. It needs to look something like -j file.txt, but instead maybe it just looks like -j, or like file.txt.
You could have a problem in the superclass named API. Look there.

Categories