How to break else statement and exit the program - java

package oddsorevens;``
import java.util.Scanner;
import java.util.Random;
public class OddsOrEvens
{
public static void main(String[] args)
{
Scanner name= new Scanner (System.in); // getting input from user
System.out.print("Hi! What's your name: ");
String user = name.nextLine(); // getting user name
System.out.println("Hello: "+user);
System.out.println("Let's play OddsOrEvens");
System.out.println("Choose Odd or Even");
String s ="oddOrEven";
Scanner str = new Scanner(System.in); // getting new string from user
String s1 = str.next(); //storing odd or even here
o:
if (s1.equals("even")||(s1.startsWith("e")))
{
System.out.println("You choose even");
System.out.println("Computer choose odd");
}
else if (s1.equals("odd")||(s1.startsWith("o")))
{
System.out.println("You choose odd");
System.out.println("Computer choose even");
}
else
{
System.out.println("Entered wrong keyword");
}
System.out.print("How many fingers you want to put out: ");
Scanner num = new Scanner(System.in);
int n=num.nextInt();
Random rand = new Random();
int computer = rand.nextInt(6);
System.out.println("Computer choose "+ computer +" fingers");
int sum;
sum=n+computer;
System.out.println(sum);
if(sum%2==0)
{
System.out.println(sum+" is even");
}
else
{
System.out.println(sum+" is odd");
}
int u = s1.length();
if(u/2==0)
{
System.out.println("You won :)");
}
else
{``
System.out.println("You lose :(");
}
}
}
This is my first pgm in java. here if the user enter wrong keyword pgm should be break and based on the user input the output of the pgm will be win or lose. help please.

Whenever you want your application to stop, you have to explicitly tell that you want to exit. To do so you have write just piece of line of code and that is System.exit(0)
Here sample code to understand it better:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
if (s.next().equals("o")) {
System.out.println("game is still on");
} else {
System.out.println("game end!");
System.exit(0);
}
}

Related

NoSuchElementException error for ATM Machine app (Modified)

I am currently learning Java and I am trying to retain the information I learned by building a ATM machine app (I plan on adding more to it in the future).
My current issue is I would like to ask a user 'What would you like to do' repeatedly until a valid input is provided(current valid inputs are 'Withdraw' and 'Deposit').
I have a loop that will repeatedly ask the user 'Please select a valid choice' if the input is not valid. If the input is valid it will execute only once, ask 'What would you like to do', and then display a NoSuchElementException. Not sure how to fix this.
Here is my code:
App.java
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("What woul you like to do?");
String response = scanner.next().toLowerCase();
Transactions newTransaction = new Transactions();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
} else if (response.equals("deposit")) {
newTransaction.Deposit();
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}
Transactions.java
import java.util.Scanner;
public class Transactions {
private int currentBalance = 100;
public void Withdrawal() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to withdraw?");
int withdrawAmount = scanner.nextInt();
if (withdrawAmount > 0) {
if (currentBalance > 0) {
currentBalance -= withdrawAmount;
System.out.println("Amount withdrawn: $" + withdrawAmount);
System.out.println("Current Balance: $" + Balance());
if (currentBalance < 0) {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println("Can't remove 0 from account");
}
scanner.close();
}
public void Deposit() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to deposit?");
int depositAmount = scanner.nextInt();
if (depositAmount > 0) {
currentBalance += depositAmount;
Balance();
}
System.out.println("Amount deposited: $" + depositAmount);
System.out.println("Current Balance: $" + Balance());
scanner.close();
}
public int Balance() {
return currentBalance;
}
}
Error Message
NoSuchElementException
You can use a sentinel. A sentinel is a value entered that will end the iteration.
//incomplete code showing logic
int choice;
Scanner input = new Scanner(System.in);
System.out.println("Enter Choice");
choice = input.nextInt();
while(choice != -1){ //-1 is the sentinel, can be value you choose
//Some logic you want to do
System.out.println("Enter choice or -1 to end");
choice = input.NextInt(); //notice we input choice again here
}
Like has been said you should learn about loops. There are two types while-loop and for-loop. In this case you should youse the while-loop.
The implementation of your problem could be this.
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("What woul you like to do?");
String response;
Transactions newTransaction = new Transactions();
while (true) {
response = scanner.next().toLowerCase();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
break;
} else if (response.equals("deposit")) {
newTransaction.Deposit();
break;
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}

How do I make sure my else statement is being read? -Brand new to Java

I'm brand new to coding and am trying to figure out why my else statement isn't working. I'm not sure if it is because of my boolean statement. I tried adding else as false for the boolean but that did not work.
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Are you exercising tonight?");
String answer = input.nextLine();
System.out.println("You said " + answer + " Are you sure?");
String answer2 = input.nextLine();
boolean Yes = true;
if (Yes) {
System.out.println("Good. That's what I wanted to hear");
} else {
System.out.println("WRONG ANSWER");
}
}
}
You need to set your Yes variable to the condition you want to check:
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Are you exercising tonight?");
String answer = input.nextLine();
if (answer.equalsIgnoreCase("yes")) {
System.out.println("Good. That's what I wanted to hear");
} else {
System.out.println("WRONG ANSWER");
}
}
}
If you want to make sure the user typed the right thing (the "Are you sure?" part), you can add a loop:
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String answer;
while (true) {
System.out.println("Are you exercising tonight?");
answer = input.nextLine();
System.out.println("You said " + answer + " Are you sure?");
String answer2 = input.nextLine();
// If the user is sure, break the loop
if (answer2.equalsIgnoreCase("yes")) break;
// Implicit else: ask the user again
}
if (answer.equalsIgnoreCase("yes")) {
System.out.println("Good. That's what I wanted to hear");
} else {
System.out.println("WRONG ANSWER");
}
}
}

How to make 'end game' method in java

so i made a game, in which user needs to guess the random number or letter. I want to make it so that when the user writes 'end game' during the game (when he guesses the number), he is being redirected to the menu (using the main(args); method). In fact, String value cannot be writen in int input. So when i write 'end game' during the game cycle, it just crashes. What should i do?
Heres code of my game:
import java.util.Scanner;
public class TwoGames {
public static void main(String[] args) { // main menu
Scanner scan = new Scanner(System.in);
System.out.println("Choose the game\n Type 'letter' or 'number' to choose the game");
String UserAnswer = "";
UserAnswer = scan.next();
if (UserAnswer.equalsIgnoreCase("number")) {
number(args);
}else if(UserAnswer.equalsIgnoreCase("letter")){
letter(args);
}
scan.close();
}
public static void letter (String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";
int numberOfTries = 0;
do {
System.out.println("Guess the Letter");
char randomLetter = (char) (Math.random() * 26 + 65);
char enteredLetter = 0;
while(true){
enteredLetter = Character.toUpperCase(scan.next().charAt(0));
numberOfTries = numberOfTries + 1;
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
break;
}
else if(enteredLetter>randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too high");
}
else if(enteredLetter<randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too low");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
public static void number(String[] args) { //heres the number guessing game
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";//variable to stop game
do {
int theNumber = (int)(Math.random() * 100 + 1);
int numberOfTries = 0;
do {
int guess = 0;
while (guess != theNumber) {
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt();
numberOfTries = numberOfTries + 1;
if (guess < theNumber)
System.out.println(guess + " is too low. Try again.");
else if (guess > theNumber)
System.out.println(guess + " is too high. Try again.");
else {
System.out.println(guess + " is correct. You win!");
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
}
}
} while (Stop.equalsIgnoreCase("end game"));
main(args);// this sends user to main menu
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
}
I am novice programmer, so yeah, thats might be a dumb question, because im learning. Anyway, any help and explanation would be useful.
To solve this problem, you should input a string, check if it equals to "End game" message and if not continue your code.
For example, replace this line:
guess = scan.nextInt();
In this code:
String input = scan.next();
if(input.equals("End game")){
main(args);
return;
}
guess = Integer.parseInt(input);
That code get a String input called input, check if he equals to "End game" and if not continue your guess loop.

Simple Java Guessing program. Continuing

I am just playing around with java and wanted to make a simple program where the user; me has to guess/type in the correct number until it's correct. What can I do so the program can keep running, printing out "Make another guess" until the user/me puts in the correct number. Maybe a boolean? I'm not sure. This is what I have so far.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
input.nextInt();
}
}
You might want to use a while loop to repeat some code:
while (value != myInt) {
System.out.println("Not yet! You entered: " + value + ". Make another guess");
value = input.nextInt();
}
System.out.println("You discovered me!");
This program would do the trick:
public static void main(String [] args){
int myInt = 2;
int value = 0;
Scanner input = new Scanner(System.in);
boolean guessCorrect = false;
while(!guessCorrect){
System.out.println("Not yet! You entered:" + value + " Make another guess");
value = input.nextInt();
if(value == myInt){
guessCorrect = true
}
}
System.out.println("You discover me!");
}
Simply introduce a loop.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
for(;;) {
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
break;
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
}
}
}
}

How to ask user to Play Again....Guess Game

I'm making a simple guess game but I don't know how to ask the player if the want to play the game again.Everytime the game ends I have to run the game again so I want to add this feature to it.I looked in some other posts but they didn't help.Here's the code:
import java.util.*;
public class guessNumber{
private static Scanner userInput = new Scanner(System.in);
public guessNumber(){
System.out.println("~~~Guess Game~~~");
}
public void guessGame(){
System.out.println("Enter the maximum number:");
int maxNum = userInput.nextInt();
System.out.println("Guess a number between 0 and " + maxNum + ":");
int randomNumber = (int) (Math.random() * maxNum);
boolean gameOn = true;
int numberOfTries = 0;
while(gameOn){
boolean printOthers = true;
numberOfTries++;
int number = userInput.nextInt();
if(number > maxNum){
System.out.println("Please enter a number between 0 and " + maxNum + ".");
printOthers = false;
}
if(printOthers){
if(number == randomNumber){
System.out.println("=================================");
System.out.println("You guessed the right number xD.");
System.out.println("Your tried " + numberOfTries + " times.");
System.out.println("=================================");
}else if(number > randomNumber){
System.out.println("Try a lower number");
}else if(number < randomNumber){
System.out.println("Try a higher number");
}
else{
System.out.println("Please enter a number between 0 and " + maxNum + ".");
}
}
}
}
public static void main(String[] args){
guessNumber guess = new guessNumber();
guess.guessGame();
}
}
In your main use a while loop. In the loop first call your guessGame() then, similarly to how you ask to enter a number, you ask if they want to play again (Y/N ?) and if they say no you break the loop otherwise you go ahead...
Add your calling method in main method with in a while loop
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
do{
//call your game
System.out.println("Do you want to play again. Press y");
}
while(scanner.next().equals("y"));

Categories