TRENDING NEWS

POPULAR NEWS

How Can I Exit Anywhere Within A Java Program

How do you exit a Java program?

You haven't specified what type of Java program but for the most straightforward one - not in a runtime environment like OSGI its a matter of just exiting from the main function.There are also methods in System and Thread which will cause a more abrupt exit.(Edit for phone keyboard induced spelling)

How do I exit a Java program without System.exit?

From your question my guess is that there is something wrong with your program. In case there is and endless loop or cross referenced logic in your code which is not found by the compiler in compile time then you are using some of the Java resources incorrectly. It's either waiting for some input or there is an endless loop, a blocked operation. You can use some Debugger to check those options! e.g. EclipseAs for the language lets you exit, there is not too many options:- Return from main(); (normal way)- System.exit();- The old dirty GOTO -> LABEL somewhere around the end of your main();- The other dirty calling / executing an external (native) piece of code using some libraries which is outside your JVM (Java Runtime).

Can I have a program in C/C++ with different entry and exit points, like entry main() n and exit in some foo()? Is there some other language where it is possible or even common?

Long ago in a land far away… When I was a young fellow, I worked on operating systems on IBM/370 platforms. It was possible in IBM/370 assembler to write modules with multiple entry and exit points.In C/C++, I’m not aware of any way to have multiple entry points. But you can have multiple exit points. You can call the exit() function from anywhere in a process. You have to be very careful doing so, though. The exit() function causes a process exit, but it doesn’t immediately synchronize with any threads started by the process. The exit() function will cause destructors on global objects to be called, and these will race with other threads in the process. So you can end up having threads that access objects that have been destroyed. I’ve debugged several cores caused by such practices; I don’t recommend using exit().

Why does my Java program run forever?

Thanks for A2A Satyam J As others have answered correctly you are missing a statement like x++; or x--; to your code. Right now you while loop is infinite while loop because while ( x < 10 ) is always true, which takes it forever to build and run...Following is fix of your code: pay attention to line no: 16 i.e x++;import java.util.*;
import java.lang.*;
import java.io.*;

class Exerciselb
{
public static void main (String [ ] args)
{
int x = 1;
while ( x < 10 )
{
if ( x > 3 )
{
System.out.println ( "big x" );
}
x++;
}
}
}
output: Success time: 0.12 memory: 320576 signal:0big xbig xbig xbig xbig xbig x

Programming 101 question: Why won't it run? (Java)?

This is my code:

import java.awt.Color;
import java.awt.Graphics;
import java.util.*;

public class Spiral {


public static void main(String[] args) {
Scanner console = new Scanner (System.in);
int myColor = console.nextInt();
DrawingPanel panel = new DrawingPanel (170,170); // Here I declare the drawing panel, our "canvas"'
Graphics g = panel.getGraphics(); // Here is our "paintbrush" (Building Java Programs, p. 197)


public static void BackgroundColor (int myColor) {
if (myColor == 1) {
panel.setBackground(Color.BLUE);
} else if (myColor == 2) {
panel.setBackground(Color.LIGHT_GRAY...
}
else if (myColor == 3) {
panel.setBackground(Color.MAGENTA);
}



It says "panel cannot be resolved" I don't understand what that means.

How to re-run the main method in java?

The main() method is public and static and can be called from anywhere else in your code. If you want to run the additional instance of your application under the same process as the original instance, you can just call this method, passing in any necessary String parameters. However, it would be advisable to do this from another thread, particularly if you are initiating the new instance from the Event-Dispatching Thread (e.g. as a result of a user clicking a button or somesuch).

Thread t = new Thread()
{
public void run()
{
String[] args = { };
MyClass.main(args);
}
};
t.start();

If, however, you want to re-launch your application in a new process (i.e. under a separate instance of the JVM), you can use Runtime.getRuntime().exec(...); to launch the java virtual machine executable passing in your application's entry-point class.

Java Problem: Counting all instances of repeating fractions from a text file?

Here's your code, with modifications so it works properly. I've add a boolean array counted so that it knows if a fraction has been counted already; I've also modified the final print statement. Seems to work okay now. Good luck!

import java.util.Scanner;
import java.io.FileNotFoundException;
import java.lang.String;
import java.io.FileInputStream;

public class Fractions{

public static void main(String [] args){
//Reads file containing fractions
Scanner inputFile = null;
try {
inputFile = new Scanner(new FileInputStream("fractions.txt"));
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}

//variables
String[] fractions = new String[100]; //will take in the fractions
String[] split = new String[2]; //used to split the fractions
int[] numerator = new int[100]; //store numerators
int[] denominator = new int[100]; //store denominators
int count = 0; //number of lines in file
int duplicate = 0; //number of fractions that are the duplicate
boolean[] counted = new boolean[100];

//count the number of lines in the file, put each line into the string[] fractions
for (int i = 0; inputFile.hasNextLine(); i++){
fractions[i]=inputFile.nextLine();
count++;
}

//split the fractions[] into two arrays: numerator and denominator
for(int i = 0; i < count; i++){
split = fractions[i].split("/");
numerator[i] = Integer.parseInt(split[0]);
denominator[i] = Integer.parseInt(split[1]);
}

//used to compare specific numerator and denominator to the rest of the numbers
int num;
int den;

//start off by comparing denominator, and then compares the numerator
//of like denominators
for(int i = 0; i < count; i++){
den = denominator[i];
num = numerator[i];

for(int a = 0; a < count; a++){
if (!counted[a]) {
if(den == denominator[a]){ //compare denominators
if(num == numerator[a]){ //compare numerators
duplicate++;
counted[a] = true;
}
}
}
}

if (duplicate>0) {
System.out.println(num + "/" + den + " has a count of "+ duplicate);
}
duplicate = 0;
}
}
}

// end of program

In Java, can I use "return" in a while loop in a method?

Yes. Remember, you cannot control how a method exits, because in any given statement you can have an exception that will exit the block and possibly the method. So every statement is a potential “return” of a sort, though it returns to the nearest enclosing try. Therefore return statements are no different than any other statement.If you want to control what happens at exit, or to force your code through some processing at exit time, then put the entire method in a try {} finally {} and do your required exit processing in the finally block, which runs whether the code ends with return or an exception. That is the only way to guarantee that the exit code actually runs.This also means that every method call has three types of returns. The normal return gets an object of the return type of the method and is the most efficient. Then there are returns for the declared exceptions that get an object of the declared exception type. Then there are the undeclared exceptions. Exceptions are more expensive because they require searching the stack for a handler, but if they are infrequent you should regard throwing them as a “return” with a different object type. (If the type returned by the method is a reference type, then it may be useful to add a forth possible return when you pass back a null instead of an object).One difference between professional and non-professional programmers is the attention given to errors and exceptions. Professionals know that “anything that can go wrong will go wrong” which means that any exception that can possibly occur should be considered in the design of the program. You may choose to ignore it and let it propagate up the stack, but that becomes part of the signature of the method and even if undeclared exceptions don’t have a syntax in the language, this is one of the things you should document in the block comment in front of the code.If an entire method is enclosed in a try block, then it cannot throw undeclared exceptions and the caller doesn’t have to worry about them. That is one programming model. The other is to ignore them and then they implicitly become part of the method signature, and the caller has to make a specific decision to localize any exceptions near the point of the call (by putting the call in an exhaustive enclosing try block) or whether you want to “adopt” as your own all exceptions raised by the methods you call as part of the possible exit conditions of your calling code.

Formatting in Java?

I am having trouble formatting the outputs at the end to one decimal place.

import java.util.Scanner;

public class OrganizingGrades
{
public static void main(String[] args)
{
int gradeA, gradeB, gradeC, gradeD, gradeF, gradeTotal, gradeInput;
double percentA, percentB, percentC, percentD, percentF;
Scanner keyboard;

gradeA = 0;
gradeB = 0;
gradeC = 0;
gradeD = 0;
gradeF = 0;
gradeTotal = 0;

...
System.out.println("ERROR: Not a valid grade.");
}

else if (gradeTotal == 0)
{
System.out.println("No grades entered.");
}
else
{
percentA = ((double) gradeA / (double) gradeTotal) * 100;
percentB = ((double) gradeB / (double) gradeTotal) * 100;
percentC = ((double) gradeC / (double) gradeTotal) * 100;
percentD = ((double) gradeD / (double) gradeTotal) * 100;
percentF = ((double) gradeF / (double) gradeTotal) * 100;

System.out.println("Total number of grades = " + gradeTotal);
System.out.printf("Number or A's = " + gradeA + " which is %.1f.%\n", percentA);
System.out.printf("Number or B's = " + gradeB + " which is %.1f.%\n", percentB);
System.out.printf("Number or C's = " + gradeC + " which is %.1fn%\n", percentC);
System.out.printf("Number or D's = " + gradeD + " which is %.1f.%\n", percentD);
System.out.printf("Number or F's = " + gradeF + " which is %.1f.%\n", percentF);
}
}
}

Major problem with variables inside actionListener class Java HELP!?

Ok, so I reduced my code down to this:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class satframe extends JFrame {

public static void main (String []args ) {
satframe frame = new satframe();
frame.setVisible(true);
}

public satframe( ) { //DO NOT TOUCH!!!

//set the frame default properties
setTitle ( "Satellite Upload");
setSize ( 1024,600 );
setLocationRelativeTo ( null );
setResizable (false);
//register 'Exit upon closing' as a default close operation
setDefaultCloseOperation( EXIT_ON_CLOSE );

changeBkColor( );
}

private void changeBkColor() {
//change background color to green
Color myGreenColor = new Color(0, 100, 0); //a dark green
Container contentPane = getContentPane();
contentPane.setBackground(myGreenColo...
//set layout manager to null
contentPane.setLayout(null);
//make the map, and align it to the left
ImageIcon pic = new ImageIcon("pic.png");
JLabel map = new JLab

TRENDING NEWS