I am finishing an assignment for Introduction to Java and have been stuck for hours.
When I run the code below, enter the integers and hit enter, I do not get anything in the output. Please help!
import java.util.Scanner;
public class U3A1_DebugFixIFStmts {
public static void main(String[] args) {
System.out.println("If Statements");
Scanner input = new Scanner(System.in);
// Prompt User to Enter Three Integers
System.out.print("Enter three integers: ");
int firstChoice = input.nextInt();
int secondChoice = input.nextInt();
int thirdChoice = input.nextInt();
//Determine & print the state of choices made
if (firstChoice == 0)
{System.out.println("State of choices: \n" +
"no choices made yet");}
else if (secondChoice == 0)
{System.out.println("State of choices: \n" +
"user made first choice (" + firstChoice + ")\n" +
"number of choices = 1");}
else if (thirdChoice == 0)
{System.out.println("State of choices: \n" +
"user made first choice (" + firstChoice + ")\n" +
"user made second choice (" + secondChoice + ")\n" +
"number of choices = 2");}
else
{System.out.println("State of choices: \n" +
"user made first choice (" + firstChoice + ")\n" +
"user made second choice (" + secondChoice + ")\n" +
"user made third choice (" + thirdChoice + ")\n" +
"number of choices = 3");}
}
}
int firstChoice = input.nextInt();
int secondChoice = input.nextInt();
int thirdChoice = input.nextInt();
These three lines of your codes require your input before your program moves ahead. Hence, give 3 numbers and then you'll see it work.
Related
I have this celebrity guessing game where the user has to guess a celebrity’s name, given only a portion of the letters in the name.
I give the player the “clue” (e.g.rge oney) and read in their guess. The program should have a loop that allows them to keep guessing. If they guess incorrectly 3 times, give them a hint If they guess incorrectly a fourth time (after the hint), they lose the game (and you should tell them who the celebrity was).
I'm having trouble with the loop. this is what I have so far.
System.out.println("Celebrity Guessing Game");
String celeb = "John Lennon";
System.out.print("Choose your difficulty (easy/medium/hard): ");
String difficulty = input.nextLine();
int maxtry = 3;
if (difficulty.equals("easy"))
{
System.out.println("Here is your clue: " + celeb.substring(1, 4) + " " + celeb.substring(5,10));
}
else if (difficulty.equals("medium"))
{
System.out.println(("Here is your clue: " + celeb.substring(0, 3) + " " + celeb.substring(4,9)));
}
else if (difficulty.equals("hard"))
{
System.out.println(("Here is your clue: " + celeb.substring(2, 4) + " " + celeb.substring(5,7)));
}
System.out.print("What is your guess? ");
String guess1 = input.nextLine();
System.out.println("guess1 = " + guess1 + " celeb = " + celeb );
while (!guess1.equals(celeb) && maxtry == 3 ) {
if (!guess1.equals(celeb) && maxtry == 3) {
maxtry--;
System.out.println("Try Again." + " Number of guesses left : " + maxtry);
}
if (guess1.equals(celeb) || guess1.equals("john lennon")) {
System.out.println("Good Guess, you are correct!");
}
This is my output:
Celebrity Guessing Game
Choose your difficulty (easy/medium/hard): easy
Here is your clue: ohn Lenno
What is your guess? john lennon
guess1 = john lennon celeb = John Lennon
Try Again. Number of guesses left : 2
Good Guess, you are correct!
^ Why is it going through both if statements??
The problem is in checking condition. It have following problems:
It should be maxtry > 0 instead of maxtry == 3
Instead of equals() use equalsIgnoreCase()
Following is corrected code snippet:
while (!guess1.equalsIgnoreCase(celeb) && maxtry > 0 ) {
if (!guess1.equalsIgnoreCase(celeb) && maxtry > 0) {
maxtry--;
System.out.println("Try Again." + " Number of guesses left : " + maxtry);
}
Note: You are not reading input from user for other tries.
I am a beginner and I am trying to make a simple calculator program using double variables, so that it allows users to add both int and double numbers to calculate. But whenever the user enters a String, the program fails. I have tried a lot to resolve this simple issue. I hope someone can help me.
Please enter first number: So when the user enters 25/25.5 everything works, but when user enters a letter such as e/f/k etc, the program fails. I have tried the following code after "Please enter first number":
if (user1 == aswin.nextDouble())
{
System.out.println("Continue");
}
else (user1 == Double.parseDouble(str))
{
System.out.println("Invalid Entry - Please enter Only numbers");
}
Following are the actual program, without the above code:
import java.util.Scanner;
import java.text.NumberFormat;
public class NewTwo_Calculator_IF_Statement {
public static void main (String [] args)
{
Scanner aswin = new Scanner (System.in);
double user1 = 0, user2 = 0, mult, div, sub, ad;
char user3;
boolean run = true;
String user;
System.out.println ("Welcome to ASWINS calculator" + '\n');
System.out.print ("Please enter First number - ");
user1 = aswin.nextDouble();
System.out.print("Please Enter Second number - ");
user2 = aswin.nextDouble();
System.out.println ('\n' + "Please choose following options" + '\n');
System.out.println ("Type either A/a/+ for Addition ");
System.out.println ("Type either S/s/- for Substraction");
System.out.println ("Type either D/d or / for Division ");
System.out.println ("Type M/m/* for Multiplication");
user3 = aswin.next().charAt(0);
mult = user1*user2;
ad = user1+user2;
sub = user1-user2;
div = user1/user2;
if (user3 == ('*') || user3 == ('m') || user3 == ('M'))
{
System.out.println('\t' + "Multiplication of " + user1 + " and " +user2 + " is = " + mult + '\n');
} else if (user3 == ('+') || user3 == ('a') || user3 == ('A'))
{
System.out.println ('\t' + "Addition of " + user1 + " and " +user2 + " is = " + ad + '\n');
} else if(user3 == ('-') || user3 == ('s') || user3 == ('S'))
{
System.out.println ('\t' + "Substraction of " + user1 + " and " +user2 + " is = " + sub + '\n');
} else if (user3 == ('/') || user3 == ('d') || user3 == ('D'))
{
System.out.println ('\t' + "Division of " + user1 + " and " +user2 + " is = " + div + '\n');
} else
{
System.out.println('\t' + "Invalid Input");
}
System.out.println ("Please Enter 'e' or type 'exit' to exit the program OR type anything else to stay on the page" + '\n');
user = aswin.next();
if (user.equalsIgnoreCase("e") || (user.equalsIgnoreCase("exit")))
{
System.out.println("Thanks for Entering -> " + user + " <-");
System.out.println ("You QUIT the page, Thanks and Hope you will use my(Aswin's) Calculator again");
System.exit(0);
}
else
{
System.out.println("Thanks for Entering -> " + user + " <-");
System.out.println (" You are STAYING on the page, Thanks " + '\n');
System.out.println ( "Thank you so much for using my calculator");
}
}
}
On the official documentation, it is mentioned that .nextDouble() throws a InputMismatchException when the next token (user input) does not match a float (such as when the user inputs a letter). You can handle such exception by using a try catch block:
try{
user1 == aswin.nextDouble()
}catch(InputMismatchException e){
// User input is invalid
System.out.println("Invalid Entry - Please enter Only numbers");
}
You can read more about catching and handling exceptions here.
I've written a code for a game that simulates the user and the computer rolling a die and the winner receives 1$ from the loser, with each starting with 2$. The code runs fine, but it doesn't end when either the user or computer reaches 0$ like i had anticipated. Any suggestions?
import java.util.Scanner;
public class ALE_04_RollDice {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")); {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
}while (userMoney >= 0 || compMoney >=0);
}}
Your while statement is testing for <= 0, but initially both variables are > 0. The while loop will never fire.
First off you have a problem with your while condition money values = 2 for player and comp, so while will never fire..fix that and you could use a do while
do{
statement(s) //block of statements
}while (Boolean expression);
So inside your do{} you could have your statements and conditions..so it will do whatever is inside those braces until the condition inside the while() is met
for example
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
You are using the incorrect condition in the while statement.You are testing if any player has >=0 this will always test true and cause an infinite loop. Instead test if BOTH players have >0 and end the game if not.
Also you have a ';' after you if statement. That will cause the code after it to execute all the time.
Here is complete working code:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")) {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
//prompt user to type 'r' to roll again
System.out.println("\n\nPress 'r' if you would like to roll ");
}while (userMoney > 0 && compMoney >0);
System.out.println("\n\nGAME OVER!!!");
}
}
//end main
You want to stop when less than or equal to but you have greater than or equal to.
while (userMoney >= 0 || compMoney >=0) {
Cause of problem:
Your while loop does not run at all, because the condition inside is initially evaluated as false.
while (userMoney <= 0 || compMoney <=0)
This reads: whilst the user has a money less than or equal to 0 OR whilst the computer has money less than or equal to 0 then run the while loop, this will never initially be true as they both the computer and user both start with $2, hence userMoney == 2 and compMoney == 2.
Solution:
Change the condition of the while loop to the following:
while(userMoney>0 || compMoney>0)
then add an if statement which says if the compMoney == 0 or if the userMoney == 0, then break out of the while loop.
if(userMoney == 0 || compMoney == 0){
break;
}
I am new to Java and I am doing some exercises, I created an if statement and else if so that when the user clicks 2 it will start the program from the start.
The problem is at the else if (yesNo == 2), I don't know what kind of code should I write there to start the program from the start. Can anybody help me? thank you.
if (option == 1) {
System.out.println("1: DAF");
System.out.println("2: Mercedes-benz");
model = in.nextInt();
if (model == 1) {
System.out.println("Model: " + mixer2.getModel());
System.out.println("Age: " + mixer2.getAge());
System.out.println("Cost: " + mixer2.getCost());
System.out.println("Capacity: " + mixer2.getCapacity() + " squares meters");
System.out.println("For how long do you want the vehicle to hire?, maximum is 12 months and every month cost 4000");
hireVehicle = in.nextInt();
cost = 4000 * hireVehicle;
System.out.println("The total cost is " + cost + " Do you want to proceed?");
System.out.println("1: yes");
System.out.println("2: no");
yesNo = in.nextInt();
if (yesNo == 1) {
System.out.println("Now, please enter your first name to complete the contract");
String name = in.next();
System.out.println("CUSTOMER CONTRACT");
System.out.println("Customer name: " + name);
System.out.println("Duration: " + hireVehicle + " months");
System.out.println("Date: " + date.date1());
}
else if (yesNo == 2){
}
You could use a loop like this one :
boolean repeat = True;
while (repeat)
{
if (yesNo ==1)
repeat = False;
else if (yesNo == 2)
repeat = True;
}
It might be easier with a do while loop, but i heard they're dirty
I have a problem with the following code
public static void SideBet(int numberDice,int bet,int money) {
System.out.println("You established a " + "\""+ "point" + "\"" + ". " + "Your " + "\""+ "point" + "\"" + " is " + numberDice + ". " + "You have to roll a(n) " + numberDice + " to win your bet, "+ bet +" chips." );
System.out.println();
System.out.println("You can put side bets for 4,5,6,8,9 or 10.");
SideBetChoice = Console.readLine("Would you like to make any side bets ? (Type " + "\""+ "Yes" + "\"" + " or "+ "\""+ "No" + "\"" + ", then hit Enter.)");
int s = 0;
int r = 0;
if (SideBetChoice.equals("Yes")) {
System.out.println("You can put as many side bets as you would like for the numbers 4,5,6,8,9 or 10.");
int SideBetNumber = Console.readInt("How many side bets would you like to make ? (Introduce a number, minimum 1, maximum 6.)");
int[] SBNArray = new int[SideBetNumber];
int[] sbArray = new int[SideBetNumber];
for (s = 0; s <= (SideBetNumber -1) ; s++) {
SBNArray[s] = Console.readInt("On which number would you like to put a side bet ?");
sbArray[s] = Console.readInt("Currently you have " + money + " chips, how much would you like to bet ?");
money = money - sbArray[s];
System.out.println("Thank you for your " +sbArray[s]+ " chip side bet on number " +SBNArray[s]+".");
System.out.println();
}
}
if (SideBetChoice.equals("No")) {
return;
}
sbArray and SBNArray does not get a value and it keeps crashing ...
Can anyone help me out and tell me what is wrong, why the 2 arrays do not get a value, therefor they are null ?
There is no readInt()-method in Console.
Also I'm not sure if you're using console correctly, it should look like this:
Console console = System.console();
console.readLine("Type something");
Just use readLine() and convert it to an int:
Console console = System.console();
String input = console.readLine("Type a number");
try
{
int myNumber = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
System.out.println("This ain't a number!");
}
Also please never use Capital Letters for Variables' Names or method-names, it's very confusing because you could think it would be a Class or a Type.
So please change the name of SBNArray and SideBetNumber, SideBetChoice etc. etc.
Only Constants should be written with only Capital Letters and Classes and Types start with Capital Letters.
EDIT:
Sorry, it seems that you're using BreezyGUI.Console, therefore there is a readInt()-method.
Could you give more information?
I'd like to know if the text of the readInt() is even displayed.