This code has lot of trouble for my AIR 2.0 Native process which I tried to launch Java from AIR application, then the Java.exe terminate itself in the Windows Task manager, I found that new MidiTest() was the caused. Is there a better solution for new instance?
public static void main(String[] arg) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!(speed.equals(speed_stop))) {
try {
speed = in.readLine();
if(!(Global.newPlayer.equals("1"))){new MidiTest();}
} catch (IOException e) {
System.err.println("Exception while reading the input. " + e);
}
}
}
private MidiPlayer player;
public MidiTest() {
System.out.println("Start player");
// /*
}
There is no alternative to new.
This is the only way to instantiate an object. Even if you use reflection, you're still calling the constructor. You need to track down the problem. Find the exact exception that's being caused, and the exact line number, and then see what you need to do to fix that problem.
I can see that you didn't provide a complete copy of your code. There's an open comment before the close brace, and it's not right. So that means we can't help you any further with the information we have.
No, the only other option for creating a new instance of your class would be using reflection, which is a much more obscure and error prone choice than new. It should not be used unless one really needs to. And even that is loading the class and calling the object's constructor in the end, exactly the same way as new.
I suspect the problem lies somewhere in code you haven't shown to us. Does MidiTest have any (static or nonstatic) initializer blocks? Is that println() statement really the only code in its constructor?
Of course, it helped if you traced down what is the exact error/exception causing the termination and where exactly does it originate from :-)
Related
I'm new to the world of programming. I am on my 6th class and we were tasked to create a new file using an instance of File. I'm getting an io exception when compiling. I searched online but I can't seem to find an explanation I can understand about the issue.
Please bear with me but my code is:
import java.io.File;
public class TestFile{
public static void main(String[] args) {
File myArchive = new File("MyDocument.txt");
boolean x = myArchive.createNewFile();
System.out.println(x);
}
}
As I understand createNewFile() will provide a true value if the file is created, but I keep getting the following message.
TestFile.java:5: error: unreported exception IOException; must be
caught or decl ared to be thrown
boolean x = myArchive.createNewFile();
^ 1 error
From what I gathered online, there's an exception that needs to be caught. The instructor didn't advise of how to handle an exception on the code or anything to do with the commands try or catch.
Thank you very much for you assistance. If I'm not complying with any of the forums' guidelines, please let me know, this is my first post and again I'm fairly new to programing.
In java you will get many Exceptions and you have to handle It using try..catch block.
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Additionally you have to define boolean x outside the try block and should be initialized to some value (either true or false) .
Try this code:-
import java.io.File;
public class Main {
public static void main(String[] args) {
File myArchive = new File("MyDocument.txt");
boolean x = true;
try {
x = myArchive.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(x);
}
}
Output:-
true
Just an intro to try-catch and what's it for:
Some operations may generate an error, which may even not be a mistake of the programmer, but may happen due to unforeseen circumstances.
For example, you want create a file, but at this moment, the file destination may become absent (e.g., a usb stick is taken out), or the disc may be full, or it may be an impossible filename (provided by another user through the keyboard, containing "forbidden" characters), or permission may not be given (e.g. in Android, when your phone asks for permissions to write files, you may grant it, or you may refuse to grant it for security's sake).
For such cases, Java provides you with an opportunity to try the error-prone code, and then catch the error. If an error happens, you don't want your app to crash. You want it to continue continue working, so you may warn the user on the screen that the file operation failed, and provide alternative actions.
So, basically, you do the following
try{
// place a risky part of code here
// like, creating a file
} catch (Exception error)
{
// This part will be executed only if there is an error
// in this part, you can change the wrong file name
// or tell the user that the disc is not available
// just do something about the error.
// If an error does not occur, then this part will not be executed.
}
try {
boolean x = myArchive.createNewFile();
System.out.println(x);
} catch (IOException e) {
e.printStackTrace();
}
The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block
I have this code snippet that I'm trying to find out what exactly it is doing, I'm pretty sure the author is pretty confused, please explain if these statements are taking any affect.
Like starting an undefined Thread what does that actually do but run in a empty thread?
What happen when class is found doesn't the return value have to be stored someway or does it load into the class in some magical way?
public SomeClass() {
try {
Class.forName("SomeclassToBeFound");
} catch (ClassNotFoundException e) {e.printStackTrace();}
new Thread().start();
}
I would appreciate some help
This is what is happening in this code snippet.
1) New thread is created which is not doing any thing. it start and ends because there no work to be done in the run method.
2) Class.forName("SomeclassToBeFound"); This line will load the class if it has not been loaded before by the class loader. But if the class is already loaded it will have no affect.
Hope this helps.
This is my very first question on SO and I'm confused there isn't a similar question yet!
So the question is:
Why doesn't try-with-resources work with field variables?
Or in other words: Why do I always need a local variable for that?
Here goes some example code:
public class FileWriteTest {
public FileWriter file;
public void workingDemo() {
try(FileWriter file = new FileWriter(new File("someFilePath")) {
// do something
} catch (IOException e) {
e.printStackTrace();
}
}
public void notWorkingDemo() {
file = null;
try(file = new FileWriter(new File("someFilePath")) {
// do something
} catch (IOException e) {
e.printStackTrace();
}
}
}
May anyone explain me why there is this convention?
An instance variable may be changed at any point during the execution of the try-with-resources block. This would break its invariant and prevent the cleanup. Note that the local variable is implictly final, for the same reason.
BTW a better question is, why does Java force us to declare a local variable, even if we don't refer to it within the block. C#, for example, doesn't require this.
Update: with version 9, Java has stopped forcing us:
private final Some obj = new Some();
try (obj) {
// obj captured in a hidden local variable, resource closed in the end
}
I suspect the designers considered using a field a bad idea as this allow the object to escape the region of usage. i.e. it is only valid in the try block so you shouldn't be able to access it anywhere else.
Section 14.20.3 of the Java Language Specification states it will only work with local variables.
Why is this? My guess is checking for definite assignment and escapage (the local variable doesn't escape into the scope of another method). A field may be initialized anywhere in the class. My guess is that by validating it's a local variable, it's much simpler to analyse.
With Java 9, They added support for try with resources with variables.
// Original try-with-resources statement from JDK 7 or 8
try (Resource r1 = resource1;
Resource r2 = resource2) {
// Use of resource1 and resource 2 through r1 and r2.
}
// New and improved try-with-resources statement in JDK 9
try (resource1;
resource2) {
// Use of resource1 and resource 2.
}
https://blogs.oracle.com/darcy/more-concise-try-with-resources-statements-in-jdk-9
First off, I think it would be bad practice to have a variable/resource which is used at multiple places. If it is not opened in the try, then you cannot close it afterwards, if it is opened there, then you won't need a non-local variable.
This leads to "second": If you have a resource open already, then you need to close it somewhere else explicitly, otherwise the autoclose wouldn't know if it is open or not.
So, IMHO it makes only sense to handle it the way it is specified in the specification.
From Java 9, no need to use a local variable in try-with-resources block. See here.
It may have to do with consistency with the language specifications.
Whenever a variable is declared between two brackets, it is encapsulated inside and cannot be accessed from the outside:
anything
{
int var;
}
// cannot access var from here!
Why shoul try { } be an exception ?
I have read through the JEditorPane Docs, from what I can understand you simply need to editorpane.setText(String value); however I am quite new to java and this solution does not work with my code. I think I am missing something obvious but completely out of ideas.
I have created a new tab with this class that extends JEditorPane, this class is designed to open the contents of the file, put them on an array, reverse the array (so latest entry is on the top) then display this list in the JEditorPane (using JeditorPane because I need to make the save url's into hyperlinks),
public class HistoryPane extends JEditorPane{
ArrayList<String> historyToSort = new ArrayList<String>();
public HistoryPane(){
setEditable(false);
historySort();
}
public void historySort() {
try (BufferedReader reader = new BufferedReader(new FileReader("BrowserHistory.txt")))
{
String currentLine;
String newLine = new String("\n");
while ((currentLine = reader.readLine()) != null) {
historyToSort.add(currentLine + newLine);
}
} catch (IOException e) {
e.printStackTrace();
}
Collections.reverse(historyToSort);
System.out.println(historyToSort);
}
{
}
private void displayHistory(){
String sorted = historyToSort.toString();
***** HistoryPane.setText(String sorted); <<<------ PROBLEM SYNTAX.*****
}
}
I have tried multiple different entries into the setText() parenthesis with no luck. What am I missing? Thank You.
NOTE:
This class won't compile because it is reliant on another class (I can't paste all of it) but this code sits within a tabbed pane created by my main class:
Error Message:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problems:
Syntax error on token "setText", Identifier expected after this token
Return type for the method is missing
This method requires a body instead of a semicolon
OK, despite the fact that you haven't read the error message, it seems you're really a newbie, so I'll help.
HistoryPane.setText(String sorted);
The above isn't valid Java. A method invocation takes a list of arguments, without a type.
HistoryPane.setText(sorted);
Now that is a valid method invocation. But it tries to invoke a static method called setText() of the class HistoryPane. What you want is to invoke the instance method setText() on the current object. So the valid syntax is
this.setText(sorted);
or simply
setText(sorted);
That should solve this particular compilation error. Don't try to run your app before every compilation error, listed in the Problems view of Eclipse, is fixed.
Note that the above line won't do what you want it to do, but I'll let you investigate what you should do instead.
My advice: don't try using Swing, which is quite a complex beast, if you don't even know how to call a method yet. Start with very simple Java exercises, not involving any GUI, until you're familiar with the Java syntax, and understand how to read, understand and fix basic compilation problems.
EDIT:
After making all the changes you suggested, the problem remained. The debugger said the lemma variable was null, but the fixes I applied didn't make things better. So, due to deadline issues, I decided to approach the problem from another view. Thank you all for your help. :)
I am writing a small program and a NullPointerException drives me crazy. I have two classes: SystemDir and Search. The first one is just an encapsulation of initial directory and a search lemma. The Search class is shown below. Briefly, I want one thread to search the first level directory and the other one to expand the subdirectories. That's where I get the exception. The exception string is
Exception in thread "Thread-0" java.lang.NullPointerException
at Search.searchFiles(Search.java:59)
at Search.<init>(Search.java:53)
at SystemDir.<init>(SystemDir.java:61)
at Search$1.run(Search.java:45)
at java.lang.Thread.run(Thread.java:679)
Where the 3 points are t.start() inside the final loop, searchFiles method call, some lines above and the new SystemDir call in the run method. Can you help me please?
public class Search {
private Thread t;
public Search(String[] subFiles, final String[] subDir, final String lemma) {
t = new Thread(new Runnable() {
#Override
public void run() {
for(int i=0;i<subDir.length;i++) {
try {
System.out.println(subDir[i]);
new SystemDir(subDir[i], lemma);
}
catch (NoDirectoryException ex) {
Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
searchFiles(subFiles,lemma);
}
private void searchFiles(String[] subFiles, String lemma) {
for(int i=0;i<subFiles.length;i++) {
t.start();
if(subFiles[i].contains(lemma)) {
System.out.println(subFiles[i]);
}
}
}
}
As a rule, never start a thread from a constructor. It can create all sorts of issues, which may be responsible for the exception you get.
Create the thread like you do in your constructor, make searchFiles public and call that method from the client code, not from the constructor.
Apart from that, have you checked that:
subFiles is not null
none of the subFiles[i] is null
lemma is not null
(add println statements if necessary)
and as pointed out by #Gray, you can't start a thread more than once.
You have failed to posted the source code for SystemDir, but the stack trace says that its constructor is trying to create a new Search object in addition to the one that created the thread in the first place.
More concretely, probably the new Search(...) expression somewhere in SystemDir's constructor is passing null for subFiles. Is there a call to File.list() somewhere that you haven't checked for a null return from, perhaps? Note that list() returns null if it cannot list a directory at all, due to anything from missing permissions to directory-not-found.
Also, It appears you're attempting to start the same thread object more than once. That will cause an IllegalThreadStateException if there is ever more than one element in subFiles.
You have not included all the code.
With the information provided:
in searchFiles either t, subFiles, or subFiles[i] is null.
Your code itself doesn't make much sense.
That makes it hard to spot the error.
I recommend using the Eclipse debugger, and check WHICH value is null.
As far as I can tell, your problem is within the recursion into SystemDir, where you don't provide the code of.
In your searchFiles method, what is the point of starting the thread in a loop? Do you want to run the thread on each execution of the loop? I think you are missing something here.
Check if some value that you are passing to the constructor is null.