my guessing game counter keeps rising - java

so for class I'm supposed to make a guessing game that gives you clues as you get closer to the answer. My question is when i run it and i get one Number correct, I would obviously keep that number and keep going with the other 4 numbers, when I do that, the problem is my correct digits counter keeps rising even if I don't get other digits correct.. how would I remedy this? Would i be able to add breaks in each of the if statements or would that completely exit me out of my do while loop?
public class GuessingGame {
public static void main(String[] args) {
int guess,numDigitsCorrect=0,sumDigitsCorrect=0,attempts=0,answer;
Random rng = new Random();
Scanner consoleScanner = new Scanner(System.in);
answer = rng.nextInt(90000) + 10000;
System.out.println("I have randomly chosen a 5-digit code for you to guess.Each time you guess,\n"
+ "I will tell you how many digits are correct and the sum of the digits that are correct."
+ "For example, if the number is \"68420\" and you guess 12468, I will respond:\n"
+ "Number of Digits Correct: 1\n"
+ "Sum of Digits Correct: 4\n"
+ "From deduction, you will know the 4 was correct in the guess."
+ "\nNow its your turn..................................................................");
do{
System.out.print("Please enter a 5-digit code (your guess): ");
guess = consoleScanner.nextInt();
int g1 = guess/10000;
int g2 = guess%10000/1000;
int g3 = guess % 10000 % 1000 / 100;
int g4 = guess % 10000 % 100 /10;
int g5 = guess % 10000 % 10 / 1;
int a1 = answer/10000;
int a2 = answer%10000/1000;
int a3 = answer % 10000 % 1000 / 100;
int a4 = answer % 10000 / 100 / 10;
int a5 = answer % 10000 % 10 / 10;
if(g1 == a1)
{
numDigitsCorrect ++;
sumDigitsCorrect += a1;
System.out.println("\nNumber of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if(g2 == a2)
{
numDigitsCorrect ++;
sumDigitsCorrect += a2;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if (g3 == a3)
{
numDigitsCorrect ++;
sumDigitsCorrect += a3;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if (g4 == a4)
{
numDigitsCorrect ++;
sumDigitsCorrect += a4;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if (g5 == a5)
{
numDigitsCorrect ++;
sumDigitsCorrect += a5;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if(guess == answer)
{
System.out.println("****HOORAY! You solved it. You are so smart****");
break;
}
}while (guess != answer);
}
}

Few things to fix -
Make sure your a4, a5 are correct
int a4 = answer % 10000 % 100 / 10; // note the modulus
int a5 = answer % 10000 % 10; // note divided by 1 or remove the redundant statement
Move your print statement out of your if block to the end of all if inside the do block as -
if (g1 == a1) {
numDigitsCorrect++;
sumDigitsCorrect += a1;
}
... //other if statements
if (guess == answer) {
System.out.println("****HOORAY! You solved it. You are so smart****");
break;
}
System.out.println("Number of digits correct: " + numDigitsCorrect);
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
Also since you already do a check
if (guess == answer) {
System.out.println("****HOORAY! You solved it. You are so smart****");
break;
}
within your do you can change your while condition to true as -
do {
... your existing code
} while(true);
To answer
Would i be able to add breaks in each of the if statements
If you do so, for even a single digit match your loop will exit(break).
Importantly to fix the counter, initialize the counter within the do block as
do {
numDigitsCorrect = 0;
sumDigitsCorrect = 0;
.. // existing logic
}

Related

How to break the execution of the code based on a user input

So I am doing a digit counter thing basically
I want it to display 123 and which number is what place value for example 123
------------------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
------------------------------------
this is my code
import java.util.Scanner;
public class digits {
public static void main(String[] args)
{
Scanner scann = new Scanner(System.in);
System.out.print("Enter any number: ");
int number = scann.nextInt();
int num1 = number % 10;
int num2 = number / 10 % 10;
int num3 = number / 100 % 10;
int num4 = number / 1000 % 10;
int num5 = number / 10000 % 10;
int num6 = number / 100000 % 10;
int num7 = number / 1000000 % 10;
int num8 = number / 10000000 % 10;
scann.close();
System.out.println("Ones: "+num1);
System.out.println("Tens: "+num2);
System.out.println("Hundreds: "+num3);
System.out.println("Thousands: "+num4);
System.out.println("Ten-Thousands: "+num5);
System.out.println("Hundred-Thousands: "+num6);
System.out.println("Millions: "+num7);
System.out.println("Ten-Millions: "+num8);
}
}
How do I stop it from printing the rest if I only type 123?
Output I got
--------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
Thousands: 0
Ten-Thousands: 0
Hundred-Thousands: 0
Millions: 0
Ten-Millions: 0
------------------------
Output I want
--------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
------------------------
You need to introduce a condition (or conditions) in your code.
You can achieve that with a chain of if statements. But the better way to do it is by utilizing a loop. Because that will allow you to get rid of the intermediate variables (num1, num2, etc) and to avoid duplicating the line of code that prints the remainder on the consol. That will make the code more readable and concise.
In order to be able to apply the loop for this problem, you need to create an array of strings that will store all quantifiers ("Ones: ", "Tens: ", etc).
It can be done like that:
public static final String[] quantifiers =
{"Ones: ", "Tens: ", "Hundreds: ", "Thousands: ",
"Ten-Thousands: ", "Hundred-Thousands: ", "Millions: ", "Ten-Millions: "};
public static void main(String[] args) {
Scanner scann = new Scanner(System.in);
int number = scann.nextInt();
for (int i = 0; i < quantifiers.length && number > 0; i++) {
System.out.println(quantifiers[i] + number % 10);
number /= 10; // does the same as number = number / 10;
}
}
output for input 123
Ones: 3
Tens: 2
Hundreds: 1
It might help your question. Because of hardcoded terms such as 'tens' or 'hundreds', it is not generic enough.
public static void main(String[] args) {
Scanner scann = new Scanner(System.in);
System.out.print("Enter any number: ");
int number = scann.nextInt();
int length = String.valueOf(number).length();
for(int i=0; i< length; i++){
if(i == 0){
System.out.println("Ones: "+ number % 10);
}else if(i == 1)
System.out.println("Tens: " + number / 10 % 10);
else if(i == 2)
System.out.println("Hundreds: "+ number / 100 % 10);
else if(i == 3)
System.out.println("Thousands: "+ number / 1000 % 10);
else if(i == 4)
System.out.println("Ten-Thousands: "+ number / 10000 % 10);
else if(i == 5)
System.out.println("Hundred-Thousands: "+ number / 100000 % 10);
else if(i == 6)
System.out.println("Millions: "+ number / 1000000 % 10);
else if(i == 7)
System.out.println("Ten-Millions: " + number / 10000000 % 10);
}
scann.close();
}
Your code is printing all the numbers because that's what you wrote:
System.out.println("Ones: "+num1);
...and so on.
If you never want to print e.g. thousands, just remove the println for thousands. If you only want to print them if someone actually enters thousands, add an if statement:
if (num4 > 0) {
System.out.println("Thousands: "+num4);
}
Repeat for the others.

why does it print twice? if -else [duplicate]

This question already has answers here:
Java - Looping 2d Array to find index of a value not working
(2 answers)
Closed 7 years ago.
I'm learning java atm , and had to write a code to calculate the monetary units, and only display the nonzero denominations using singular words for single units and plural words for plural units.
This is the code so far:
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
// receive amount
System.out.println("Enter an amount in double, for example 11.56: ");
double amount = input.nextDouble();
int remainingAmount = (int)(amount * 100);
// find the number of one dollars
int numberOfDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
// find the number of quarters in the remaing amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
//find the number of dimes in the remaing amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
//find the number of nickels in the remaing amount
int numberOfNickles = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
//find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
//Display results
System.out.println("Your amount" + amount + "consists of");
if (numberOfDollars > 1) {
System.out.println(" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1); {
System.out.println(" " + numberOfDollars + "dollar");
}
The output is:
run:
Enter an amount in double, for example 11.56:
12,33
Your amount12.33consists of
12dollars
12dollar
1quarters
1quarter
0dimes
0dime
1nickles
1nickle
3pennies
3penny
Why is everything printed double? 3 == not 1 so why does it still say 3 penny?
Noob question maybe, but thats because i am one :) Thanks for help!
Because you added a random ; after the second if. Therefor your second System.out.println is not part of the if-statement. Remove it:
if (numberOfDollars > 1) {
System.out.println (" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1) {
System.out.println (" " + numberOfDollars + "dollar");
}
Remove the semicolon after if();
if (numberOfDollars == 1);
The second print statement is printing because it is not a part of if(); due to the semicolon that you have after if()
replace
else if (numberOfDollars == 1); { // with ;, condition terminates here itself
with
else if (numberOfDollars == 1) {
Semicolon at the end of If statememnt , finish the statement in single line. Means it ignores the result of condition and continue the execution from the next line.

Testing primes in Java - adding additional conditions

Beginner here. So I want to write a program that prints out all the prime numbers up to the number the user entered. E.g., user enters 5, program prints out 2 and 3. That part I understand, however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no) IF the entered number is bigger than, let's say, 50. Here is code for first part:
public class Primes {
public static void main(String args[]) {
System.out.println("All primes up to: ");
int num = new Scanner(System.in).nextInt();
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
I honestly can't wrap my around as to what I should be doing next. My first program ever ("Hello world" does not count ;P).
Edit :
Your current code seems to work fine.
As per your doubt as mentioned in one of the comments : Yes, but where do I add if statement that does the following: if the number entered is below 50, then the program prints out all the prime numbers up to the entered number. If the number the user entered is bigger than 50, it tells only whether the entered number is prime or not ( simply "It's a prime" or "No, it's not a prime"). Hope that made things clearer
The check you need to put is after you take the input :
int num = new Scanner(System.in).nextInt();
if( number > 50 )
{
if(isPrime(number))
{
// print out is prime
}
// print out it is not prime
}
else
{
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
SUGESTIONS :
However, just to touch upon the algorithmic part, I would recommend using Sieve of Eratosthenes for picking out all the prime numbers within a given range, as you need in your case.
Example :
To find all the prime numbers less than or equal to 30, proceed as follows:
First generate a list of integers from 2 to 30:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Strike (sift out) the multiples of 2 resulting in:
2 3 5 7 9 11 13 15 17 19 21 23 25 27 29
The first number in the list after 2 is 3; strike the multiples of 3 from the list to get:
2 3 5 7 11 13 17 19 23 25 29
The first number in the list after 3 is 5; strike the remaining multiples of 5 from the list:
2 3 5 7 11 13 17 19 23 29
The first number in the list after 5 is 7, but 7 squared is 49 which is greater than 30 so the process is finished. The final list consists of all the prime numbers less than or equal to 30.
Here's the code attached for reference ( Disclaimer : I'm picking up this code here from this site. Just pasted it here for more immediate visibility).
Code :
public class PrimeSieve {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]) primes++;
}
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
Try this..
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
this is more efficient way tough:-
public boolean isPrime(int n) {
// fast even test.
if(n > 2 && (n & 1) == 0)
return false;
// only odd factors need to be tested up to n^0.5
for(int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no).
Your current isPrime function seems to work, so just ask for a number and test it.
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (isPrime(num)) {
System.out.printf("%d yes%n", num);
} else {
System.out.printf("%d no%n", num);
}
}
Or with a ternary,
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
}
Edit Based on your comment, move your print up sequence to a method
public static void primesUpTo(int num) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
}
Then
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (num > 50) {
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
} else {
primesUpTo(num); // <-- call the method above.
}
}
If i understand the question right:
If user enteres number lesser than or equal to 50, then print all primes that are lesser than that number.
Otherwise, just write if inputted number is a prime.
With already existing isPrime() method:
int num = new Scanner(System.in).nextInt();
if (num <= 50) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
} else { //num > 50
if(isPrime(num)) {
System.out.println(num + " is prime.");
} else {
System.out.println(num + " isn't prime.");
}
}

Need help using random numbers and modulos

I'm trying to make a simple program that will display 20 random numbers between 1 and 100 and then print out which numbers are divisible by 3 and equivalent to 1%3 and 2%3. It seems to work just fine but I've noticed it only works with the very last number in the list. What am I missing to include all the numbers in the search for my math? Thank you in advance for any help I can get!
import java.util.Random;
public class Lab5 {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
for(int i=0;i<=repeat;i++){
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
}
System.out.println();
System.out.println("-------------------------------------");
if(n % 3 == 0){
System.out.println("Numbers divisible by three: "+n+(", "));
}else{
System.out.println("Numbers divisible by three: NONE");
}
System.out.println("-------------------------------------");
if(n == 1 % 3){
System.out.println("Numbers equivalent to one modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to one modulo three: NONE");
}
System.out.println("-------------------------------------");
if(n == 2 % 3){
System.out.println("Numbers equivalent to two modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to two modulo three: NONE");
}
}
}
It is only printing the last number because the check if the number is divisible, etc is not in your for loop at the top. Simply copy and paste all of the code below it into your for loop and it should work as you intended.
You also have an error here: if (n == 1 % 3), it is legal but will check if n is equal to the remainder of 1 / 3. I don't think that is what you wanted to achieve, so correct it like this: if (n % 3 == 1) as Ypnypn suggested.
Your n is declared outside of the loop body, so its value will persist. However, since you are overwriting n in each loop iteration, only the last value of n will persist and will be used by other parts of the program.
As Ypnypn has said, correct your use of modulo, and as Arbiter and deanosaur have suggested, move the rest of the program logic inside the for loop
The correct syntax for modulus is n % 3 == 2. The current code n == 2 % 3 means n == 0, since the order of operations in Java requires that modulus is evaluated before equality.
You are putting all the output statements (System.out.println()) outside your loop, so it only outputs the last value.
Move your output statements so they are inside your loop:
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
int[] numbers = new int[3]; // To hold how many numbers have modulo 0, 1 or 2
for(int i = 0; i <= repeat; i++) {
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
if(n % 3 == 0)
System.out.println("The number " + n + " is divisible by 3");
else
System.out.println("" + n + " modulo 3 = " + n % 3);
numbers[n % 3]++;
}
System.out.println("Numbers divisible by 3: " + numbers[0]);
System.out.println("Numbers with modulo 3 = 1: " + numbers[1]);
System.out.println("Numbers with modulo 3 = 2: " + numbers[2]);
}
Well .. you did not calculate anything in the loop, so your print statements work the last value of n after you exited the loop. Try something like
package com.example.modulo;
import java.util.Random;
public class Modulo {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
int[] nMod = new int[3];
nMod[0] = 0;
nMod[1] = 0;
nMod[2] = 0;
for (int i = 0; i <= repeat; i++) {
n = rnd.nextInt(100) + 1;
nMod[n%3] = nMod[n%3] + 1;
System.out.print(n + " (" + n%3 + "), ");
}
System.out.println();
System.out.println("-------------------------------------");
System.out.println("Numbers divisible by three: " + nMod[0] + (", "));
System.out.println("Numbers equivalent to one modulo three: " + nMod[1] + (", "));
System.out.println("Numbers equivalent to two modulo three: " + nMod[2] + (", "));
}
}

Split number into several numbers

I wrote a programm to get the cross sum of a number:
So when i type in 3457 for example it should output 3 + 4 + 5 + 7. But somehow my logik wont work. When i type in 68768 for example i get 6 + 0 + 7. But when i type in 97999 i get the correct output 9 + 7 + 9. I know that i have could do this task easily with diffrent methods but i tried to use loops . Here is my code: And thanks to all
import Prog1Tools.IOTools;
public class Aufgabe {
public static void main(String[] args){
System.out.print("Please type in a number: ");
int zahl = IOTools.readInteger();
int ten_thousand = 0;
int thousand = 0;
int hundret = 0;
for(int i = 0; i < 10; i++){
if((zahl / 10000) == i){
ten_thousand = i;
zahl = zahl - (ten_thousand * 10000);
}
for(int f = 0; f < 10; f++){
if((zahl / 1000) == f){
thousand = f;
zahl = zahl - (thousand * 1000);
}
for(int z = 0; z < 10; z++){
if((zahl / 100) == z){
hundret = z;
}
}
}
}
System.out.println( ten_thousand + " + " + thousand + " + " + hundret);
}
}
Is this what you want?
String s = Integer.toString(zahl);
for (int i = 0; i < s.length() - 1; i++) {
System.out.println(s.charAt(i) + " + ");
}
System.out.println(s.charAt(s.length()-1);
The problem with the code you've presented is that you have the inner loops nested. Instead, you should finish iterating over each loop before starting with the next one.
What's happening at the moment with 68768 is when the outer for loop gets to i=6, the ten_thousand term gets set to 6 and the inner loops proceed to the calculation of the 'thousand' and 'hundred' terms - and does set those as you expect (and leaving zahl equal to 768 - notice that you don't decrease zahl at the hundreds stage)
But then the outer loop continues looping, this time with i=7. With zahl=768, zahl/1000 = 0' so the 'thousand' term gets set to 0. The hundred term always gets reset to 7 with zahl=768.
The 97999 works because the thousand term is set on the final iteration of the 'i' loop, so never gets reset.
The remedy is to not nest the inner loops - and it'll perform a lot better too!
You should do something like this
input = 56789;
int sum = 0;
int remainder = input % 10 // = 9;
sum += remainder // now sum is sum + remainder
input /= 10; // this makes the input 5678
...
// repeat the process
To loop it, use a while loop instead of a for loop. This a great example of when to use a while loop. If this is for a class, it will show your understanding of when to use while loops: when the number of iterations is unknown, but is based on a condition.
int sum = 0;
while (input/10 != 0) {
int remainder = input % 10;
sum += remainder;
input /= 10;
}
// this is all you really need
Your sample is a little bit complicated. To extract the tenthousand, thousand and the hundreds you can simply do this:
private void testFunction(int zahl) {
int tenThousand = (zahl / 10000) % 10;
int thousand = (zahl / 1000) % 10;
int hundred = (zahl / 100) % 10;
System.out.println(tenThousand + "+" + thousand + "+" + hundred);
}
Bit as many devs reported you should convert it to string and process character by character.

Categories

Resources