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');
}
Related
Why does the code break when the default case of the switch function is used.
import java.util.Scanner;
public class Main {
static void checkCommand(String command)
{
switch (command) {
case "add" -> System.out.println("added");
case "access" -> System.out.println("accessed");
case "compare" -> System.out.println("compared");
default -> {
System.out.println("Invalid command, please try again");
enterCommand();
}
}
}
static void enterCommand(){
System.out.print(">>> ");
Scanner usrInput = new Scanner(System.in);
String input = usrInput.nextLine();
while (!input.equals("quit")){
checkCommand(input);
System.out.print(">>> ");
input = usrInput.nextLine();
}
}
public static void main(String[] args) {
enterCommand();
}
}
When I enter in "add", "compare", or "access", and then "quit", the program works as intended, but if I enter in anything that is incorrect where it uses the default case, the program breaks and repeatedly asks for input even if the input is "quit". I have tried a few different things to fix it and nothing has worked. I'm trying to keep the switch statement but if there isn't a way to keep it and have the program run as intended I am open to other options.
Your code works for me. The only problem is that I have to enter quit twice, after entering an invalid command, in order for the program to terminate.
Here is output from a sample run of the exact same code as in your question:
>>> access
accessed
>>> add
added
>>> george
Invalid command, please try again
>>> compare
compared
>>> quit
>>> quit
I am required to enter quit twice because method enterCommand is being called from method checkCommand. You don't need to do this. The while loop, in method enterCommand will ensure that the user is prompted again to enter a command – even after [s]he has entered an invalid command.
Calling enterCommand from checkCommand means that you are essentially calling enterCommand recursively. In the above output, I needed to enter quit twice, since I only entered a single, invalid command. I suggest that you run your code in a debugger to understand why you get this behavior.
As #OldDogProgrammer wrote in his comment to your question, you should create a Scanner object only once rather than each time method enterCommand executes.
As #MadProgrammer wrote in his comment, a do-while loop may be more appropriate than a plain while loop.
Also, quit is not an invalid command so I think that you need to handle that command in method checkCommand and the handling is that you just ignore the command. Since you are using switch expressions, I couldn't find a way to "ignore" a case so in the below code I simply print an empty string. Alternatively, you could print an appropriate message such as Good bye, for example.
import java.util.Scanner;
public class Main {
private static Scanner usrInput;
static void checkCommand(String command) {
switch (command) {
case "add" -> System.out.println("added");
case "access" -> System.out.println("accessed");
case "compare" -> System.out.println("compared");
case "quit" -> System.out.print("");
default -> {
System.out.println("Invalid command, please try again");
}
}
}
static void enterCommand() {
String input;
do {
System.out.print(">>> ");
input = usrInput.nextLine();
checkCommand(input);
} while (!input.equals("quit"));
}
public static void main(String[] args) {
usrInput = new Scanner(System.in);
enterCommand();
}
}
Here is the output when I ran the above code:
>>> access
accessed
>>> add
added
>>> George
Invalid command, please try again
>>> compare
compared
>>> quit
As you can see, I only need to enter quit once.
You need to understand the recursive mechanism.
When the latest recursive has done, it needs to do the remaining tasks from previous recursive. I added comments into your code to explain:
static void checkCommand(String command){
switch (command) {
// ...
default: {
System.out.println("Invalid command, please try again");
enterCommand(); // recursive is calling here.
}
}
}
static void enterCommand(){
System.out.print(">>> ");
Scanner usrInput = new Scanner(System.in);
String input = usrInput.nextLine(); // time 1: input: test | time 2: input: quit -> done recursive 1.
while (!input.equals("quit")){
checkCommand(input); // time 1: go to default and call recursive, go to input time 2
System.out.print(">>> "); // Do the remaining task from time 1. In case you input time 3: "quit". the program will exit.
input = usrInput.nextLine();
}
}
The more recursives are called, the more remain tasks need to do. In your code, to quit the program, you need to type "quit" (n + 1) times if the recursive is called n times
Solutions: To quit immediately after typing "quit" in the first time, just remove the recursive call.
default: {
System.out.println("Invalid command, please try again");
}
So basically I'm trying to make a minigame only using IF statements and in a single class, and everything is working smoothly so far. My biggest issue is, the "back" prompt. I tried system.exit(0), but since it kills the program, that won't be an answer. my question is, how do you "re-run" the class? For instance, when you are in the "options" menu, how do you go back in the main menu?
import java.util.Scanner;
public class Main {
public static void main (String[]args)
{
//Main Menu Prompt.
System.out.println ("Welcome to my mini parkour game!");
System.out.println ("Decide which trick to use, and don't mess up!");
System.out.println ("Choose one: Play, Quit");
Scanner bruh = new Scanner (System.in);
String MainMenu = bruh.nextLine ();
// Quit Prompt.
if (MainMenu.equals ("Quit"))
{
System.out.println ("You have quit the game.");
System.exit (0);
}
// Play Prompt.
if (MainMenu.equals ("Play"))
{
System.out.println ("Proceed to level 1, 2, 3, 4, 5, 6, 7, 8, 9, 10");
Scanner playgame = new Scanner (System.in);
String LevelSelect = playgame.nextLine ();
if (LevelSelect.equals ("1"))
{ System.out.println("You have reached this block of code!");
}
}
//code block to remind that java is case sensitive.
else {
System.out.println("error, try picking one again. (case sensitive.)");
return new Main();
}
}
}
I wanted the output to be at the main menu prompt even when you are from the play prompt, without killing the program.
I believe a while loop controlled by your user input stored in a variable will do the magic. You will have to learn how to use while loops.
If you want to advance to a God-level Java programmer use enum where you define your states and then create inside while loop a state machine using switch-case.
I am too lazy to type a working code here from my phone but something like that on a high level:
enum State { PLAY, QUIT };
public static void main(String[] args) {
boolean runAgain=true;
State state;
while (runAgain) {
//get the input from user
//update state
switch(state) {
case PLAY :
// update state
break;
case QUIT:
// update STATE
break;
//case WHATEVERELSE...
default:
assert false : "never get here";
}
}
}
It is a bit of learning and reading java specs involved, but Hey, after doing that you'll be able to program a working algorithm for .... an ELEVATOR!
Good luck!
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.
I've simplified the issue to the code below.
When ran, you see a message.
If you use the mouse and click on 'ok', then you can continue to type new commands.
If you press 'enter' or 'space' on the keyboard, then keyboard input breaks. I.e one can type things into the command line but a 'return' doesn't do anything.
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class MainClass {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("hello, please enter your command");
String UsrCmd = sc.nextLine();
System.out.println("you tyep: " + UsrCmd);
JOptionPane.showMessageDialog (null,"Dialog Text","Title Text",JOptionPane.QUESTION_MESSAGE);
//Work around for Linux users:
//Runtime.getRuntime().exec("/usr/bin/zenity --info --text='hello'");
}
}
}
(I'm new to S.o.f. I apologize for mistakes in advance. Please kindly correct me where I make them. Thank you).
JR 1.7 Fedor 20 64bit.
It should work normally, since you dont have any statement that could stop the while execution, or a break; command. However, I would advice you to use JDK(java developer kit) instead of JRE.
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