int[] total not printing [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm sorry if this title isn't descriptive; it's hard to explain the problem without the code. My problem is this: I'm running this code
private static Integer[] buffer = new Integer[60];
private static int sum;
...
public static void main(String[] args) throws InterruptedException{
...
while (true) {
try {
main.repaint(); //call paint() method for graphics
rebuffer();
getBufferSum();
//System.out.println(sum);
} catch (NullPointerException e) {}
Thread.sleep(1000);
//}catch(NullPointerException e){e.printStackTrace();}
}
}
private static void getBufferSum() {
System.out.println("Started");
int total = 0;
for(int i = 0; i < 60; i++){
total += buffer[i];
}
System.out.println(total);
sum = total;
}
private static void rebuffer() {
for(int i = 1; i < 60; i++){
buffer[i - 1] = buffer[i];
}
buffer[59] = count;
//System.out.println(count);
count = 0;
System.out.println("Done");
}
And I'm getting this output:
Done
Started
Done
Started
Done
Started
...
Why is the line System.out.println(total); failing to execute?

Your buffer variable is an array of Integer, which is nullable (contrary to primitive int, which defaults to 0).
It's likely that any element has not been initialized before invoking them by index in your getBufferSum method, hence a NullPointerException that is not logged, hence a sleeping time of 1 second, hence the "Done" statement prints thereafter.
You should probably add e.printStackTrace(); in your catch statement to figure this out, instead of sleeping for 1 second.
Also consider debugging your code.
As Hovercraft Full Of Eels points out, it is considered very bad practice to catch NullPointerExceptions (as most RuntimeExceptions and all Errors).
On the long run you should get rid of that try / catch.

Related

SO,Basically i am doing a Timer(Stopwatch) Program in Java for 24 Hours but The hours Never Increment by one why so? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Basically i am doing a Timer(Stopwatch) Program in Java for 24 Hours but The hours Never Increment by one why so?
I am not able to find out why the hours is not displaying the number of hours after each passing hour.
Here Is My Program Below:
public class Real
{
public static void Th()
{
int hrs=0,min=0,sec=0;
int temp=0;
try
{
Thread t=Thread.currentThread();
System.out.println(sec);
boolean flag=false;
System.out.println("\t\t\t\t\t\t*****Timer*******");
System.out.println("HOURS:MINUTES:SECONDS");
while(flag==false)
{
System.out.println("\f\t\t\t\t\t\t*****Timer*******");
System.out.println("HOURS:MINUTES:SECONDS");
System.out.println(hrs+"\t"+min+"\t"+sec);
t.sleep(1000);//1 sec
sec++;
temp=min;
if(sec==60)
{
min++;
sec=0;
}
if(temp==60&&sec==60)
{
hrs++;
temp=0;
}
if(min==59)
{
min=0;
}
if(hrs==24||hrs==12)
{
if(hrs==12)
{
hrs=0;
}
else if(hrs==25)
{
flag=true;
}
}
}
}
catch(InterruptedException e)
{
System.out.println("THREAD INTERRUPTED");
}
}
}
You should look into this bit of code:
if(sec==60) {
min++;
sec=0;
}
if(temp==60&&sec==60) {
hrs++;
temp=0;
}
What you want is hrs++; to be called. In order to meet the condition in the if-statement both temp and sec need a value of 60. But sec cannot ever be 60 at that if-statment because it gets overridden by sec=0; in the if-statment above.

java question about try catch statement with finally [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Here is a code written by java.
public class work2{
public static void main(String args[]) {
try {
int x = 0;
for (x=1; x<4; x++);
System.out.println(x);
} catch(Exception e) {}
finally {
System.out.println("Error");
}
}
}
And the output is
4 Error
Would you explain why the output is looks like this?
Always remember in a try catch block - "finally always Run", irrespective of whether there is an exception or not. Now coming to your code. Inside the try block you have below line:
try {
int x = 0;
for (x=1; x<4; x++);
System.out.println(x);
}
Here the for loop ends in a semicolon, which means it doesn't have a body.
Now, the for loop will run from i=1 till i<4 and then will come out of loop with value of i as 4.
Now the next line is a print statement which prints the current value of i as 4.
After that the controls goes to the finally block and prints "Error"
That's how you get the output as
4
Error
The for - Loop you're using is only increase the value of x but doesn't print it out. So you increase x to 4 and than print it out, the finally part will be printed anyway.
If you want to put out every value of x, you had to add { } after the for - Loop.
It will look like:
public class Main{
public static void main(String args[]) {
try {
int x = 0;
for (x=1; x<4; x++) {
System.out.println(x);
}
} catch(Exception e) {}
finally {
System.out.println("Error");
}
}
}
try {
int x = 0;
for (x=1; x<4; x++);
System.out.println(x);
}
the try block didn't catch any exception, so the code were run as it is.
and in
finally {
System.out.println("Error");
}
A finally block contains all the crucial statements that must be
executed whether exception occurs or not. The statements present in
this block will always execute regardless of whether exception occurs
in try block or not such as closing a connection, stream etc.
it will print "Error" regardless what happen.
So, Try block printed 4, and then Finally block print "Error"
You write the statements which cause exception in try block. And these exceptions are handled using catch block. finally block is executed even if exception is not triggered.
In your question, x=0; initially. Since there is a semicolon ; after for loop, the loop will be executed 3 times and when x=4, the condition fails and it prints the value of x that is 4. And finally block is executed.
public class Main{
public static void main(String args[]) {
try {
int x = 0;
for (x=1; x<4; x++)
System.out.println(x);
} catch(Exception e) {}
finally {
System.out.println("Error");
}
}
}
The output should be
1
2
3
error
you should remove the ; after for loop .
A finally block contains all the crucial statements that must be executed whether exception occurs or not. ... The statements present in this block will always execute regardless of whether exception occurs in try block or not such as closing a connection, stream etc.

Calling non static method in static method [duplicate]

This question already has answers here:
What is a StackOverflowError?
(16 answers)
Closed 4 years ago.
I am having a little issue with my code. I am trying to find the runtime to compare to some math that I have prepared for the problem. I have one method in particular that I am testing that goes like this:
public static int foo(int n, int k){
long startTime = System.nanoTime();
if(n<=k){
long endTime = System.nanoTime();
System.out.println("checkFoo");
System.out.println("start time: " +startTime);
System.out.println("end time: " +endTime);
return 1;
}
else{
return foo(n/k,k) + 1;
}
}
I test this code in my main method in the following way:
public static void main(String[] args){
foo(1, 1);
foo(5, 1);
foo(10, 1);
foo(100, 1);
}
I get an error where it says
Exception in thread "main" java.lang.StackOverflowError
and then it repeats the line:
at Problem3.foo(Problem3.java:42)
I am wondering if this has to do with the fact that foo is supposed to return an int and maybe I am just not calling the function correctly. If that is the case, what is considered the correct way to call this function so that it also prints out the information that I need it to? Or is this error completely different than how I am understanding it to be?
You just have an infinite recursive loop:
foo(5, 1): n = 5, k = 1
calls foo(5 / 1, 1), i.e. foo(5, 1)
calls foo(5 / 1, 1), i.e. foo(5, 1)
calls foo(5 / 1, 1), i.e. foo(5, 1)
...
You would have gotten a compile error if the problem was a wrong return type. A stackoverflow error is caused when the method uses up all the memory that has been allocated. For more info on how a stackoverflow error is caused read this: What is a StackOverflowError?
Seems like you have an infinite recurrent function call, which causes JVM's heap overfill. Try to include some input validation to prevent situations like this.
Your code is running in infinite loop but you can catch it like below
public static int foo(int n, int k){
long startTime = System.nanoTime();
if(n<=k){`enter code here`
long endTime = System.nanoTime();
System.out.println("checkFoo");
System.out.println("start time: " +startTime);
System.out.println("end time: " +endTime);
return 1;
}
else{
try {
return foo(n/k,k) + 1;
} catch (StackOverflowError e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 1;
}
}
}
When you call this foo(5, 1); the the argument are 5 and 1 this means logic inside foo if(5<=1) fails and thus code in side else will execute i.e. return foo(5/1,1) + 1; this will call foo again and again, and repeats, and repeats ... resulting in StackOverflowError
foo(5, 1); always calling with out ending foo, so you are getting StackOverflowError
try to make this call end

MultiThreading with for loops in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Alright so i have been trying to run a for loop that runs 60 times. In this for loop i am using Thread.sleep(2000); to ping a server. I want to do this 10 times for this thread but for a separate loop through the for loop. In the mean time i want another 6 threads running doing 10 of their own so this hole process is sped up and completed in around 12 seconds.
for(int i = 0; i < 6; i++) {
//I am starting a new thread here.
}
#Override
public void run() {
//THIS is where i want a each thread to be doing 10 each to speed up the process.
for(int i = 0; i < 60; i++) {
//Pinging server.
Thread.sleep(2000L);
//Gets info from server here. That is why there is a 2 second delay.
}
}
I am sorry if this is hard to understand but i tried setting this out in the simplest way possible.
Thanks in advance.
If I get You right, You are not depending on the results, right? Here is a quick handdraft made out of the code:
Thread[] t = new Thread[6];
for(int i = 0; i < 6; i++) {
t[i] = new Thread() {
#Override
public void run() {
for(int i = 0; i < 60; i++) {
//Pinging server.
Thread.sleep(2000L);
//Gets info from server here. That is why there is a 2 second delay.
}
}
};
t[i].start();
}
Thread.sleep(longEnough);
This is the cheapest variant for kicking off threads, but beware, it is not professional! You should at least loop over the thread array to call join() on them in order to wait long enough instead of using a time constant.
If You want to do serious threading please consider using Java's ExecutorService (see http://www.vogella.com/tutorials/JavaConcurrency/article.html#threadpools) or ForkJoin of Java 7 (http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html)
In your initial for loop, instead of creating Threads, you should be creating Callable instances. Add these into a List, create an Executor, and pass the List to the Executor (FixedThreadPool for example). Then execute the Executor and they'll run in parallel. After all these hints, Ill leave the implementation to you since this looks sneakingly like a homework question.

The counter is a negative value in some cases. Why? And How to solve this? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
package threadapps;
public class Threads extends javax.realtime.RealtimeThread{
/**
* #param args the command line arguments
*/
static volatile boolean stop = false;
public static void main(String[] args) throws InterruptedException {
// TODO code application logic here
//
Thread a = new Threads();
Thread b = new Threads();
//set priority for threads
a.setPriority(4);
b.setPriority(6);
//run threads
a.start();
b.start();
//Sleep Thread
Threads.sleep(5000);
stop = true;
}
#Override
public void run(){
// for loop for counting to 10
//for(int i = 0; i<10;i++){
// System.out.println( Thread.currentThread().getName()+" The Counter Is "+i);
//}
int count = 0;
for(;!stop;)
count++;
System.out.println(Thread.currentThread().getName()+" The Count is "+count);
}
}
Run this code and see the results. Can it be negative in some cases?
If count will reach the Integer.MAX_VALUE then, at the next increment, it will be the Integer.MIN_VALUE.
Try following code:
int x = Integer.MAX_VALUE;
System.out.println(++x); // prints out -2147483648
Once you reach the max value an Integer can hold, you go back to Integer.MIN_VALUE and increment from there on. So I guess in your code count just goes up to Integer.MAX_VALUE and then keeps on going (as it runs for 5 seconds), ending up being negative.
If you want to hold larger values use a long.
Its because of binary calculation.
see the byte-example.
00000001 is decimal 1
00000010 is decimal 2
...
01111111 is decimal 127
10000000 is decimal -127
10000001 is decimal -126
Same to a int.
Use a BigInteger instead of int because its an infinite word size-integer

Categories