Terminate program with letter Q - java

I'd like to terminate the program by typing Q whenever. I can't place it in "diceChosen" because it's an integer. I've tried different things but nothing works for me.
Scanner userInput = new Scanner(System.in);
int wins = 0;
int losses = 0;
int diceOne = 0;
int diceTwo = 0;
int diceThree = 0;
int sum = 0;
System.out.println("Välkommen till spelet 12. Du ska slå 1-3 tärningar och försöka få summan 12...");
for (int counter = 0; counter < 3; counter++) {
System.out.printf("%nAnge vilken tärning du vill slå[1,2,3](avsluta med q): ");
int diceChosen = userInput.nextInt();
if (diceChosen == 1)
diceOne = (int)(Math.random() * 6) + 1;
if (diceChosen == 2)
diceTwo = (int)(Math.random() * 6) + 1;
if (diceChosen == 3)
diceThree = (int)(Math.random() * 6) + 1;
sum = diceOne + diceTwo + diceThree;
if (sum == 12)
++wins;
if (sum > 12)
++losses;
System.out.printf("%d %d %d sum: %d #vinst: %d #förlust: %d", diceOne, diceTwo, diceThree, sum, wins, losses);
}

Since you can not use try and catch other alternative can be by changing your userInput.nextInt() to userInput.nextLine(); so it can detect when Q is pressed if Q is not pressed then we convert String to int so it can calculate the logic with Integer.parseInt(diceChosen);
All the code
while (true) {
for (int counter = 0; counter < 3; counter++) {
System.out.printf("%nAnge vilken tärning du vill slå[1,2,3](avsluta med q): ");
String diceChosen = diceChosen = userInput.nextLine();
int diceChosenToInteger = 0;
if (diceChosen.equalsIgnoreCase("Q")) {
System.exit(0);
} else {
diceChosenToInteger = Integer.parseInt(diceChosen);
}
if (diceChosenToInteger == 1)
diceOne = (int) (Math.random() * 6) + 1;
if (diceChosenToInteger == 2)
diceTwo = (int) (Math.random() * 6) + 1;
if (diceChosenToInteger == 3)
diceThree = (int) (Math.random() * 6) + 1;
sum = diceOne + diceTwo + diceThree;
if (sum == 12)
++wins;
if (sum > 12)
++losses;
System.out.printf("%d %d %d sum: %d #vinst: %d #förlust: %d", diceOne, diceTwo, diceThree, sum, wins, losses);
}
}
}
}

You could have an additional question asking the user if they would like to play again:
import java.util.Random;
import java.util.Scanner;
public class Main {
private static int getIntegerInput(Scanner scanner, String prompt, int minValue, int maxValue) {
System.out.print(prompt);
int validInteger = -1;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
validInteger = scanner.nextInt();
if (validInteger >= minValue && validInteger <= maxValue) {
break;
} else {
System.out.printf("Error: Please enter an integer between %d and %d inclusive%n", minValue, maxValue);
System.out.print(prompt);
}
} else {
System.out.printf("Error: Please enter an integer between %d and %d inclusive%n", minValue, maxValue);
System.out.print(prompt);
scanner.next();
}
}
return validInteger;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int gamesPlayed = 0;
int wins = 0;
System.out.println("Welcome! You must roll 1-3 dice and try to get the sum 12...");
while (true) {
System.out.printf("Game %d:%n", ++gamesPlayed);
int numDiceRolls = getIntegerInput(scanner, "How many dice do you want to roll? ", 1, 3);
int total = 0;
for (int i = 1; i <= numDiceRolls; i++) {
int roll = new Random().nextInt(6) + 1;
System.out.printf("Roll %d: %d%n", i, roll);
total += roll;
}
System.out.printf("The total for this game was %d%n", total);
if (total == 12) {
System.out.println("You won this game!");
wins++;
} else {
System.out.println("You lost this game!");
}
System.out.print("Enter q to quit or anything else to play again: ");
String playAgain = scanner.next();
if (playAgain.toLowerCase().equals("q")) {
break;
}
}
System.out.printf("You won %d time(s) and lost %d time(s)", wins, gamesPlayed - wins);
}
}
Example Usage:
Welcome! You must roll 1-3 dice and try to get the sum 12...
Game 1:
How many dice do you want to roll? 5
Error: Please enter an integer between 1 and 3 inclusive
How many dice do you want to roll? 3
Roll 1: 1
Roll 2: 2
Roll 3: 6
The total for this game was 9
You lost this game!
Enter q to quit or anything else to play again: a
Game 2:
How many dice do you want to roll? 3
Roll 1: 6
Roll 2: 3
Roll 3: 3
The total for this game was 12
You won this game!
Enter q to quit or anything else to play again: q
You won 1 time(s) and lost 1 time(s)

Related

Why wont Min and Max num update

Very new to Java (please don't laugh)and trying to do a project that asks user for a number and will keep track of the highest and lowest number when the user enter a sentinel value. My error is the I cannot get max and min values to update when going through the while loop.
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double number, or 'q' to quit");
double currentNum = 0.0;
double maxNum=0.0;
double minNum=0.0;
int count = 0;
while(sc.hasNextDouble())
{
currentNum = sc.nextDouble();
count++;
System.out.println(count);
if(count ==1)
{
minNum = currentNum;
maxNum = currentNum;
System.out.println("Please enter a double number, or 'q' to quit");
}
else if(count!=1){
if (currentNum > maxNum)
{
currentNum = maxNum;
System.out.println("You are in currentNum > maxNum");
System.out.println(maxNum);
System.out.println("Please enter a double number, or 'q' to quit");
System.out.println(maxNum);
}
else if (currentNum < minNum)
{
currentNum = minNum;
System.out.println("You are in currentNum < minum");
System.out.println("Please enter a double number, or 'q' to quit");
}
}
}
System.out.println("Min num " + minNum);
System.out.println("Max num " + maxNum);
}
}
I think you got your logic mixed up.
When you get a number larger or smaller than maxNum you want to update maxNum to currentNum not the other way around.
Also the count == 1 if condition is redundant.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double number, or 'q' to quit");
double currentNum = 0.0;
double maxNum=(double)Integer.MIN_VALUE;
double minNum=(double)Integer.MAX_VALUE;
int count = 0;
while(sc.hasNextDouble()) {
currentNum = sc.nextDouble();
count++;
System.out.println(count);
if (currentNum > maxNum){
maxNum = currentNum;
System.out.println("You are in currentNum > maxNum");
System.out.println("Maximum : "+maxNum);
}
else if (currentNum < minNum){
minNum = currentNum;
System.out.println("You are in currentNum < minum");
System.out.println("Minimum : "+minNum);
}
System.out.println("Please enter a double number, or 'q' to quit");
}
System.out.println("Min num " + minNum);
System.out.println("Max num " + maxNum);
}
}
One thing that I noticed is that you're comparing double variables. Generally it's not a good idea comparing floating point values because they have precision problems. You should use long or int instead. If you really don't have any other choice and have to use double, you should checkout this question: How to compare two double values in Java?
As pointed out in comment, you're updating currentNum instead of maxNum/minNum. So your else-if block for updating min-max value should look like this:
if (currentNum > maxNum) {
System.out.printf("You are in currentNum(%d) > maxNum(%d)", currentNum, maxNum);
//currentNum = maxNum; // <- Wrong, doesn't update maxNum; currentNum would be updated in next loop iteration anyway
maxNum = currentNum; // <- What you should be doing
}
else if (currentNum < minNum) {
System.out.printf("You are in currentNum(%d) < minNum(%d)", currentNum, minNum);
//currentNum = minNum; // <- Wrong, doesn't update minNum
minNum = currentNum; // <- What you should be doing
}

How to make while loop check if there are 16 digits in a string

How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!
import java.util.Scanner;
public class LuhnAlgorithm {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine();
int i = 0;
char chk = nums.charAt(15);
while(!nums .equals("") ) {
if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
}
int sum = 0;
for( i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if ( i % 2 == 0 ) {
num = num * 2;
if ( num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if ( sum2 == chk2) {
System.out.println("Number is valid.");
}
else {
System.out.println("Number is not valid. ");
}
System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
nums = input.nextLine();
}
System.out.println("Goodbye!");
input.close();
}
}
You can include your code that you only want done if the length ==16 in an if statement.
Meaning, instead of:
if (nums.length != 16) {
//code if there is an error
}
//code if there is no error
you can do:
if (nums.length == 16) {
//code if there is no error
} else {
//code if there is an error
}
(I also want to point out that you set chk = nums.charAt(15) before your while loop, but you don't reset it in the while loop for the next time the user inputs a new credit card number.)
You can bring the prompts and all your initialization except the scanner itself into the while loop. Then if they say "", break to exit the loop. If they say a number that is too short or too long, say continue to go back to the prompting.
Thus:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine().trim();
if (nums.length() == 0) {
break; //exits while loop
}
if (nums.length() != 16) { //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
continue; //goes back to the beginning right away
}
//still here, process the number
char chk = nums.charAt(15);
int sum = 0;
for (int i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if (i % 2 == 0) {
num = num * 2;
if (num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if (sum2 == chk2) {
System.out.println("Number is valid.");
} else {
System.out.println("Number is not valid. ");
}
}
System.out.println("Goodbye!");
input.close();
}
}

How can I implement a sequence of numbers in this Prime number generator?

I'm unsure of how to create a sequence of numbers that can be placed before each iteration of printed prime numbers. Thank you for any help you can offer.
public class CountingPrimes {
public static void main(String[] args) {
int flag = 0, i, j;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the 1st number: ");
int firstNum = sc.nextInt();
System.out.println("Enter the 2nd number: ");
int secondNum = sc.nextInt();
System.out.println("Counting prime numbers between "
+ firstNum + " and " + secondNum + ":");
for (i = firstNum; i <= secondNum; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
} else {
flag = 1;
}
}
if (flag == 1) {
System.out.println(i);
}
}
}
}
Right now, my code outputs (after the user enters their two numbers):
Counting prime numbers between 1 and 14:
3
5
7
11
13
What I need my code to look like:
Counting prime numbers between 1 and 14:
1. 3
2. 5
3. 7
4. 11
5. 13
Also, if you could see any errors or improvements I could change, I would greatly appreciate it. Thank you again!
You can use a counter and print the counter as you print the prime number. Increment the counter each time.
int counter = 1;
int flag = 0, i, j;
.....
if (flag == 1) {
System.out.format("%d. %d\n", counter, i);
counter++;
}
a simple change:
import java.util.Scanner;
public class CountingPrimes {
public static void main(String[] args) {
int flag = 0, i, j;
int count = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the 1st number: ");
int firstNum = sc.nextInt();
System.out.println("Enter the 2nd number: ");
int secondNum = sc.nextInt();
System.out.println("Counting prime numbers between "
+ firstNum + " and " + secondNum + ":");
for (i = firstNum; i <= secondNum; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
} else {
flag = 1;
}
}
if (flag == 1) {
System.out.println(++count + "." + i);
}
}
}
}
Just add a count variable and increment it whenever you output a number:
...
int count = 0;
for (i = firstNum; i <= secondNum; i++) {
...
if (flag == 1) {
count++;
System.out.format("%d. %d%n", count, i);
}
}
Declare Count before for loop
int count = 0;
and then increment the count on every prime number.
if (flag == 1) {
System.out.println(++count+". "+i);
}
}

MOOC loops ending remembering

I'm currently stuck with MOOC exercise 36. My problem is I can't make my program store odd and even numbers. I understand I need to use the modulus operator % 2 so the program can find if the reminder is 0 - 1 making is an even or odd number.
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int tal; //Min reader funktion
int sum = 0;
int numbersTyped = 0;
double average = 0.0;
int even = 0;
int odd = 0;
while (true) {
tal = Integer.parseInt(reader.nextLine());
if (tal == -1){
System.out.println("Thank you and see you later!");
System.out.println("The sum is: " + sum);
System.out.println("How many numbers: " + numbersTyped);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
break;
}
if (tal >= 0){
sum += tal;
numbersTyped++;
average = (double) sum / (double) numbersTyped;
} else if (tal > 0){
tal %= 2;
even = tal;
} else if (tal > 1) {
tal %= 2;
odd = tal;
}
}
}
try executing this code:
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int tal; //Min reader funktion
int sum = 0;
double doubleSum =0.0d;;
int numbersTyped = 0;
double doubleNumbersTyped = 0.0d;
double average = 0.0;
int even =0;
int odd = 0;
while (true) {
tal = Integer.parseInt(reader.nextLine());
if (tal == -1){
System.out.println("Thank you and see you later!");
System.out.println("The sum is: " + sum);
System.out.println("How many numbers: " + numbersTyped);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
break;
}
if (tal >= 0){
sum += tal;
numbersTyped++;
doubleSum = (double) sum;
doubleNumbersTyped = (double) numbersTyped;
average = doubleSum / doubleNumbersTyped;
}
if (tal > 0 && tal %2==0){
even++;
}
if (tal > 1 && tal %2!=0) {
odd++;
}
}
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers:");
int sum=0;
int i=0;
int even=0;
int odd=0;
double average=0.0;
while (true) {
int number=Integer.parseInt(reader.nextLine());
if (number!=-1) {
sum+=number;
i++;
average=(double)sum/(double)i;
}
if (number==-1) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is "+sum);
System.out.println("How many numbers:"+i);
System.out.println("The average is "+average);
System.out.println("Even numbers "+even);
System.out.println("Odd numbers "+odd);
break;
}
if (number%2==0) {
even++;
}
if (number%2!=0) {
odd++;
}

Need help adding "Do you want to play again" statement in my program

I'm making a Craps java program and I'm having some trouble adding a "Do you want to play again" statement at the end. If you can help me out that would be greatly appreciated! Also, the counter that I have to count how many games the user won/lost is not working properly. If you see the problem can you please tell me!
import java.util.Scanner;
public class Lab5 {
static int dice2;
public static void main(String[] args) {
//variables
int dice1;
int dice2;
int numWins = 0;
int numLosses = 0;
//Call the welcome method
welcome();
//fetch random numbers
/*
* **************************************************************
*welcome method
*welcome user
*no parameters
*no return
****************************************************************
*/
}
public static void welcome() {
System.out.println("Welcome to a Lucky (for me) Dice Game! \nFEELING LUCKY?!? Hope you brought lots of CASH!");{
}
int die1 = (int) (Math.random()*6 + 1);
int die2 = (int) (Math.random()*6 + 1);
int dice = die1 + die2;
System.out.println("Roll: total = " + dice);
int numWins = 0;
int numLosses = 0;
if (dice == 7 || dice == 11){
System.out.println("Woah!!! With a: "+dice+ " You WIN!!!!!!!!");
numWins++;
}
else if (dice == 2 || dice == 3 || dice == 12){
System.out.println("Sorry, with a "+dice+" You lose:(");
numLosses++;
}
while (dice != 0){
int die3 = (int) (Math.random()*6 + 1);
int die4 = (int) (Math.random()*6 + 1);
int dice2 = die3 + die4;
System.out.println("Roll: total = "+dice2);
if (dice2 == 2|| dice2 == 3 || dice2 == 12){
System.out.println("Sorry, with a "+dice2+" You lose:(");
numLosses++;
dice = 0;
}
else if (dice2 == 7 || dice2 == 11){
System.out.println("Woah!!! With a: "+dice2+ " You WIN!!!!!!!!");
numWins++;
dice = 0;
}
{
System.out.println("So far you have won " + numWins +
" times and lost " + numLosses + " times, ");
{
}
}
}
}}
This is my output when I run it:
Welcome to a Lucky (for me) Dice Game!
FEELING LUCKY?!? Hope you brought lots of CASH!
Roll: total = 2
Sorry, with a 2 You lose:(
Roll: total = 8
So far you have won 0 times and lost 1 times,
Roll: total = 10
So far you have won 0 times and lost 1 times,
Roll: total = 8
So far you have won 0 times and lost 1 times,
Roll: total = 3
Sorry, with a 3 You lose:(
So far you have won 0 times and lost 2 times,
The counter should only be stated after the win or lose. How do I fix this?
To repeat something, use a loop, such as a while loop or a do-while loop if you're not sure how manny times you'll loop. To get user input, use a Scanner object -- which you've already imported. The do-while loop structure will be something like...
do {
// code to do inside of the loop
} while (somethingIsTrue);
You will need to use some sentinel variable to change in the loop and then test inside of the while boolean check. It could be a String, in which case you'd use the String equals(...) or equalsIgnoreCase(...) method in your while's boolean check.
So consider prompting for input at the end of the do block of code using System.out.print(...), getting the input with your Scanner, and then testing that input in the while boolean test.
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Lab5
{
static int dice2;
public static void main(String[] args)
{
//variables
int dice1;
int dice2;
int numWins = 0;
int numLosses = 0;
//Call the welcome method
//welcome();
//fetch random numbers
/*
* **************************************************************
*welcome method
*welcome user
*no parameters
*no return
****************************************************************
*/
while(true)
{
welcome();
}
}
public static void welcome()
{
System.out.println("Welcome to a Lucky (for me) Dice Game! \nFEELING LUCKY?!? Hope you brought lots of CASH!");
int die1 = (int) (Math.random()*6 + 1);
int die2 = (int) (Math.random()*6 + 1);
int dice = die1 + die2;
System.out.println("Roll: total = " + dice);
int numWins = 0;
int numLosses = 0;
if (dice == 7 || dice == 11)
{
System.out.println("Woah!!! With a: "+dice+ " You WIN!!!!!!!!");
numWins++;
}
else if (dice == 2 || dice == 3 || dice == 12)
{
System.out.println("Sorry, with a "+dice+" You lose:(");
numLosses++;
}
while (dice != 0)
{
int die3 = (int) (Math.random()*6 + 1);
int die4 = (int) (Math.random()*6 + 1);
int dice2 = die3 + die4;
System.out.println("Roll: total = "+dice2);
if (dice2 == 2|| dice2 == 3 || dice2 == 12)
{
System.out.println("Sorry, with a "+dice2+" You lose:(");
numLosses++;
dice = 0;
}
else if (dice2 == 7 || dice2 == 11)
{
System.out.println("Woah!!! With a: "+dice2+ " You WIN!!!!!!!!");
numWins++;
dice = 0;
}
{
System.out.println("So far you have won " + numWins +
" times and lost " + numLosses + " times, ");
{
}
}
}
System.out.printf("\n\nWould you like to play again? ");
Scanner scanner = new Scanner(System.in);
String uinput = scanner.nextLine();
if(uinput.isEmpty() ||
uinput.equals("n") || uinput.equals("no"))
{
scanner.close();
System.out.println("Goodbye.");
return;
}
System.out.println();
}}

Categories