Why am I getting this exception? - java

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.

Related

Println method doesn't work on second run

So my Kiir method doesn't work since my last run. The program should write the new values to a .txt file, and give it back the whole text with the new value included.
The program says the issue is in the
public static void Kiir(ArrayList<Versenyzo>versenyzok){
for (Versenyzo f : versenyzok){
System.out.println(f.toString());
}
but I can't see the problem. Any idea?
public class VizsgaMintaA {
static SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
static Scanner sc= new Scanner(System.in);
/**
* #param args the command line arguments
* #throws java.text.ParseException
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws ParseException, FileNotFoundException {
ArrayList<Versenyzo> versenyzok = new ArrayList<>();
Feltolt(versenyzok);
Kiir(versenyzok);
Ujversenyzo(versenyzok);
Kiir(versenyzok);
Fajlbair(versenyzok);
}
private static void Feltolt(ArrayList<Versenyzo> versenyzok) throws ParseException{
Versenyzo v = null;
File f = new File("versenyzok.txt");
try {
Scanner scan = new Scanner(f, "iso-8859-2");
while (scan.hasNextLine()) {
String sor = scan.nextLine();
String[] adatok = sor.split(";");
if (adatok.length == 3) {
v = new Versenyzo();
v.nev = adatok[0];
v.szuletes = df.parse(adatok[1]);
v.csapat = adatok[2];
} else if (adatok.length > 3) {
v = new Versenyzo (adatok[0],df.parse(adatok[1]),adatok[2]
,Integer.parseInt(adatok[3])
);
}
versenyzok.add(v);
}
} catch (FileNotFoundException ex) {
System.out.println("Nincs meg a fájl.");
}
}
public static void Kiir(ArrayList<Versenyzo>versenyzok){
for (Versenyzo f : versenyzok){
System.out.println(f.toString());
}
}
private static void Ujversenyzo(ArrayList<Versenyzo>versenyzok)throws ParseException{
Versenyzo v = new Versenyzo();
System.out.println("Adjon meg egy nevet:");
v.nev=sc.nextLine();
System.out.println("Adja meg a születési idejét:");
v.szuletes=df.parse(sc.nextLine());
System.out.println("Adja meg a csapatot:");
v.csapat = sc.nextLine();
System.out.println("Adja meg a vb címek számát:");
v.vbcim = sc.nextInt();
versenyzok.add(v);
}
public static void Fajlbair(ArrayList<Versenyzo>versenyzok) throws FileNotFoundException {
PrintStream f2 = new PrintStream(new File ("versenyzok2.txt"));
for (Versenyzo v : versenyzok){
f2.println(v.toString());
}
}
}
class Versenyzo {
String nev,csapat;
Date szuletes;
int vbcim;
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
#Override
public String toString(){
return "Versenyzo:" +nev + " Született:" + df.format(szuletes)+" Csapata:"+ csapat + " Vb címek:" + vbcim;
}
public Versenyzo(String nev, Date szuletes, String csapat, int vbcim) {
this.nev = nev;
this.szuletes = szuletes;
this.csapat = csapat;
this.vbcim = vbcim;
}
public Versenyzo(){
}
}
First check if the list passed to Kiir() is null:
public static void Kiir(ArrayList<Versenyzo> versenyzok){
if (versenyzok == null)
return;
for (Versenyzo f : versenyzok){
System.out.println(f);
}
}
I did make another change to Kiir().
I removed toString() from f.toString(), since you have overridden it, it is redundant.
Now the only problem with your implementation of the toString() method inside the Versenyzo class is if there exist null values in the szuletes property.
If this is the case then change to this:
#Override
public String toString(){
return "Versenyzo:" + nev + " Született:" + (szuletes == null ? "null" : df.format(szuletes)) + " Csapata:" + csapat + " Vb címek:" + vbcim;
}

Multithread PDF manipulation

I'm writing a java program whose operation is summarized as follows:
The subfolder with the specified name is selected in the source
folder.
All the pdfs are taken and converted into txt files in
the target folder.
The name of an item is searched inside the
txt.
If the name is found then the pdf from source to target is
copied.
All the txt from the target folder are deleted, in this
way all the pdfs containing the searched word remain.
"It all works", the problem is that the txt files are not deleted from target and I can not understand why. Thanks in advance, best regards.
Launcher.java:
import java.lang.String;
import java.util.Scanner;
import java.io.File;
public class Launcher {
// campi
int status = 1;
static String source = "C:\\Users\\MyUser\\Desktop\\source\\";
static String target = "C:\\Users\\MyUser\\Desktop\\target\\";
public static void main(String [] args) {
// strings
String src = source;
String item = "";
// init
Scanner scan = new Scanner(System.in);
System.out.print("\nFornitore: ");
src += scan.nextLine().toUpperCase() + "\\";
System.out.print("Item: ");
item = scan.nextLine();
// notifier
Launcher launcher = new Launcher();
// threads
MakerThread maker = new MakerThread(launcher, src, target);
SearcherThread searcher = new SearcherThread(launcher, src, target, item);
CleanupThread cleaner = new CleanupThread(launcher, target);
// run
maker.start();
searcher.start();
cleaner.start();
}
}
MakerThread.java:
import java.io.File;
public class MakerThread extends Thread {
// campi
String src = "";
String target = "";
Launcher launcher;
// costruttore
public MakerThread(Launcher launcher, String src, String target) {
this.src = src;
this.target = target;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.src);
for (File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 1){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("pdf")) {
System.out.println("PDF TROVATO: " + f.getName());
// input
String input = win_str(src + f.getName());
// output
String output = target;
output += f.getName().replaceAll(".pdf", ".txt");
output = win_str(output);
// command
String command = "cmd /C java -jar ./pdfbox-app-2.0.11.jar ExtractText ";
command += input + " " + output;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
}
}
// set status, awake other threads
launcher.status = 2;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}
SearcherThread.java:
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
public class SearcherThread extends Thread {
// campi
String src = "";
String target = "";
String item = "";
Launcher launcher;
// costruttore
public SearcherThread(Launcher launcher, String src, String target, String item) {
this.target = target;
this.src = src;
this.item = item;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.target);
for(File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 2){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("txt")) {
System.out.println("SEARCHING IN: " + f.getName());
// init
String line;
BufferedReader br = new BufferedReader(new FileReader(new File(target+f.getName())));
// txt search
while((line = br.readLine()) != null) {
if(line.contains(item)) {
System.out.println(" [" + item + "]" + " trovato in " + f.getName() + "\n");
// input
String pdf = f.getName().replaceAll(".txt", ".pdf");
String input = win_str(src+pdf);
// output
String output = win_str(target);
// command
String command = "cmd /C copy " + input + " " + output;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
break;
}
}
}
}
// set status, awake other threads
launcher.status = 3;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}
CleanupThread.java:
import java.io.File;
public class CleanupThread extends Thread {
// campi
String target = "";
Launcher launcher;
// costruttore
public CleanupThread(Launcher launcher, String target) {
this.target = target;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.target);
for (File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 3){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("txt")) {
System.out.println("CLEANING UP: " + f.getName());
// input
String input = win_str(target + f.getName());
// command
String command = "cmd /C del " + input;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
}
}
// set status, awake other threads
launcher.status = 1;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}

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

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

Going back to main class

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.

Categories