I've recently started studying Java and I already had my first problem. Currently I'm making a text adventure game (written in Java) and I can't continue because the program is printing out two lines but that I don't want it to. I don't how I can make it print out only one line.
In the last bit of the program there is a system.out.print("hello")
import java.util.Scanner;
public class TextAd2 {
Scanner sc = new Scanner(System.in);
//Name
String Pname;
public static void main(String[] args) {
//connection
TextAd2 con;
con = new TextAd2();
con.info();
con.start1();
}
public void info() {
System.out.println("Hello!");
System.out.println("Your Name? ");
Pname = sc.nextLine();
System.out.println("Hello " + Pname);
System.out.println("Wana Start The Game or Stop?");
String text1 = sc.nextLine();
switch (text1) {
case "Start":
start1();
break;
case "Stop":
System.exit(0);
break;
default:
System.out.println("Unknown Command.");
}
}
public void start1()
{
//it starts to print this twice
System.out.println("hello");
}
}
I actually don't think that the system.out.print is the problem, maybe the program is just reading the 'start1()' twice that's why it's printing "hello" two times. I did this in an if else statement and it's doing the same thing too. I don't know the code to how to prevent this either way. I am doing something wrong but I don't know what is the probelm
You can calling twice con.start1();
Once in your main():
con.info();
con.start1();
And the second time in your switch:
case "Start":
start1();
break;
At first, the execution reaches this line:
con.info();
So info starts running. Then execution reached:
case "Start":
start1();
break;
So start1 starts executing and prints Hello.
However, remember that the deepest call stack is still on the info method. After printing Hello, start1 returns it is popped from the call stack. break; then runs and info also pops from the call stack. Now, we will go to the next line after info(), which is start1!
That's why it is printing twice. To stop this, simply remove start1 from the main method,
Related
I'm a beginner at Java and I want to get into it and I enjoy playing around with it. So I started doing an online course.
So after a few videos I learned a bit about switch statements and wanted to know how to loop them effectively.
package v1;
import java.util.Scanner;
public class Computer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Computer is booting up...");
System.out.println("Welcome to Mindows '93, please enter a command.");
String command = input.nextLine();
boolean computerON = true;
while (computerON) {
switch (command) {
case "!music":
System.out.println("Playing music!");
break;
case "!browse":
System.out.println("Launching browser...");
break;
case "!help":
System.out.println("Here are the commands that can be used !music, !browse, !shutdown");
break;
case "!shutdown":
System.out.println("Shutting down Mindows, goodbye!");
break;
default:
System.out.println("Command not recognised, type !help for a list of commands...");
break;
}
if (command.equals("!shutdown")) {
computerON = false;
}
}
}
}
So basically what I want is to make a mock text-based OS called Mindows with very limited functionality, but I'm having problems.
When I input !music, the program will constantly spam lines of "Playing music!"
When I enter !shutdown, however, it terminates which is what I want.
What I want is to type !music, !browse, !help and (x) to get the default message without the program spamming lines OR terminating.
I want to be able to type these commands in constantly until the !shutdown command is issued.
You read the command only once, out of your loop.
Try moving the line:
String command = input.nextLine();
into the while loop.
You're going into an infinite loop because you are accepting input from the user before the loop, and the input doesn't change during the execution of the loop. So if you entered "!music", the command doesn't change throughout the loop and the switch statement always goes into case "!music": in each iteration of the loop, which is why computerON is always true and the loop executes and prints "Playing music" infinitely.
The solution to this would be to move the String command = input.nextLine(); statement inside the while loop, like the above answers say.
Changed your logic here :
boolean computerON = true;
while (computerON) {
String command = input.nextLine();
switch (command) {
case "!music":
System.out.println("Playing music!"); break;
case "!browse":
System.out.println("Launching browser...");
break;
case "!help":
System.out.println("Here are the commands that can be used !music, !browse, !shutdown");
break;
case "!shutdown":
System.out.println("Shutting down Mindows, goodbye!");
break;
default:
System.out.println("Command not recognised, type !help for a list of commands...");
break;
}
if (command.equals("!shutdown")){
computerON = false;
}
}
I have no code to paste since all I have is a template of my methods to be used. Hopefully this isn't too broad because I've looked all over and haven't received the answer I'm needing.
Many have seen or heard of a "Magic 8 Ball" program. A user asks a question, and they receive a random answer in return. I could have written the code easily with one method, but now we've delved into using multiple methods and I'm missing a piece of the puzzle.
The rules of this program:
1) I have to create at least three methods: the main, an input method, and an output method.
2) I have to use a switch statement for the random answers.
3) I have to use a while loop (or a do-while) to prompt the user to either ask another question, or quit.
I think my only problem lies in where to place each piece of the code. I'm going to need to call a Scanner. That's no big deal. I know how to do the switch statement. I know how to randomize the output. I'm most likely going to use a boolean for the keep going/quit part. But where do I actually PLACE the scanner? The boolean? In the main? In an input method? What about the processing section for the randomization? Are all my variables declared in the main so they spread throughout?
I hope my question makes sense.
Creating Scanner once either in main, or in the constructor as a class level object will be much cheaper than creating every time you call the input method. If created at class level it can be used directly in input method, otherwise if it is created in main method it can be passed as an argument to the input method.
Boolean can be in the input method because you are directly comparing the input and you have no more use for it.
When you have an object, especially an expensive one, it is better to create it only once wherever applicable, or create it as few times as possible.
Excuse my sloppy code, and ignore the case names. They are temporary since I will be renaming them. I tried every scenario after compiling. I asked a question, it answered, and it asked if I wanted to ask another. I asked another, it repeated the prompt. I answered "n", and it said "Thanks for playing. Goodbye", and stopped running. Here is my code. Problem solved.
import java.util.Scanner;
public class MagicBall {
public static void main(String[] args) {
int random = 0;
boolean playAgain = true;
while (playAgain) {
askAnother(random);
}//end while
}//end main
public static void askAnother(int r) {
System.out.print("Hello! What is your question? ");
Scanner input = new Scanner(System.in);
String question = input.nextLine();
String yes_or_no;
String next_question;
randomAnswer(r);
boolean playAgain = true;
while(playAgain) {
System.out.println("Would you like to ask another question? Y to ask, N to quit.");
yes_or_no = input.nextLine();
if (yes_or_no.equalsIgnoreCase("Y")) {
System.out.println("What is your next question?");
next_question = input.nextLine();
randomAnswer(r);
}//end if
else if (yes_or_no.equalsIgnoreCase("N")) {
playAgain = false;
System.out.println("Thanks for playing. Goodbye.");
System.exit(0);
}
else {
System.out.println("Invalid Input. Please enter Y or N.");
continue;
}//end else
}//end while
}//end input method
public static int randomAnswer(int r1) {
r1 = (int)(Math.random() * 9);
switch(r1) {
case 0: System.out.println("Yes"); break;
case 1: System.out.println("Yes1"); break;
case 2: System.out.println("Yes2"); break;
case 3: System.out.println("Neutral"); break;
case 4: System.out.println("Neutral1"); break;
case 5: System.out.println("Neutral2"); break;
case 6: System.out.println("No"); break;
case 7: System.out.println("No1"); break;
case 8: System.out.println("No2"); break;
}//end switch
return r1;
}//end output method
}//end MagicBall class
First thank you for reading. Also I'm very aware of how I can get this to work they way I want it to. I'm just experimenting and not getting expected results.
When I run this code I would expect that when I enter the letter X I would be asked
to try again and re-attempt to enter the letter B. Well, I am. However The program will then break to the start: label and process based on the new value of input we got in the
default case. If on my second attempt I enter the letter B, nothing gets executed in the
switch statement. If you enter the letter B on your second try, the program will print that you entered B and then the program will terminate. Why is this?
import java.util.Scanner;
public class Help
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter the letter B: ");
char input = kb.nextLine().charAt(0);
start:
switch(input)
{
case 'B':
System.out.println("Nice Work!");
break;
default:
System.out.println("Try again: ");
input = kb.nextLine().charAt(0);
System.out.println(input);
break start;
}
}
}
The labeled break statement is meant for terminating loops or the switch statement that are labeled with the corresponding label. It does not transfer control back to the label. Your switch statement is simply falling through to the end of program, as it should.
A labeled break would only be helpful if you had nested switch statements and needed to break out of the outer one from the inner one.
See this for further information.
Use while cycle:
import java.util.Scanner;
public class Help
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter the letter B: ");
while(true)
{
char input = kb.nextLine().charAt(0);
switch(input)
{
case 'B':
System.out.println("Nice Work!");
break;
default:
System.out.println("Try again: ");
}
}
}
}
In my code below im am tring to add a thread.sleep for when someone chooses the option to exit the lift, i am not sure whats wrong with the code i entered to make it sleep.I already included the Interrupted exception so can someone tell me where i went wrong.
import java.util.Arrays;
import java.util.Scanner;
public class username{
public static void main(String... args) throws InterruptedException {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
Thread.sleep(5000);
System.exit(0);
break;
}
You're ending your program after the sleep returns.
Thread.sleep(5000);
System.exit(0);
Maybe you're looking for a loop of some kind. You haven't shown us what comes after the switch, but maybe that System.exit(0), which stops the java process, shouldn't be there.
Get rid of the System.exit(0)
Wrap your method in a loop if you want it to loop. My example is an infinite loop, but if your application accepts user input you can just as easily have a boolean flag that serves as the loop condition.
public static void main(String... args) throws InterruptedException {
while(true){
//all of your code
}
}
Also you should surround your sleep in a try-catch instead of declaring a throws on your main method... it is good practice to catch exceptions you can handle, and throw exceptions that you cannot handle to earlier stack frames that can. Typically you don't want your main() method to have a throws clause as it can cause the premature termination of your application. This doesn't really matter for InterruptedException in your specific case, but does for many other exceptions.
I'm making a school assignment and this time around I thought about using a switch statement since it looked more efficient.
It's just something basic but if I enter a letter for example and after that number 1 for example it would return case 1 twice?
This is my code for the entire class so far:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
private int option;
public static void main(String[] args) {
Test t = new Test();
t.start();
t.optionMenu();
}
public void start() {
System.out.println("Make your choice:");
System.out.println("1: Play");
System.out.println("2: Options");
System.out.println("3: Exit");
}
public void optionMenu() {
try {
Scanner sc = new Scanner(System.in);
this.option = sc.nextInt();
System.out.println(this.option);
} catch (InputMismatchException e) {
System.out.println("Please enter a number");
optionMenu();
}
switch (this.option) {
case 1:
System.out.println("Game starting...");
break;
case 2:
System.out.println("Loading options");
break;
case 3:
System.out.println("Game exiting...");
System.exit(0);
break;
default:
System.out.println("Enter a valid number (1, 2 or 3");
break;
}
}
}
Any help would be much appreciated, thanks!
When you call sc.nextInt() without first asking if (sc.hasNextInt()), you are open to some strange behavior when end-users start typing unexpected input, such as letters. In this case the scanner would not advance its reading pointer, so your program will get stuck reading the same incorrect output.
To fix this issue, add a loop that "clears out" the invalid entry before attempting to read an int again, like this:
while (!sc.hasNextInt()) {
System.out.print("You need to enter an integer.");
sc.nextLine(); // Clear out the bad input
}
int val = sc.nextInt(); // At this point we know that sc.hasNextInt(), because that's the loop condition
Another point is that it is not a good idea to do with recursion what can be done with iteration: the recursive call to optionsMenu is going to accumulate as many levels of invocation as the number of times the end-user enters an incorrect value, so a very persistent user could theoretically force a stack overflow on your program by entering invalid data repeatedly.
Using the code fragment above would free you from the need to call optionsMenu recursively, and also from catching the input exception.
It's just something basic but if I enter a letter for example and after that number 1 for example it would return case 1 twice?
I'm not sure what you mean here. Firstly, your idea works, this code should be fine!
Second, if you enter anything besides just the number 1, 2, or 3, you will go to the "default:" block of code. Since you are prompting the user again if they fail, typing "a" or "a1" into the prompt just shows the menu again. The user needs to just type "1", "2", or "3" to successfully select a menu option.