How to return to the main method and execute again the whole program? I tried the return but it just ends the execution.
This is the code:
File folder = new File("C:\my path");
File[] listOfFiles = folder.listFiles();
if (folder.isDirectory()){
if(folder.list().length>0){
System.out.println("Directory is not empty!");
}
else {
System.out.println("Directory is empty!");
return; //I need to return from the main method
}
}
else{
System.out.println("Invalid directory!");
}
I want to return to the main method if the directory is empty. I used the return but, it did not return from the start :( Any idea on how to return to the main method? Thanks :)
This is the entire main method: (Sorry if it is too long)
My goal is to check if a new file entered the directory. Then it will list the files on that directory and one-by-one it will be deleted. If there's no file from the directory, it will return to the start.
Comment correction: "//It will return to the start"
The two loops: The second loop will be executed during the execution of the first loop. (Sorry if I did not indent it). After the execution of the second loop, it will return to the first loop.
It's hard to read but I assume you want to exit the loop using return statement which is not working that way. If you want to exit a loop you have to use break.
Here's a little bit of explanation: Difference between Return and Break statements
And since it's a basic programming knowledge I advice you to go through some Java tutorial first. For example: http://www.tutorialspoint.com/java/inde
The traditional way to return all the way to the top main method, is to throw a RuntimeException (or one of its subclasses) which is caught by the main method only. Any exception handlers on the way up, must rethrow this exception after doing what they need to.
Note that your application must be written very carefully to avoid leaking resources like opened files.
Don't do everything in main method. You must extract part of your code in other declared method like:
public static void doPartOfSomething() {
...
}
public static String doOtherPartOfSomething( String path ) {
...
return "aresult"; // Stop the execution of this method
}
Please note that the second one takes a parameter and returns a result when is called (a String here)
And then, from main method (or other place), you can call this piece of code several times:
doPartOfSomething();
doPartOfSomething();
String result = doOtherPartOfSomething( "/test" );
...
Doing that, you can execute some piece of code, return and stop a part of code, and continue with another call into the calling method.
I think you should learn more about classes, objects, methods and fields in java.
Related
Considering the following code
public static void main(String...arg){
//do something
if(<<the method has called by a new process>>){System.exit(0);}
else{System.setProperty("main_result","0");return;}
}
the main method would be called by a separated process by JVM or existing process, now how can I find it out?
Thanks in advance
Let's clarify: there might be another class with a main that was started, or the main is somehow called again.
Normally you want to call System.exit(0) (or return;?) but when called from the program itself you want to end in System.setProperty("main_result","0");.
public static void otherMain(String[] args) {
Main.main(args);
}
public static void main(String[] args) {
...
StackTraceElement[] elems = Thread.currentThread().getStackTrace();
//for (StackTraceElement elem : elems) {
// System.out.printf("%s%n", elem.getClassName());
//}
if (elems.length > 2) { // [0] Thread [1] main
System.setProperty("main_result","0");
}
}
In java, every Java process runs in its own JVM. So, the "same" main
method cannot be called by a different process under normal
circumstances
Even if you run the same program twice, they will be running in their
own JVMs.
You can try one thing.. Keep a static variable in your program, run it and
make it sleep for a long period of time (process 1).. Now, run the same
program again and update the static variable(runs in process 2).. See, whether it will be
updated in the first process (No, it won't be updated as each process will have it's own
set of variables..)
Do you really need it? Just don't use System.exit(0); and refactor main method to finish gracefully.
Calling System.setProperty in both cases - when run as new process and also as a class on classpath, will not make any difference.
Edit: Finding out who is calling the method is not easy and definitely bad practice.
I would refactor the code as follows:
public static void main(String...arg){
System.exit(doStuff(arg));
}
public static int doStuff(String... arg) {
//do something
}
To access this logic within the same JVM you can now call MyClass.doStuff and get the return value directly.
It would be better to consider refactoring and get rid of such problem.
Otherwise the following code can help:
if(Thread.currentThread().getStackTrace()[1].getClassName().equals(
System.getProperty("sun.java.command"))){
System.out.println("!");
}
Will not work if there is no "sun.java.command" property (on not Sun/Oracle JVMs it may absent)
I was doing some work for college and my main runs this:
Spreadsheet sheet = new Spreadsheet(0,0);
SpreadsheetManager manager = new SpreadsheetManager(sheet);
/* Read an Import file, if any */
String filename = System.getProperty("import");
if (filename != null)
sheet.parseInputFile(filename, sheet);
Thing is, when I actually try to import a file it doesn't do what is supposed to and the filename is always null, so it never reaches my parseInputFile.
My teachers made a bunch of code for different programming exercises that do similar things available, and I've also looked at projects my colleagues did in previous years, but every single one does what I am doing above.
I have to run my program like this: java -Dimport=A-002-002-M-ok.import calc.textui.Calc otherwise none of the tests given by the teachers will run.
I'm sorry if this is not a useful question, but I've tried looking everywhere. If anyone could explain how the System.getProperty("import") works and why it isn't working in this case, I would be very grateful.
I suggest you take a look at the documentation of System.getProperty().
Basically it retrieves a value from the system, either already present or set by you.
To avoid retrieving null you can use another method signature that specify a default value:
System.getProperty("import", "file.txt");
To set a System property, you can specify it at launch:
java -Dimport="file.txt" your_application
or set it programatically :
System.setProperty("import", "file.txt");
When you run your program with:
java -Dimport=foo
then the method call
System.getProperty("import")
should return "foo".
Is ist possible that you write a tiny example program to convince yourself? Without any SheetManagers and all stuff, just
class ItWorks {
public static void main(String[] args) {
System.out.println(System.getProperty("import"));
}
}
Call it thus
java -Dimport=indeed ItWorks
and report what happens.
That being said: if you want to pass command line arguments, why don't you use the facility for command line arguments? (i.e. the String[] array passed to main?)
You could then call your program like this:
java calc.textui.Calc my-nice-spreadsheet.data
=====================================================
Please write the follwoing in your calc.textui.Calc program immediately after the open brace of your class definition:
public class Calc ..... { // a line like this already exists
// insert next line here
public static String filename = System.getProperty("import");
// rest of your class, as before.
}
Then comment out the getProperty() line in your method that didn't work, but leave the rest including the System.out.println(filename);
Does it change?
Maybe system properties are not the most indicated way to do that (depends on your application).
You could also use command line arguments to pass the file name to your main method:
public class CommandLineExample {
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("usage: CommandLineExample <filename>");
System.exit(1);
}
String filename = args[0];
if (filename !=null && !filename.isEmpty()) {
...
}
}
}
Your program should be called as:
java CommandLineExample theFileName
the string "theFileName" will be passed to the main method in args[0] (any additional words will be passed in subsequent positions of args {args[1], args[2], ...})
EDIT
if the program must be called with
java -Dimport=filename ...
then System.getProperty("import") will return the filename.
Confirm that you are calling the correct program (class name, package, version, last compile was successful, ...) and also check that the property is not mistyped like java -Dinport=A-... or has additional spaces, uppercase letters...
I'm writing a private method in Java that reads and write to a simple text file, which it should make if it doesn't exist since createNewFile() checks for that first.
private boolean updateGameQuota(String name, String quantity) {
...
File quotaLog = new File("seller-quotas.txt");
quotaLog.createNewFile();
...
return ret;
}
The compile-time error is: SmsFunctions.java:256: error: unreported exception IOException; must be caught or declared to be thrown
quotaLog.createNewFile();
^
1 error
Placing it in a try-catch block doesn't seem to be the issue, as I tried that (also on many other lines that try passing quotaLog) but eventually I get to a point where it's clear that something else is wrong. The File object is fine, but then if I try to use createNewFile or say
FileReader sQReader = new FileReader(quotaLog);
I get a FileNotFoundException even though the file is definitely there and I tried this on other text files which are read elsewhere successfully with the same result.
Any help or ideas would be greatly appreciated!
Update:
So in the end my issue was indeed just putting try-catch blocks around everything and making sure variables set within them were first created outside of those blocks. My confusion came from a false sense of sureness that fileraders/filewriters shoulnd't need try catch blocks (I could swear I've used them without many times) and the error was actually an indication of something else.
Perhaps before closing the thread someone could elaborate as to why Java doesn't always make a fuss about it, if that's true?
Thanks!
File.createNewFile() can throw an IOException (a checked exception) and needs to be surrounded in a try-catch block or the method you're using it in needs to be declared as throws IOException and you need to handle it upstream.
To debug the FileNotFoundException, you could try:
File quotaLog = new File("seller-quotas.txt");
System.out.println(quotaLog.getAbsolutePath());
Which uses the File.getAbsolutePath() method to print where it expects the file to exist.
So I'm making a program on a pretty low level of Java-programming.
This is what I'm having problems with:
//The String fillText is given a value earlier in the program
if ("".equals(txa1.getText()))
{
txa1.setText(fillText);
txa1.setVisible(true);
}
else if ("".equals(txa2.getText()))
{
txa2.setText(fillText);
txa2.setVisible(true);
}
else if ("".equals(txa3.getText()))
{
txa3.setText(fillText);
txa3.setVisible(true);
}
else if ("".equals(txa4.getText()))
{
txa4.setText(fillText);
txa4.setVisible(true);
}
else if ("".equals(txa5.getText()))
{
txa5.setText(fillText);
txa5.setVisible(true);
}
...
This code appears to ALWAYS fill all of the textareas (txaX) with fillText.
I was expecting it to only execute the first of the statements that returned true and then break out of the if-else-statement.
I tried to do it with a switch-case, but ended up failing since the String is changed during the run of the program.
What is wrong?
Thanks in advance!
It is in loop .Definetely that is causing the problem.With out loop it will go to only one block.It is not possible too execute without loop.When ever we are using if else only one block will execute.
"".equals(txa1.getText())
I think above condition for each returns true.
getText() method is always returning empty string i.e "";
You have to carefully examine your conditions, it'll basically execute the predecessors if the condition is false.
I suggest you think more on the logic of what you are trying to achieve..
I'm running into the strangest error in this program, which is confirmed when debugging it. I have the following code (boiled down to highlight the problem, of course):
BHFrame.java
public class BHFrame
{
private boolean uSS;
private StateSaver stateSaver;
public BHFrame(boolean useInternalStateSaver)
{
//Init code
uSS = useInternalStateSaver;
//More init code
System.out.println(uSS);
if (uSS)
{System.out.println("Entered 1");
stateSaver = new StateSaver(title, false);
stateSaver.addSaveable(getThis());
}
//More init code
System.out.println(uSS);
if (uSS)
{System.out.println("Entered 2");
try
{
stateSaver.loadState();
stateSaver.putState(getThis());
}
catch (IOException ex)
{
alertUserOfException(ex);
}
}
}
}
GUI.java
public class GUI extends BHFrame
{
public GUI(boolean useInternalStateSaver)
{
super(useInternalStateSaver);
}
}
Main.java
public class Main
{
public static void main(String[] args)
{
GUI gui = new GUI(false);
}
}
Output
false
false
Entered 2
Exception in thread "main" java.lang.NullPointerException
at bht.tools.comps.BHFrame.<init>(BHFrame.java:26)
at bhms.GUI.<init>(GUI.java:5)
at bhms.Main.main(Main.java:5)
The class BHFrame is extended and run from a child class that calls this constructor, but that really shouldn't affect this behavior. The problem is that, when false is passed to the constructor as useInternalStateSaver, the first if (uSS) is skipped, but the second is entered. Upon debugging, I found that uSS is false throughout runtime, including on the line of the second if statement, here. Why would Java enter an if statement when the condition returns false? Before you ask, I did delete the .class files and recompile it just in case there was some residual code messing with it, but I got the same result. And rest assured, all the references to the uSS variable are displayed here.
Solution
As it turns out, this appears to be a bug in NetBeans 7.1 Build 201109252201, wherein the IDE doesn't properly insert new code into the compiled .class files. The problem was fixed by compiling the files externally. A bug report has been submitted.
Whatever's throwing that exception is probably not in your posted code.
It's not being caught by your catch statement, which only catches IOException.
It's a NullPointerException and can occur anywhere.
You have shown no indication that the code inside your if block is actually executing. In your screenshot, there is absolutely know way of knowing if your if block is entered or not. There are no logging statements.
Add debugging messages at various points to see exactly what is happening. Or, you know, look at line 26 (wayyyyy before your posted code) to see why you're getting a NullPointerException.
I've seen crazy stuff like this when there is bad RAM on the machine. You might want to run memtest86.
You might also consider deleting all of your project class files, and then doing a build. Maybe you changed Main.java, but it was never recompiled. I hate that when that happens.
This is just a guess, because I can't see the code you are mentioning, but I reckon you have defined a local variable uSS in the second //More init code segment.
Once you define a local variable named the same as an instance variable, it 'hides' the instance variable. Better to qualify all instance variables with this.
So, try qualifying all above accesses of uSS with this. ... (this.uSS)
Even if this isn't the issue, it might be better to post the full code anyway.
HTH