I'm on the last steps of finishing my BST and Trie in java and I've come across this problem. I can't print the last element out to a file. It's not the toString methods cause I've tried switching them around. I remember a while back one of my professors mentioned something about closing the file. Something along the lines of putting an int value inside the parentheses of the close method, I'll develop on this below (not sure if I'm right thought, just something I vaguely recall)
Here's a snippet of the code that I'm having trouble with.
try{
output = new PrintWriter(inputFile);
output.println("BST:");
output.println(tree.toString());
output.println("Trie:");
output.println(trie.myToString());
output.close();
}
catch(IOException e){}
System.out.println("Goodbye");
so if I recall correctly, the teacher said to do something like output.close(0) or the like, but it's shooting me errors. Can anyone help me with this? Thank you.
catch(IOException e){}
you are swallowing the reason here. Don't do that.
At least print the reason with
catch(IOException e) {
e.printStackTrace(System.err);
}
try
output.flush()
before close the output
or try
output = new PrintWriter(inputFile,true);
Related
I just got into java programming today and I made a calculator that I'm so proud of as a first project even though I took many parts of it from the internet like the Scanner code and how to allow input for the user, but I don't know how to print out an error if the input doesn't match the variable assigned to, ex: user inputs a string instead of an integer,
You could use a try and catch statement to determine if the input you need is of the type that you want.
try {
// Block of code to try
}
catch(Exception e) {
// error if it's not the type you are looking for
}
As the answer above states you can use try and and catch and also create a custom exception but that won't really help you because just copying it won't make you understand it and there is a lot of concepts you should learn before you take a look at that.
If you want to learn how to code/learn java I can recommend you this video series by BroCode https://www.youtube.com/watch?v=NBIUbTddde4&list=PLZPZq0r_RZOMhCAyywfnYLlrjiVOkdAI1
It's really good for beginners and easy to follow along
I'm trying to create a program that keeps asking a question until the user presses enter. But for some reason, the program goes into an infinite loop that continuously outputs:
"Enter the operation: You need to add '[' at the beginning of the set."
If you accidentally do not follow the rules. Now, the program should print that message but only once. I think the loop continuously asks for the operation but it goes straight to the error (If you do not enter anything, I guess that counts as not using an [ at the beginning).
I already know how to solve it but because I tried everything!! I am not sure how my solution changes anything... Can you give me advice on how to solve it and/or explain to me what is it about the do-while loop implemented at the end that does the trick?
Edit: TextIO is a class written by Eck, D. J. in his book. I will link the chapter where it gives the code here: http://math.hws.edu/javanotes/c2/s6.html
The problematic code is
while (true) {
System.out.print("\nEnter the operation: ");
TextIO.skipBlanks();
if (TextIO.peek() == '\n') { //There is no operation, end the program.
break;
}
try {
calculation();
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
The solution I implemented looks like this:
while (true) {
System.out.print("\nEnter the operation: ");
TextIO.skipBlanks();
if (TextIO.peek() == '\n') { //There is no operation, end the program.
break;
}
try {
calculation();
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
do {
ch = TextIO.getAnyChar(); // Read ahead the "enter".
} while (ch != '\n'); //If necessary, make sure to stop the error message and keep the loop going.
}
Thanks, guys!!
It sounds like you're using TextIO class from David J. Eck's Introduction to Programming Using Java, Eighth Edition book.
According to the source of the class:
[TextIO.peek()] returns the next character in the current input source, without actually removing that character from the input.
You're checking the input actually without removing it. That's why in the next iteration, the loop keeps reading the same bad input, and throwing the exception indefinitely.
Also your fix performs what is lacking after calling peek(). Removing the char from the input.
Hence, replacing peek() by getAnyChar() in your first attempt solves the problem.
I'm not sure what's TextIO, you should use the standard Scanner class.
Everytime I run this code, the console goes into an infinite loop printing "Please input a number". I do not understand why this is happening. Thanks in advance.
boolean check = true;
int temp = 0;
while(check==true){
try{
temp= asker.nextInt();
check = false;
}
catch(InputMismatchException e){
System.out.println("Please input a number.");
}
}
Edit: asker is a Scanner. The purpose of the code is to loop until an integer is inputted by the user.
The method asker.NextInt() is throwing an InputMismatchException, indicating that the input received from asker (assuming it's a Scanner) isn't actually an integer. This exception causes the loop to restart without setting check to false.
Print the exception within the catch block to get more information about the failure. But most likely, you're feeding your application something (lots and lots of something, if it's looping like that) that doesn't actually contain integer values.
You never want to actually "Use" try/catch--by that I mean don't use it as part of your program logic--this is what you are doing.
One big problem is that, like your app, you don't see the stack trace. Eating a stack trace in an exception is almost always wrong.
If you do have to catch an exception, handle it near the catch as well as you can, but it's better to set up your code so that the exception can't be thrown anyway.
Discard this advice if your teacher told you to do it this way, but remember in the back of your mind that it's poor form.
Also don't tell your teacher that it's poor form :) he either doesn't know in which case he won't understand why or he does know and is using this to show you how try/catch works.
What is asker, a Scanner? If nextInt() fails, it doesn't consume any input, so when you catch your exception and loop back around to try again, it ends up just reading the same bad input again.
You should do something in the catch block to consume the invalid input, so that the next time around, it can read some different input. Call asker.nextLine() maybe, and ignore the return value.
You need to break the loop and report why the loop occurs
boolean NotValid = true;
int temp = 0;
while(NotValid){
try{
temp= asker.nextInt();
NotValid = false;
break; // stop
}
catch(InputMismatchException e){
System.out.println("Please input a number. reason why:");
System.out.println(e);
NotValid = true;
}
}
I have this Java game server that handles up to 3,000 tcp connections, each player, or each tcp connection has its own thread, each thread goes something like this:
public void run()
{
try
{
String packet = "";
char charCur[] = new char[1];
while(_in.read(charCur, 0, 1)!=-1 && MainServer.isRunning)
{
if (charCur[0] != '\u0000' && charCur[0] != '\n' && charCur[0] != '\r')
{
packet += charCur[0];
}else if(!packet.isEmpty())
{
parsePlayerPacket(packet);
packet = "";
}
}
kickPlayer();
}catch(IOException e)
{
kickPlayer();
}catch(Exception e)
{
kickPlayer();
}
finally
{
try{
kickPlayer();
}catch(Exception e){};
MainServer.removeIP(ip);
}
}
The code runs fine, and I know that each thread for each player is a bad idea, but I'll have too keep it this way for now. The server runs fine on a fast machine (6cor x2, 64bits, 24GB RAM, Windows Server 2003).
But at some point, after about 12 hours of UpTime, the server starts to loop somewhere... I know that because the java process takes 99% of the CPU infinitely until the next reboot.
And I'm having hard time to profile the application because I don't want to disturb the players. The profiler I use (visualvm) always end up chashing the server without telling me where's the problem.
Anyways, in that piece of code above I think maybe the problem comes from this:
while(_in.read(charCur, 0, 1)!=-1)
(the _in is a BufferedReader of the client's socket).
Is it possible that _in.read() can return something else infinitely that will keep my code runing and taking 99% of ressources? Is there something wrong with my code? I don't understand everything, I only wrote half of it.
Reading one char at a time is almost as slow as building a String with +=. I wouldn't be able to tell you which is worse. It wouldn't surprise me if a single connection tied an entire core using this approach.
The simplest "fix" to do would be to use a BufferedReader and a StringBuilder.
However the most efficient way to read data is to read bytes, into a ByteBuffer and parse the "lines". I assume you are receiving ASCII text. You could write the parser to be able to process the content and the end of line in one stage (ie with one pass of the data)
Using the last approach, here is an example (including code) of where I am parsing an XML message from a socket and replying in XML. The typical latency was 16 micro-seconds and the throughput was 264K per second.
http://vanillajava.blogspot.com/2011/07/send-xml-over-socket-fast.html
You can do something like the following which likely to be fast enough
BufferedReader br = new BufferedReader(_in);
for(String line; ((line = br.readline()) != null;) {
if(line.indexOf('\0') >= 0)
for(String part: line.split("\0"))
parsePlayerPacket(part);
else
parsePlayerPacket(line);
}
If you find this solution dead simple and you are familiar with ByteBuffer you might consider using those.
I had the kind of a same problem at one of my applications I wrote. My Application took 50% cpu (in a dual core).
What I made then to resolve the Problem, is let the Thread sleeping 1 timetick
Thread.sleep(1);
I hope this is helpfull for you
edit:
oh and for what is that ?
}catch(IOException e)
{
kickPlayer();
}catch(Exception e)
{
kickPlayer();
}
I think you don't need the IOException Catch (the Exception catch, catches every kind of exception)
That exception handling just hurted my eyes. There's no point in calling kickPlayer() inside catch blocks since you are calling it again in finally. Finally executes (almost) always.
And now about your problem, forget my previous answer, I was a bit asleep XD. I don't see anything prone to loop forever in the posted while loop. InputStream.read() either returns -1 when there's no more data or throws an exception. The problem must be in other code, or maybe is a threading problem.
As they have told you in other answers, try to use buffered streams, reading a block of characters instead of only one at a time, and replace the string concatenation for StringBuilder's append method. This should improve performance, but not sure if it will solve the problem (maybe it appears in 24h instead of 12).
I have a question about the order of the execution of statements in a catch block in Java.
when I run the following class Test1 (see below), I expect to have as output first Hi!, then the result of the e.printStackTrace(); statement, and then Bye!. However, I never get this order. Please, look at the outputs, which I have pasted below.
public class Test1 {
public static void calculate() {
try {
int h = 5/0;
} catch (ArithmeticException e) {
System.out.println("Hi!");
e.printStackTrace();
}
System.out.println("Bye!");
}
public static void main(String[] args) {
calculate();
}
}
Output1:
Hi!
Bye!
java.lang.ArithmeticException: / by zero
at Test1.calculate(Test1.java:6)
at Test1.main(Test1.java:15)
Output2:
java.lang.ArithmeticException: / by zero
at Test1.calculate(Test1.java:6)
at Test1.main(Test1.java:15)
Hi!
Bye!
I have two questions:
1.) The more important question: Why I always have Hi! and Bye! printed always one after the other, even though mye.printStackTrace() in the code is between them?
2.) Why sometimes I have the output of the statement e.printStackTrace() before Hi!, and sometimes after Bye! ? I have run the program many times and I cannot understand under what circumstances I get one or the other print.
Thank you.
I am using Java 6, and Eclipse (Ganymed).
Exception.printStackTrace() prints to System.err whereas "Hi!" and "Bye!" are on System.out. If you run your program on a regular console, they eventually end up on the screen, but the order may be out. If you are running the program through an IDE (e.g. NetBeans), the streams will probably be color-coded so you can easily distinguish them.
You print "Hi!" and "Bye!" to System.out (i.e. stdout), while the stack trace is printed to System.err (i.e. stderr). The order in which they are printed is determined by when the two buffers are flushed.
It could be a timing issue. Println writes to standard out, while printStackTrace might be hooked up to standard error. Then it's just a matter of which buffer gets flushed first.
A1 - e.printStackTrace() prints to System.err and not System.out, so different streams, different print order.
try adding System.out.flush() after every print (printStackTrace included).