When I am running a simple java program in eclipse, when I run it, the console flashes what it should, then it disappears.
public class apples {
public static void main(String[] args) {
int age = 60;
if (age < 50) {
System.out.println("You are young");
} else {
System.out.println("You are old");
}
}
}
Your program is immediately terminating after printing what needed to be printed. You can use several methods to keep the console on the screen.
Your program is immediately terminating after printing what needed to be printed. You can use several methods to keep the console on the screen. One possibility is to use
while(true);
to stop the application from exiting. Beware that you should only use this for debugging methods!
Another, probably better, way is to ask for input before closing the window.
Simply read a line from standard input. Your program will wait until you type something and only then exit.
Scanner sc = new Scanner(System.in); // create a scanner that will read from standard input
String s = sc.nextLine(); // You don't even need to save the return value of
// sc.nextLine() here
Related
I am making a Program to find Values of Roots of a given Quadratic Equation.
This is the code -
import java.util.*;
class Success
{
public static void main(String[] args)
{
String input1;
Scanner sc=new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("-------------------------------------------------------------------");
System.out.println("-------------------------------------------------------------------");
System.out.println("!! Success !!");
System.out.println("------- (-_-) -------");
System.out.println();
System.out.println("Let's Try Again!!!");
System.out.println();
System.out.println("Enter anything to Exit or 1 to go back to Main Menu.");
input1 = sc.nextLine();
if(input1.equals("1"))
{
System.out.print('\f');
Main_Menu.main(args);
}
else
{
System.exit(0);
}
}
}
Here I use System.exit(0); to exit the program. But using this just minimizes the window. Is there any way to close the window.
P.S - This is just a class which links to Main_Menu Class if the entered value is 1. This is not the full code!
Quadratic Equations - BlueJ Program - Image
Thank You
The call to System.exit(0) just terminates the currently running Java Virtual Machine. It doesn't necessarily close the terminal window. A Java program does not know anything about it's context, so it cannot access the window it is using for its output.
However, there are two different ways to clear the terminal in BlueJ. You can get BlueJ to automatically clear the terminal before every interactive method call. To do this, activate the 'Clear screen at method call' option in the 'Options' menu of the terminal. You can also clear the terminal programmatically from within your program. Printing a formfeed character (unicode 000C) clears the BlueJ terminal, for example:
System.out.print('\u000C');
This will work in the BlueJ terminal, but is not guaranteed to have the same effect in all terminals. You could, for example, create a method with this in it and call that method whenever you want to clear the terminal screen.
public void clearScreen()
{
System.out.print('\u000C');
}
This is the basic setup for a little console-based quiz game. The answers are numbered. I want the player to give the answer number. If the input is not a number, then my program should give a warning, and wait for proper input.
Instead, what I get (after inserting something that is not a number) is an infinite loop of asking the question and presenting the answers again.
public static void main(String[] args) {
boolean quizActive = true;
while(quizActive) {
presentQuestion();
presentAnswers();
Scanner s = new Scanner(System.in);
if (s.hasNext()) {
String choice = s.next();
if (!NumberUtils.isNumber(choice)) {
presentText("Please insert the answer number.");
} else {
System.out.println("You made a choice!");
checkAnswer(choice);
quizActive = false;
}
s.close();
}
}
}
What am I doing wrong here?
If you do not want to question and answers be presented each time move presentQuestion() and presentAnswers() outside the loop.
But main problem is that you closing Scanner.
Remove s.close(); and move Scanner s = new Scanner(System.in); outside of the loop.
I really don't get the point in using scanner for acquiring user input.
The scanner class is perfect to process structured input from a flat file with known structure like an CSV.
But user input need to deal with all the human imperfection. After all the only advantage you get is not needing to call Integer.parseInt() your yourself at the cost to deal with the not cleared input when scanne.nextInt() fails...
So why not using InputStreamReader aside with a loop suggested by others?
Here an Example :
public class Application {
public static void main(String [] args) {
System.out.println("Please insert the answer number. ");
while (true) {
try {
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
System.out.println("You made a choice!");
checkAnswer(choice);
break;
} catch (Exception e) {
System.out.println("Invalid Number, Please insert the answer number ");
}
}
}
}
You started your Quiz in a loop which is regulated by your quizActive boolean. That means that your methods presentQuestion() and presentAnswers() get called every time the loop starts again.
If you don't input a number but a character for example, your program will run the presentText("Please insert the answer number.") and start the loop again. As it starts the loop again, it will call the methods presentQuestion() and presentAnswers().
To stop that, you can do another loop around the input-sequence. Also your Scanner s = new Scanner(System.in) should be outside the loop. And you shouldn't close your Scanner right after the first input and then open it again!
if you want a code example, please tell me :)
I wrote a simple program to loop and find max of a set of numbers input by the user as:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int currMax, currEl;
currMax = sc.nextInt();
while (sc.hasNext()) {
currEl = sc.nextInt();
currMax = (currEl > currMax ? currEl : currMax);
}
sc.close();
System.out.println(currMax);
} // end function main
}
I am using Eclipse on Windows.
When I run it the first time it runs fine, and considers Ctrl-Z as EOF and exits the loop. But second time onwards, it does not seem to read the EOF. I am unable to explain this, or fix this behavior.. what do you think is going on, and how do I fix it??
Follow-up: The problem happens with Eclipse, and not when I use cmd line. I suspect this is what is happening -- if I use cmd line, I can do Ctrl-Z and then hit Enter, but if I use Eclipse, I believe as soon as I hit Ctrl-Z, s.hasNext() evaluates to false and the above program terminates.
This program goes in an infinite loop in while cycle. Please, can someone tell me why?
import java.util.Scanner;
public class program {
public static void main(String[] pars) {
System.out.println("Insert something.");
Scanner read = new Scanner(System.in);
String s = "";
while(read.hasNext()) {
System.out.println(read.next());
}
System.out.println("End of program");
}
}
Read the Javadoc of Scanner#hasNext():
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
Hence the while loop will always be executed in your case, each time waiting for input from the user. Since the Scanner is linked to System.in, the input stream will always block until the user inputs a string and hasNext() will always return true, unless the user signals the end of file (e.g. through the Ctrl+z combination on Windows). Scanner#hasNext() is more convenient when reading from files where the input size is known and the end of the file marks the end of the stream.
One way to end the loop here is to add a condition on the input:
while (read.hasNext()) {
s = read.next();
if(s.equals("quit")) {
break;
}
System.out.println(s);
}
P.S.: It is more conventional to name classes starting with an uppercase letter.
The problem is this line:
while(read.hasNext()) {
If you use System.in as a stream provided by the user, it will - if no such input is available - as #manouti says, block and wait for input. But even if you provide input, it will keep waiting. The system has no means to detect whether the user wants to provide additional input in the future.
It will only stop, if the Stream ends. This can be under two conditions:
The end of the file (in case of I/O redirection like java -jar program.jar < input.dat; or
The user marks the end of a stream, in most shells with Ctrl+D. This marks the end-of-stream.
An alternative is to provide some kind of stop directive. Something like "END". Thus:
while(read.hasNext()) {
String nx = read.next();
if(nx.equals("END")) {
break;
}
System.out.println(nx);
}
Just remove while loop
public static void main(String[] pars) {
System.out.println("Insert something.");
Scanner read = new Scanner(System.in);
String s = "";
System.out.println(read.next());
System.out.println("End of program");
}
Or if u want display certain no.of string then mention condition properly.
public static void main(String[] pars) {
System.out.println("Insert something.");
Scanner read = new Scanner(System.in);
String s = "";
int i=0;
while(i<5) {
System.out.println(read.next());
i++;
}
System.out.println("End of program");
}
I am playing with Java and want to do a simple while loop that keeps going until the user presses ctrl+z.
I have something like this:
public static void main(String[] args) {
//declare vars
boolean isEvenResult;
int num;
//create objects
Scanner input = new Scanner(System.in);
EvenTester app = new EvenTester();
//input user number
System.out.print("Please enter a number: ");
num = input.nextInt();
while() {
//call methods
isEvenResult = app.isEven(num);
if(isEvenResult) {
System.out.printf("%d is even", num);
} else {
System.out.printf("%d is odd", num);
}
}//end while loop
}//end main
I tried while( input.hasNext() ) { ... but the code inside the while loop wouldn't execute.
//input user number
System.out.print("Please enter a number: ");
do {
try {
num = input.nextInt();
} catch (Exception e) {
break;
}
// call methods
isEvenResult = app.isEven(num);
if (isEvenResult) {
System.out.printf("%d is even", num);
} else {
System.out.printf("%d is odd", num);
}
} while (true);
When the user writes something non-numeric, the loop breaks.
while (num != 'z')
Although if you are expecting a 'z' why are doing input.getInt()?
You may want to check out the Console class too.
If you want to loop until the user has to force break via Ctrl+Z, then just do while(true). But you want your nextInt() to be inside the loop, and maybe also your prompting statement.
TrueSoft's solution is dead on. The reasons it may not be working for the asker is are kinda outside the scope of the program.
The program works for me: I'm running it under Linux and enter Ctrl-D as the first thing on a line. Ctrl-D is end-of-file for Linux the same way that Ctrl-Z is for Windows. Program stops dead in its tracks, perfectly.
The Windows console (the black DOS box, whatever you want to call it) has a wrinkle: It reads input line-by-line. It won't see the Ctrl-Z until it's read the line, so it needs an Enter keyin before it will see the Ctrl-Z.
I'm unwilling to fire up Windows just to try this, but my guess is that CTRL-Z followed by the Enter key (just like after the number entries) should cause the program to stop cleanly.
There are system-y ways to make a Java program work on a character-by-character basis so you can handle any characters directly and respond immediately to Ctrl-Z. But that's advanced stuff and doesn't belong in a simple programming exercise like this. I think Ctrl-Z / Enter is an acceptable way to have the program end.
You need to implement KeyBindings. Then you can make the determination to exit based off of what keys were pressed.
you are doing the input outside the loop,and it will run for only once.
System.out.print("Please enter a number: ");
num = input.nextInt();
Put your above code inside the loop.
Since you are having a system out inside the loop you will also come to know whether the control went inside the loop, obviously it should.
Also, try
while(true)
I wonder if while() alone is working.
This looks like Exercise 6.16 out of Deitel's book Java How to Program, 9th Edition.
The CTRL-Z charcter does, indeed, end input on a Windows platform just as CTRL-D ends input on most any UNIX or Linux platform.
Also, there are logic errors in the construction of the program that indicate Scanner methods and the System.in byte stream (i.e. the standard input from the console) are not well understood.
In your posted program, the statement:
num = input.nextInt();
executes unconditionally. It will block execution until some kind of input is received. If the input is not an integer, it will throw an exception. If the input received is an integer, then num will be assigned the integer value and the integer in the input stream (input) will be discarded from the input stream. There may be remainaing stuff on the input line up to the end of line, depending on what the user typed in before hitting the enter key that ended the input line and placed it into the System.in byte stream that Scanner is scanning.
If you were to leave your program as written except for putting input.hasNext() into the while statement's test condition, it would block until more input was in the input stream after the integer that nextInt() processed.
Some answer(s) suggest using KeyBindings as a solution. Whilst that may work, it gets into waiting for keypress events at nearly the hardware level and is NOT friendly to platform independence. It is a potential rabbit-hole into Alice's Wonderland for having to figure out all kinds of event processing and the code having to know what platform it is running on. Using the hasNext() boolean false return to indicate the end of the input stream should work on any platform and will avoid potentially non-portable gee-whiz code for processing the keyboard and key presses at nearly the hardware event level.
The following program is one that does what you (and the exercise) intended and will end the input if the user presses CTRL-Z on a Windows platform or a CTRL-D on a UNIX/Linux platform without you having to determine the platform on which the code is executing.
// Exercise 6.16: EvenOrOddTest.java
// Write a method isEven that uses the remainder operator (%)
// to determine whether an integer is even. The method should
// take an integer argument and return true if the integer is
// even and false otherwise. Incorporate this method into an
// application that inputs a sequence of integers (one at a time)
// and determines whether each is even or odd.
import java.util.Scanner;
public class EvenOrOddTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int integer;
System.out.println("Odd even integer test.");
System.out.printf("Input CTRL-Z on Windows or CTRL-D on UNIX/Linux to end input\n"
+ "or an integer between values\n"
+ "%d and %d\n"
+ "to test whether it is odd or even: ",
Integer.MIN_VALUE, Integer.MAX_VALUE);
// the input.hasNext() will block until
// some kind of input, even a CTRL-Z,
// arrives in the stream
// the body of the while loop will execute
// every time input appears for as long as the input
// is not a CTRL-Z
while (input.hasNext()) { // repeat until end of input
// prompt user
// now see if the input we did get is an integer
if (input.hasNextInt()) { // we got an integer...
integer = input.nextInt();
System.out.printf("\n%d is "
+ (EvenOrOdd.isEven(integer) ? "even.\n\n" : "odd.\n\n"), integer);
} else { // we got a non-integer one too large for int
System.out.printf("\nInput %s invalid! Try again...\n\n", input.next());
} // end if...else
// white space (i.e. spaces and tabs) are separators
// next and nextInt get only to the first separator
// so it is possible for the user to enter an integer
// followed by tabs and/or spaces followed by more
// input, integer or not up to the end of the input line
// input.nextLine() flushes everything not processed
// by the nextInt() or next() to the input line end
// won't block execution waiting for input
// if there is nothing left on the input line
input.nextLine();
// prompt for user input again
System.out.printf("Input CTRL-Z to end input\n"
+ "or an integer between values\n"
+ "%d and %d\n"
+ "to test whether it is odd or even: ",
Integer.MIN_VALUE, Integer.MAX_VALUE);
} // end while
} // end main
static boolean isEven(int integer) {
// integer modulus 2 is zero when integer is even
return ((integer % 2) == 0);
} // end isEven
} // end class EvenOrOddTest