"Why does my lottery game ignores zeros?" - java

I'm doing exercice 3 from Chapter 4 of the book "Introduction to Java" by Walter Savitch.
Instructions:
Develop an algorithm for a simple game of guessing at a secret five-digit code. When the user enters a guess at the code the program returns two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code os 53840, and the user guesses 83241, the digits 3 and 4 are in the correct position. Thus, the program should respond 2 and 7. Allow the user to guess a fixed number of times
Current problems:
my code looks dirty and too long. I'm a beginner, but looking for ways to make it more efficient
when entering a 'guess number' that starts with any other number than 0 it works but when it starts with 0, my program ignores the first digit
I've spent two hours on it. There's still another 25 exercises waiting for me in this chapter only so I hope to be more efficient with the other exercises.
public static void main(String[] args) {
int SecretCode = 12140;
int Win = 0;
//just checking the incrementor
int sum = 0;
System.out.println("Ceci est un jeu de lotterie. \nPouvez-vous deviner le nombre à 5 chiffres caché ?\n");
Scanner fromPlayer = new Scanner(System.in);
do {
System.out.println("Votre nombre porte-bonheur: ");
int guess = fromPlayer.nextInt();
//Interprets Guess int to string
String stringGuess = String.valueOf(guess);
int length = stringGuess.length();
boolean CorrectLength = (length == 5);
if (CorrectLength) {
String Firstdigit = stringGuess.substring(0, 1);
String Seconddigit = stringGuess.substring(1, 2);
String Thirddigit = stringGuess.substring(2, 3);
String Fourthdigit = stringGuess.substring(3, 4);
String Fifthdigit = stringGuess.substring(4);
//Interprets Secret Code int to string
String stringSecretCode = String.valueOf(SecretCode);
String FirstdigitCode = stringSecretCode.substring(0, 1);
String SeconddigitCode = stringSecretCode.substring(1, 2);
String ThirddigitCode = stringSecretCode.substring(2, 3);
String FourthdigitCode = stringSecretCode.substring(3, 4);
String FifthdigitCode = stringSecretCode.substring(4);
//Just checking the values that the program will compare to secret code
System.out.println("Vous avez entré \n" + Firstdigit + "\n" + Seconddigit + "\n" + Thirddigit + "\n" + Fourthdigit + "\n" + Fifthdigit);
if (Firstdigit.equals(FirstdigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Firstdigit);
System.out.println("Premier numéro est : correct. Score: " + Win);
} else {
System.out.println("Premier numéro est : incorrect. Score:" + Win);
}
if (Seconddigit.equals(SeconddigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Seconddigit);
System.out.println("Deuxième numéro est : correct. Score: " + Win);
} else {
System.out.println("Deuxième numéro est : incorrect. Score: " + Win);
}
if (Thirddigit.equals(ThirddigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Thirddigit);
System.out.println("Troisième numéro est : correct. Score: " + Win);
} else {
System.out.println("Troisième numéro est : incorrect. Score: " + Win);
}
if (Fourthdigit.equals(FourthdigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Fourthdigit);
System.out.println("Quatrième numéro est : correct. Score: " + Win);
} else {
System.out.println("Quatrième numéro est : incorrect. Score: " + Win);
}
if (Fifthdigit.equals(FifthdigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Fifthdigit);
System.out.println("Cinquième numéro est : correct. Score: " + Win);
} else {
System.out.println("Cinquième numéro est : incorrect. Score: " + Win);
}
System.out.println("Vous avez deviné " + Win + " numéros. Leur total vaut " + sum);
} else {
System.out.println("ERREUR. Il faut entrer 5 chiffres.");
}
I expect the output of 02140 to be
"Premier numéro est : incorrect. Score: 0
Deuxième numéro est : correct. Score: 1
Troisième numéro est : correct. Score: 2
Quatrième numéro est : correct. Score: 3
Cinquième numéro est : correct. Score: 4
Vous avez deviné 4 numéros. Leur total vaut 7"
BUT the actual output is: ERREUR. Il faut entrer 5 chiffres.
as if the program doesn't identify 0 as a digit.

Instead of using
String stringGuess = String.valueOf(guess);
you should use
String stringGuess = String.format("%05d", guess);
to always convert the number you've read into a five digit long String. In your current solution you should see that if you print stringGuess leading zeros will have been removed from the input.
Instead, you could use the following code which uses the nextLine() method of the Scanner class to solve your problem:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] expected = "53849".toCharArray();
// enter CTRL-D to stop
while (scanner.hasNext()) {
String input = scanner.nextLine();
if (input.length() != 5) {
System.err.println("wrong length");
continue;
}
char[] actual = input.toCharArray();
int digitSum = 0;
int correctDigits = 0;
for (int i = 0; i < expected.length; i++) {
if (actual[i] == expected[i]) {
correctDigits++;
digitSum += actual[i] - '0';
}
}
String msg = String.format(
"Number of correct digits: %d, their sum: %d",
correctDigits, digitSum
);
System.out.println(msg);
}

Try the one below and see if it works for you. Take the input directly into stringGuess instead of taking it into int and then converting it into String.
int guess = fromPlayer.nextInt(); //remove this and take input into the below variable directly
String stringGuess = fromPlayer.next();
Check this for your reference why the int cannot store leading zeroes.

Related

How to align numbers in Java

So i'd like to align the row that displays the tenth year with rest of the numbers.
I've tried printf but it doesn't seem to work.
I've looked at many posts already but everything seems to be roaming around printf with some string formats.
If you can juste explain how to do it to me with some examples it would help me a lot.
Thanks for the help.
public class Foo {
public static void main(String[] args) {
double capitalDeDepart = capitalDepart(0);
double tauxInteretAnnuel = interetAnnuel(0);
double anneeTotalPlacement = dureePlacement(0);
affichage();
calcul(capitalDeDepart, tauxInteretAnnuel, anneeTotalPlacement);
}
public static double capitalDepart(double capitalDeDepart) {
Scanner clavier = new Scanner(System.in);
System.out.print("Indiquez le capital de départ : ");
capitalDeDepart = clavier.nextDouble();
return capitalDeDepart;
}
public static double interetAnnuel(double tauxInteretAnnuel) {
Scanner clavier = new Scanner(System.in);
System.out.print("Inscrivez le taux d'intérêt annuel : ");
tauxInteretAnnuel = clavier.nextDouble();
return tauxInteretAnnuel;
}
public static double dureePlacement(double anneeTotalPlacement) {
Scanner clavier = new Scanner(System.in);
System.out.print("Indiquez la durée du placement en années : ");
anneeTotalPlacement = clavier.nextDouble();
return anneeTotalPlacement;
}
public static void affichage() {
System.out.println("Année Capital Intérêt Nouveau capital");
System.out.println("----------------------------------------------");
}
public static void calcul(double capitalDeDepart, double tauxInteretAnnuel, double anneeTotalPlacement) {
int annee = 0;
double interet = 0;
double nouveauCapital = 0;
double tauxEnDecimal = 0;
do {
annee++;
capitalDeDepart = capitalDeDepart + interet;
tauxEnDecimal = tauxInteretAnnuel / 100;
interet = capitalDeDepart * tauxEnDecimal;
nouveauCapital = (int)(capitalDeDepart + interet);
System.out.println(" " + annee + " " + (int)capitalDeDepart + "$ " + (int)interet + "$ " + (int)nouveauCapital + "$");
} while (annee != anneeTotalPlacement);
}
}
Indiquez le capital de départ : 10000
Inscrivez le taux d'intérêt annuel : 10
Indiquez la durée du placement en années :
Année Capital Intérêt Nouveau capital
----------------------------------------------
1 10000$ 1000$ 11000$
2 11000$ 1100$ 12100$
3 12100$ 1210$ 13310$
4 13310$ 1331$ 14641$
5 14641$ 1464$ 16105$
6 16105$ 1610$ 17715$
7 17715$ 1771$ 19487$
8 19487$ 1948$ 21435$
9 21435$ 2143$ 23579$
10 23579$ 2357$ 25937$
Just replase your System.out.println(...) with following:
System.out.format("%2d %5d$ %5d$ %5d$\n", annee,
(int)capitalDeDepart, (int)interet, (int)nouveauCapital);
you must will try add a String variable... like...
String reglerAnnee;
...
// add a space if year(anne) is less than 10
// using a ternary operator, like an "if" but less code
reglerAnnee = annee < 10 ? " " : "";
..
// and add to the println ...
System.out.println(" "+reglerAnnee + annee + " " + (int) capitalDeDepart
+ "$ " + (int) interet + "$ "
+ (int) nouveauCapital + "$");
...
The result will be like:
1 10000$ 1000$ 11000$
2 11000$ 1100$ 12100$
...
9 21435$ 2143$ 23579$
10 23579$ 2357$ 25937$

Do-while loop not printing the right variables

I'm doing a programming task which asks the user some questions, if the user gets the answer wrong/right it doesn't matter, ad a random number generator is used to determine their points for that question. However if they choose the 'impossible answer' (something that it couldn't possibly be, their score is reset to 0.
When I run the code,
If I get 23 points on the first questions and 0 on the second, it should reset my score to 0 on the second question, but at the end the total score shows as 23.
Any help would be appreciated
import java.util.Scanner;
public class Main {
public static double randnum(){
int random = (int)(Math.random() * 50 + 1);
return random;
}
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int score1 = 0;
int score2 = 0;
int score3 = 0;
int totalscore = 0;
final double NumberofQuestions = 2;
String[][] questions ={
{"What is the largest bone in the human body? ", "\n Choose 1 for Femur \n Choose 2 for Tibia \n Choose 3 for Palatine Bone \n Choose 4 for Tongue ", "1"},
{"What is the capital of Albania? ! ","\n Choose 1 for Shkoder \n Choose 2 for Tirana \n Choose 3 for Durres \n Choose 4 for Rome ", "2"}
};
String[] Answers = new String[(int) NumberofQuestions];
int x=0;
do
{
System.out.print("" + (x+1) + ". " + questions[x][0] + " "+questions[x][1]);
Answers[x] = String.valueOf(input.nextInt());
Answers[x].toLowerCase();
if(questions[x][2].equals(Answers[x])) {
score1 = (int) randnum();
System.out.println("Correct: " + score1 + " points");
totalscore = totalscore + score1;
}
if (Answers[x].equals("4")){
System.out.println("\n Thats a impossible answer! The right answer is "+questions[x][2]);
totalscore = 0;
score2 = 0;
System.out.println(score2 + " points");
} else {
System.out.println("\nIncorrect. The right answer is "+questions[x][2]);
score3 = (int) randnum();
System.out.println(score3 + " points");
totalscore = totalscore + score3;
}
System.out.print("\n");
x++;
} while(x < NumberofQuestions); //close outer loop
totalscore = score1 + score2 + score3;
System.out.println("\n\t\tYou got " + totalscore + " points !\n\n\n");
System.exit(0);
}
}
A quick fix to your problem with your current code:
if user chooses impossible answer, set all score variables to 0, not just score2
change the do/while loop to a simple while loop :
while(x<NumberofQuestions)
{ …
instead of :
do
{ ...
Also note you're using 3 score variables while you ask just 2 questions
This line of code is undoing all of the totalscore calculations you did during your loop:
totalscore = score1 + score2 + score3;
Since it looks like score1, score2, and score3 are just meant to be temporary variables, I'd say you should get rid of this line of code. Also consider declaring those variables local to each block of logic they belong to.

Mutliple lines of a while loop printing in gui dialog (Java)

I want to print multiple lines of a while loop in 1 gui dialog box.
This is the code I have currently
package Tempconv1;
import javax.swing.JOptionPane;
public class TimesTables
{
public static void main(String[] args)
{
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
//Calculating number inputs
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
String multimsg = ("The calculation is " + num1 + " x " + counter + "=" + total);
JOptionPane.showMessageDialog(null, multimsg);
}
JOptionPane.showMessageDialog(null, "All Done");
}
}
It works but prints out "The calculation is 5x1 = 5" and then opens a new message box to show "The calculation is 5x2 = 10".
I want it to print out
The Calculation is 5x1 = 5
The Calculation is 5x2 = 10
etc
All inside 1 textbox
What you are telling your program to do is create a string of the individual calculation, and then create a dialog box. Then do it again for each loop.
You will want to build all of the messages into one string inside your loop, and then create the dialog box outside the loop.
String multimsg = "";
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
multimsg += ("The calculation is " + num1 + " x " + counter + "=" + total);
}
JOptionPane.showMessageDialog(null, multimsg);
you might want to look into using stringbuilder or similar to be more efficient about building the message string. (https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html)
The problem is that you are showing the message inside the while loop. The syntax with the while loop can be a little bit confusing.
If you are using java 8 you can replace the while/counter with an IntStream and you can compose the message by joining the Strings in the collector:
String message = IntStream.rangeClosed(1, 12)
.mapToObj(i -> "The calculation is " + num1 + "x" + i + " = " + i * num1)
.collect(Collectors.joining(", "));
The first line creates a stream of integers from 1 to 12. The second line maps every number to an individual textmessage. The last line concatenates all the individual messages by joining them with a ,
Your main method would look something like this:
public static void main(String[] args){
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
//Calculating number inputs
String message = IntStream.rangeClosed(1, 12)
.mapToObj(i -> "The calculation is " + num1 + "x" + i + " = " + i * num1)
.collect(Collectors.joining(", "));
JOptionPane.showMessageDialog(null, message);
JOptionPane.showMessageDialog(null, "All Done");
}
before loop:String multimsg = "";
in loop after the maths:multimsg=multimsg+"The calculation is " + num1 + " x " + counter + "=" + total;
and after while loop JOptionPane.showMessageDialog(null, multimsg);
Build only the msg inside the loop and save it to StringBuilder.
public static void main(String[] args)
{
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
//Calculating number inputs
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
sb.append("The calculation is ").append(num1).append(" x ").append(counter).append("=").append(total).append(" ");
}
JOptionPane.showMessageDialog(null, sb.toString());
JOptionPane.showMessageDialog(null, "All Done");
}

I cannot make Java accept a keyboard input string

I would like to know how to get a keyboard response in my java program to work and continue with the game as normal.
I realize the code is a little messy and an array might suit better, but for this instance I would like only answers about keyboard inputs.
The game works well enough until it reaches the if and if else statement. Then I really don't know how to fix it.
import java.util.Random;
import java.util.Scanner;
class blackjack {
public static void main(String[] args) {
Random r = new Random();
Scanner keyboard = new Scanner(System.in);
String money;
String name;
String hiscore;
String h;
String s;
int card1 = 1 + r.nextInt(11);
int card2 = 1 + r.nextInt(11);
int card3 = 1 + r.nextInt(11);
int card4 = 1 + r.nextInt(11);
int card5 = 1 + r.nextInt(11);
int card6 = 1 + r.nextInt(11);
int card7 = 1 + r.nextInt(11);
int card8 = 1 + r.nextInt(11);
int card9 = 1 + r.nextInt(11);
int card10 = 1 + r.nextInt(11);
int card11 = 1 + r.nextInt(11);
int card12 = 1 + r.nextInt(11);
int card13 = 1 + r.nextInt(11);
int total1 = card2 + card3;
int total2 = total1 + card4;
System.out.println("Welcome to Blackjack ! ");
System.out.println("Score as close to 21 without going over to win ");
System.out.println("What is your name?");
name = keyboard.nextLine();
System.out.println("Hello " + name);
System.out.println("Let's play some BlackJack!");
System.out.println("The dealer shows: \n\t\t" + card1);
System.out.println("Your first card is: \n\t\t " + card2);
System.out.println("Your second card is: \n\t\t" + card3);
System.out.println("giving you a total of " + total1);
System.out.println("Would you like to (H)it or (S)tick?");
if h = keyboard.nextLine();
System.out.println("Your next card is " + card4);
System.out.println("Giving you a new total of: " + total2);
if else s = keyboard.nextLine();
System.out.println("your final score is: "total1);
}
}
That if (and if-else) statement is broken. It's not valid syntax. Correct syntax would be:
if(h = keyboard.nextLine());
Note that I said that was correct syntax, but that will definitely not do what you want it to do. It seems like what you want to do is check against predetermined strings "h" and "s".
Store the variable off somewhere, then do the comparison. Remember that to compare Strings in Java, you need to use .equals().
String response = keyboard.nextLine();
if("h".equals(response)) {
// perform operations here
} else if("s".equals(response)) {
// perform operations here
}

Java Powers display table

I need to display an output like this:
Enter an integer: 3
Number Squared Cubed
====== ======= =====
1 1 1
2 4 8
3 9 27
But instead, when I run the code, I get this output:
Number Squared Cubed
====== ======= =====
3 9 27
In other words, I need to display the powers of an integer,including the powers of the numbers less than or equal to the integer. The numbers of the lesser integers need to be listed but are not displayed along with the integer being entered. How do I fix the code to make sure it outputs all of the integers that are less than or equal to the integer being entered? There are no errors (i.e. red exclamation mark circles) but I need to figure out the proper calculation.
Here is the code:
====================
import java.util.Scanner;
public class Powers
{
public static void main(String[] args)
{
System.out.println("Welcome to the Squares and Cubes Table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.println("Enter an Integer: ");
int integerNext = sc.nextInt();
System.out.println("Number" + " " + "Squared" + " " + "Cubed");
System.out.println("======" + " " + "======" + " " + "======");
for(int i = 1; i <= integerNext; i++)
{
i = integerNext;
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow (i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.println(message);
System.out.println();
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
}
Help is always appreciated. Thanks.
Firstly, as Nikhil said: "Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed".
Secondly, move the first closing curly brace to before getting user input - you want to run the loop, and only ask about continuing when that's finished, if I understand correctly.
Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed
Your are almost there. Since you are looping from 1 to integerNext (which is 3 in your text), the looping variable i will get the values [1,2,3] each iteration, so you don't have to set i manually. When you do:
i = integerNext;
you are setting i to 3, so the loop will finish when it reaches the loop condition.
You may also want to put the "Continue?" check outside the loop:
for (int i = 1; i <= integerNext; i++) {
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow(i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.print(message);
}
// see if the user wants to continue
System.out.print("\nContinue? (y/n): ");
choice = sc.next();
System.out.println();
import java.util.Scanner;
public class SquaresAndCubes {
public static void main(String[] args)
{
// Welcome the user
System.out.println("Welcome to the Squares and Cubes table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do
{
// Get input from the user
System.out.print("Enter an integer: ");
int integer = sc.nextInt();
// Create a header
String header = "Number " + "Squared " + "Cubed " + "\n"
+ "====== " + "======= " + "===== ";
System.out.println(header);
int square = 0;
int cube = 0;
String row = "";
for (int i = 1; i <= integer; i++)
{
square = i * i;
cube = i * i * i;
row = i + " " + square + " " + cube;
System.out.println(row);
}
// See if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
while (!choice.equalsIgnoreCase("n"));
}
}
Basic way to do it with foor loop and some printlines
Scanner sc = new Scanner(System.in);
System.out.print("What number would you like to go up to? ");
int userInt = sc.nextInt();
System.out.println("");
System.out.println("Here is your table!");
System.out.println("");
System.out.println("number | squared | cubed");
System.out.println("------ | ------- | -----");
for (int i = 1; i <= userInt; i++){
System.out.println(i + " | " + (i * i) + " |" + " " +(i * i * i));
}

Categories

Resources