Guessing game loop - java

Here is the code for a guessing game I have made. My counter in not increasing past 1. I am passing the parameters choice and generatedNumber from a seperate controller class. Should the do while loop be in the controller class?
public String startGuessingGame(int choice, int generatedNumber) {
int count = 0;
final int attempts = 4;
String result = null;
do {
count++;
if (choice == generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed the correct number!";
}
else if (choice > 50 || choice < 0) {
result = "Out of range. "
+ "\nPlease choose a number between 1 and 50.";
}
else if (choice > generatedNumber) {
result = "Attempt " + count + " "
+ " - You have guessed too high!";
}
else if (choice < generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed too low!";
}
if (count == attempts) {
result = "You are out of guesses! The number was " + generatedNumber;
}
}
while(count < attempts);
return result;
}
}

There is no loop here.
You're looking for something like while(count < attempts).

Try this:
Incrementing the counter at the end before the while condition:
do{
...
if (count == attempts) {
result = "You are out of guesses! The number was " + generatedNumber;
}
count++;
}while(count < attempts);
return result;
...

You need to make count a class variable (member) of your controller class and have your do/while loop in that class so that the startGuessingGame only handles the validation of the user choice. Something like this but the code is far from complete
public class SomeControllerClass() {
final int attempts = 4;
int count = 0;
public void someMethod() {
int choice = 0;
do {
choice = getChoice();
count++;
String text = otherClass.startGuessingGame(choice, generatedNumber);
while (count < attempts);
}
and the method only does validation
public String startGuessingGame(int choice, int generatedNumber) {
String result = null;
if (choice == generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed the correct number!";
} else if (choice > 50 || choice < 0) {
//and so on
return result;
}

Related

I am trying to make a function that adds 1 to either opps_score or bets_score but when I print the results the default value is printed

int bets_score = 0;
int opps_score=0;
When I call this method it shoud return 1 to either bets_score or opps_score
b.getCSRecordOdds(wins, loses, opps_wins, opps_loses, bets_score, opps_score);
if (bets_score > opps_score) {
System.out.println("You're bet is looking good \n
Score: " + bets_score+" to " + opps_score);
} else {
System.out.println("You should probably sit this one out \n
Score: " + opps_score+" to " + bets_score);
}
This is the abstract method
public int getCSRecordOdds(int cs_bets_wins, int cs_bets_loses, int cs_opps_wins, int cs_opps_loses, int bets_score, int opps_score){
if (cs_bets_wins / cs_bets_loses > cs_opps_wins / cs_opps_loses) {
bets_score = bets_score +1;
return bets_score;
} else {
opps_score = opps_score +1;
return opps_score;
}
}

Java program that teaches kid simple addition and subtraction

I feel like I'm almost there with the code but the problem is the while loop I am not allowed to use break and continue statements for this program. The first output test its suppose to have 14 questions where you get 12 right and 2 wrong giving you 86%. As for the second test you get a perfect score while the last test takes you to 20 questions that being the max number of questions, 4 of the first 8 questions correctly and 4 of the first 8 incorrectly, and then the next 12 correctly giving you 80% Code below:
package proj3;
import java.util.Scanner;
public class Project4App {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int correctNum = 0;
int wrongNum = 0;
double percent = 0;
int subNumCorrect = 0;
int subNumWrong = 0;
int addNumCorrect = 0;
int addNumWrong = 0;
int totalQuestions = 0;
while(!(correctNum == 10 && totalQuestions == 10) && !(percent >= 85.0 && totalQuestions >= 10) && (totalQuestions != 20)) {
Question Quest = new Question();
System.out.println("What is the result?" + "\n" + Quest.toString());
int userInt = scnr.nextInt();
if((Quest.getOperator() == '+') && (userInt == Quest.determineAnswer())) {
addNumCorrect += 1;
}
else if(Quest.getOperator() == '+' && (userInt != Quest.determineAnswer())) {
addNumWrong += 1;
}
if((Quest.getOperator() == '-') && (userInt == Quest.determineAnswer())) {
subNumCorrect += 1;
}
else if((Quest.getOperator() == '-') && (userInt != Quest.determineAnswer())) {
subNumWrong += 1;
}
if(userInt == Quest.determineAnswer()){
correctNum += 1;
System.out.println("Congratulations, you got it correct!");
}
else if (userInt != Quest.determineAnswer()){
wrongNum += 1;
System.out.println("The correct answer for " + Quest.toString() + " is " + Quest.determineAnswer());
}
totalQuestions++;
percent = Math.round((double)(correctNum * 100) / (totalQuestions));
}
System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
System.out.println("The percent correct: " + percent + "%");
scnr.close();
}
}
I think this largely does what you want. A number of the counters weren't being modified as was intended. This is partly due to the amount going on in your main method making it hard to see what's going on (too much information). I've extracted functionality to smaller, more well defined methods.
You had a whole lot of logic effectively saying you want the user to have achieved 85% with at least 10 questions answered - and stop when 20 questions are asked. You could factor this condition out to a method returning a boolean isGameComplete(totalQuestions) and put this in the while condition-expression.
I've taken the liberty of implementing a question class based on the functionality that I think achieves the intention.
The correctPercent was rounded to an int which made it impossible to be == to 85.5%, say. I've converted this to a double so if you get more than 85%, say 85.25%, the game completes successfully.
Probably some other stuff I've added, which I've tried to comment in-line, if significant. Hopefully this is what you were after.
If it ever gets too difficult to understand, extracting small chunks of code to well named methods (even long ones) helps enormously, since it reduces your mental load.
class Project4App {
static final Scanner scanner = new Scanner(System.in);
static int correctNum = 0;
static int wrongNum = 0;
static int subNumCorrect = 0;
static int subNumWrong = 0;
static int addNumCorrect = 0;
static int addNumWrong = 0;
static int totalQuestions = 0;
static double percentCorrect = 0;
public static void main(String[] args) {
/**
* answer at least 9/10 questions correctly (to get 85%)
*/
while (percentCorrect < 85.0 && totalQuestions >= 10 && totalQuestions <= 20) {
Question question = new Question();
int userInt = getUsersAnswer(question);
boolean isCorrect = question.determineAnswer(userInt);
updateStatistics(question, isCorrect);
printResults(); // can remove this/comment this out - added to help with debugging
}
System.out.println();
System.out.println("------------ Game Complete! ------------");
printResults();
}
private static void printResults() {
System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
System.out.println("The percent correct: (" + (addNumCorrect+subNumCorrect) + "/" + totalQuestions +") " + percentCorrect + "%");
System.out.println("The percent wrong: (" + (addNumWrong+subNumWrong) + "/" + totalQuestions +") " + (100 - percentCorrect) + "%");
}
private static int getUsersAnswer(Question question) {
System.out.println("What is the result?" + "\n" + question.toString());
int userInt = scanner.nextInt();
return userInt;
}
public static void updateStatistics(Question question, boolean isCorrect){
if (question.getOperator() == '+') {
if (isCorrect) {
addNumCorrect++;
correctNum++; // newly added (wasn't updated)
} else {
addNumWrong++;
wrongNum++; // newly added - unused variable originall
}
} else { // operator is '-'
if (isCorrect) {
subNumCorrect++;
correctNum++; // newly added (wasn't updated)
} else {
subNumWrong++;
wrongNum++; // newly added - unused variable originall
}
}
totalQuestions++; // newly added
percentCorrect = (correctNum * 100) / totalQuestions;
}
}
class Question {
private static final int UPPER_LIMIT_ON_RANDOM_NUMBERS = 20;
private static final Random random = new Random();
private final int number1;
private final int number2;
private final char operator;
public Question() {
operator = Math.random()>0.5 ? '+' : '-';
number1 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // NOTE THE SUBTRACTION NUMBER COULD BE NEGATIVE IF number2
number2 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // IS GREATER THAN number1.
}
public char getOperator() {
return operator;
}
public boolean determineAnswer(int userAnswer) {
switch (operator) {
case '+':
return userAnswer == (number1 + number2);
case '-':
return userAnswer == (number1 - number2);
}
return false; // shouldn't end up here - would be better to throw an unchecked exception and crash the program - new RuntimeException()
}
#Override
public String toString() {
return number1 + " " + operator + " " + number2;
}
}
Output:
------------ Game Complete! ------------
Progress Report:
Addition:
You got 7 correct and 0 incorrect.
Progress Report:
Subtraction:
You got 2 correct and 1 incorrect.
The percent correct: (9/10) 90.0%
The percent wrong: (1/10) 10.0%

Why Phone Number validate without regEx giving dead code in java

index increment showing dead code why so ?? before adding special character condition it was working fine no dead code was showing and i want to validate special character condition as well.
public class ValidatePhoneNumber {
void validatePhoneNumber(String pNumber) {
// 1st Case - +91 9765463742 have to check for + sign
boolean flag = false;
String specialCharacter = "!##$%^&*()-/`~:<>/?|=.,";
if (pNumber.startsWith("+") && pNumber.length() == 14) {
for (int index = 1; index < pNumber.length(); index++) {
if ((Character.isDigit((pNumber.charAt(index))) || Character.isSpaceChar((pNumber.charAt(index))))
&& (!(specialCharacter.contains(Character.toString(pNumber.charAt(index)))))
&& (!(Character.isLetter(pNumber.charAt(index))))) {
flag = true;
}
else
System.out.println(pNumber.charAt(index) + " " + pNumber + " Number is Invalid");
flag = false;
break;
}
if (flag == true) {
System.out.println("Number " + pNumber + " is Valid");
}
}
public static void main(String[] args) {
ValidatePhoneNumber phoneNumber = new ValidatePhoneNumber();
phoneNumber.validatePhoneNumber("+91 975644#742");
phoneNumber.validatePhoneNumber("09765463742");
The problem is because of the following break statement which will break the for loop right after the first iteration and therefore index++ will never get an opportunity to run:
else
System.out.println(pNumber.charAt(index) + " " + pNumber + " Number is Invalid");
flag = false;
break;
You should write it as:
void validatePhoneNumber(String pNumber) {
// 1st Case - +91 9765463742 have to check for + sign
boolean flag = false;
int index;
String specialCharacter = "!##$%^&*()-/`~:<>/?|=.,";
if (pNumber.startsWith("+") && pNumber.length() == 14) {
for (index = 1; index < pNumber.length(); index++) {
if (!(Character.isDigit(pNumber.charAt(index)) || Character.isSpaceChar(pNumber.charAt(index)))
&& (specialCharacter.contains(Character.toString(pNumber.charAt(index)))
|| Character.isLetter(pNumber.charAt(index)))) {
flag = true;
break;
}
}
} else {
flag = true;
}
if (!flag) {
System.out.println("Number " + pNumber + " is Valid");
} else {
System.out.println(pNumber + " Number is Invalid");
}
}
Note that I've moved System.out.println(pNumber.charAt(index) + " " + pNumber + " Number is Invalid"); out of the loop so that this message gets printed only once.
Test code:
ValidatePhoneNumber phoneNumber = new ValidatePhoneNumber();
phoneNumber.validatePhoneNumber("+91 975644#742");
phoneNumber.validatePhoneNumber("+91 9765463742");
Output:
+91 975644#742 Number is Invalid
Number +91 9765463742 is Valid

error msgs after second loop attempt

I'm working on another assignment and am stuck. First off, I realize I probably won't get the results I want from this code, but at the moment I can't run the code to even see how close or far away I am. I'm sure I'm missing something simple and hope that something will pop out to someone here so I can move past this point. My mother tongue is English but I'm living in Sweden and trying to learn code in a Swedish class so I added //for translations.
Again, I am working with very basic code so am not looking for an easy hack, more of just some insight to where I have gone wrong.
My assignment is to ask the user to enter 10 numbers, store those as an array. Then, offer the user 4 options to calculate those numbers and a 5th option to quit the program.
Here's what I have so far:
package inlämningsuppgift3;
import java.util.Scanner;
import java.util.Arrays;
public class Inlämningsuppgift3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal = 0;
int[] num = new int[10];
int sum = 0;
int min = 0;
int max = 0;
for (nr = 0; nr < 10; nr++) {
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr] = tal;
if (nr == 0) { //first number
min = tal;
max = tal;
}
else { // All other numbers
if (tal > max) { max = tal; }
if (tal < min) { min = tal; }
}
sum = sum + tal;
}
{
// What would you like to do?
System.out.println("Välj vad du vill göra?");
// Show largest number
System.out.println("1: Visa storsta talet.");
// Show smallest number
System.out.println("2: Visa minsta talet.");
// Show average
System.out.println("3: Visa medeltalet.");
// Show all numbers
System.out.println("4: Visa alla inmatade tal.");
// Quit
System.out.println("5: Avsluta");
}
do {
int k = input.nextInt();
if (k == 1) {
// Largest number is:
System.out.println("Storsta talet är: " + max);
}
else if (k == 2) {
// Smallest number is:
System.out.println("Minsta talet är: " + min);
}
else if (k == 3) {
// Average number is:
System.out.println("Medeltalet är: " + sum/10);
}
else if (k == 4) {
// All the entered numbers:
System.out.println("Alla tal: " + num[10] + ", ");
}
else if (k==5) {
// Goodbye
System.out.println("Hej då!");
break;
}
else {
System.out.println("Felaktigt, prova igen.");
// Unrecognized, try again.
}
while (k<5);
}
}
}
I'm getting error on the last 3 } and I'm not sure why. Are they in the wrong place? I've tried moving them around, I've tried deleting them (obviously, didn't help either) I tried changes to my {} placement above in the code and just haven't found a way around this error. Thank you in advance for any input!
java do-while syntax is:
do {
// Statements
}while(Boolean_expression);
so, change it to:
int k = 0;
do {
k = input.nextInt();
if (k == 1) {
System.out.println("Storsta talet är: " + max);
} else if (k == 2) {
System.out.println("Minsta talet är: " + min);
} else if (k == 3) {
System.out.println("Medeltalet är: " + sum / 10);
} else if (k == 4) {
System.out.println("Alla tal: " + num[10] + ", ");
} else if (k == 5) {
System.out.println("Hej då!");//good bye
break;
} else {
System.out.println("Felaktigt, prova igen.");
}
} while (k < 5) ;
and after while line must be two } now.
Hej Hej!
I made the modifications I think like you asked to make it 'just about work'
package Dunno;
import java.util.Scanner;
public class NumberCollector { //No special characters in source files,
//Can get transformed during deployment
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal =0;
int[] num = new int[10];
int sum = 0;
int min=0;
int max=0;
for (nr=0; nr<10; nr++)
{
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr]=tal;
if(nr == 0) //first number
{
min=tal;
max=tal;
}
else //all other numbers
{
if(tal>max)max =tal;
if(tal<min) min=tal;
}
sum = sum + tal;
}
System.out.println("Välj vad du vill göra?");
//what would you like to do?
System.out.println("1: Visa storsta talet.");
//Show largest number
System.out.println("2: Visa minsta talet.");
//show smallest number
System.out.println("3: Visa medeltalet.");//show average
System.out.println("4: Visa alla inmatade tal.");
//show all numbers
System.out.println("5: Avsluta");//quit
while (true) //Moved the stop condition to start of the loop makes it easier to read logically.
{
int k = input.nextInt();
if (k==1)
{
System.out.println("Storsta talet är: " + max);
//largest number is:
}
else if (k==2)
{
System.out.println("Minsta talet är: " + min);
//smallest number is:
}
else if (k==3)
{
System.out.println("Medeltalet är: " + sum/10);
//average number is:
}
else if (k==4)
{
System.out.println("Alla tal: " + num[10] + ", ");
//all the entered numbers:
}
else if (k==5)
{
System.out.println("Hej då!");//good bye
break;
}
else
{
System.out.println("Felaktigt, prova igen.");
//unrecognized, try again.
}
};
}
}
I only had to move around some braces.
It seems to broadly do what you want? It throws an exception if you ask for result 4, I'll leave that to you :)
Maybe this will be a good starting point? Consider replacing the loop with a switch/case condition would be nicer to read and maintain?

how can i Return an error when typing neither Y/N?

How do i return an error and ask the question Do you want to try again (Y/N)? again when the user entered neither Y/N as an answer?
package randomgenerate;
/**
*
* #author Trung
*/
public class World {
public static void main(String[] args) {
int max=0;
int min=0;
double aver = 0;
int option;
rg a = new rg();
a.generate();
a.count();
System.out.println("Max number is "+ a.maximum(max));
System.out.println("Average number is "+ a.average(aver));
System.out.println("Min number is "+ a.minimum(min));
System.out.println("Do you want to run it again (y/n)?: ");
option = a.getchoice();
switch (option)
{
case 1:
{
a.generate();
a.count();
System.out.println("Max number is "+ a.maximum(max));
System.out.println("Average number is "+ a.average(aver));
System.out.println("Min number is "+ a.minimum(min));
System.out.println("Do you want to run it again (y/n)?: ");
option = a.getchoice();
}
case 2:
{
System.out.println("Program exits.");
System.exit(0);
}
case 3:
{
System.out.println("Invalid. Please enter gyh or gnh: ");
a.getchoice();
}
}
}
}
package randomgenerate;
import java.util.Scanner;
/**
*
* #author Trung
*/
public class rg {
//generate 100 random number
int s[]= new int[101];
public void generate (){
int i, random;
System.out.println("Generating 100 random integers between 0 and 9");
for (i=1; i<=100;i++)
{
s[i] = (int)(Math.random()*10+0);
System.out.println("Number "+i+" = "+ s[i]);
}
}
//count
public void count (){
int i;
int count0=0;
int count1=0;
int count2=0;
int count3=0;
int count4=0;
int count5=0;
int count6=0;
int count7=0;
int count8=0;
int count9=0;
for (i=1; i<=100; i++)
{
if (s[i]==0)
{
count0++;
}
else if (s[i]==1)
{
count1++;
}
else if (s[i]==2)
{
count2++;
}
else if (s[i]==3)
{
count3++;
}
else if (s[i]==4)
{
count4++;
}
else if (s[i]==5)
{
count5++;
}
else if (s[i]==6)
{
count6++;
}
else if (s[i]==7)
{
count7++;
}
else if (s[i]==8)
{
count8++;
}
else if (s[i]==9)
{
count9++;
}
}
if (count0 <= 1)
{
System.out.println("0 occurs "+ count0 + " time");
}
else
{
System.out.println("0 occurs "+ count0 + " times");
}
if (count1 <= 1)
{
System.out.println("1 occurs "+ count1 + " time");
}
else
{
System.out.println("1 occurs "+ count1 + " times");
}
if (count2 <= 1)
{
System.out.println("2 occurs "+ count2 + " time");
}
else
{
System.out.println("2 occurs "+ count2 + " times");
}
if (count3 <= 1)
{
System.out.println("3 occurs "+ count3 + " time");
}
else
{
System.out.println("3 occurs "+ count3 + " times");
}
if (count4 <= 1)
{
System.out.println("4 occurs "+ count4 + " time");
}
else
{
System.out.println("4 occurs "+ count4 + " times");
}
if (count5 <= 1)
{
System.out.println("5 occurs "+ count5 + " time");
}
else
{
System.out.println("5 occurs "+ count5 + " times");
}
if (count6 <= 1)
{
System.out.println("6 occurs "+ count6 + " time");
}
else
{
System.out.println("6 occurs "+ count6 + " times");
}
if (count7 <= 1)
{
System.out.println("7 occurs "+ count7 + " time");
}
else
{
System.out.println("7 occurs "+ count7 + " times");
}
if (count8 <= 1)
{
System.out.println("8 occurs "+ count8 + " time");
}
else
{
System.out.println("8 occurs "+ count8 + " times");
}
if (count9 <= 1)
{
System.out.println("9 occurs "+ count9 + " time");
}
else
{
System.out.println("9 occurs "+ count9 + " times");
}
}
public int maximum (int max)
{
max = s[0];
for (int i=1;i<=100;i++)
{
if(max<s[i])
{
max=s[i];
}
}
return (max);
}
public int minimum (int min)
{
min = s[0];
for (int i=1;i<=100;i++)
{
if(s[i]<min)
{
min=s[i];
}
}
return (min);
}
public double average (double aver)
{
int i = 1;
int subtotal1 = 0;
int subtotal2 = 0;
int subtotal3 = 0;
int subtotal4 = 0;
int subtotal5 = 0;
int subtotal6 = 0;
int subtotal7 = 0;
int subtotal8 = 0;
int subtotal9 = 0;
for (i=1;i<=100;i++)
{
if (s[i]==1)
{
subtotal1 = subtotal1 + s[i];
}
else if (s[i]==2)
{
subtotal2 = subtotal2 +s[i];
}
else if (s[i]==3)
{
subtotal3 = subtotal3 +s[i];
}
else if (s[i]==4)
{
subtotal4 = subtotal4 +s[i];
}
else if (s[i]==5)
{
subtotal5 = subtotal5 +s[i];
}
else if (s[i]==6)
{
subtotal6 = subtotal6 +s[i];
}
else if (s[i]==7)
{
subtotal7 = subtotal7 +s[i];
}
else if (s[i]==8)
{
subtotal8 = subtotal8 +s[i];
}
else if (s[i]==9)
{
subtotal9 = subtotal9 +s[i];
}
}
aver = (subtotal1 + subtotal2 + subtotal3 + subtotal4 + subtotal5 + subtotal6 + subtotal7 + subtotal8 + subtotal9) * 0.01;
return (aver);
}
public int getchoice() {
Scanner reader = new Scanner(System.in);
String selection = reader.nextLine();
if (selection.equals("y") || selection.equals("Y")){
return 1;
}
else if (selection.equals("n") || selection.equals("N")){
return 2;
}
else
{
return 3;
}
}
}
Try something like this:
while(true){
System.out.println("Do you want to try again (Y/N)?");
String input = reader.nextLine();
if(input.equals("N"))
break;
else
continue;
}
you can just add in the getchoice() method :
if(!selection.toLowerCase().equals("y") && !selection.toLowerCase().equals("n") ){
System.out.println("Error");
return this.getchoice();
}
Scanner sc = new Scanner(System.in);
System.out.println("Do you want to run it again (y/n)?: ");
while (!(sc.hasNext() && ((sc.nextLine().equalsIgnoreCase("y"))||
sc.nextLine().equalsIgnoreCase("n")))){
System.out.println("Do you want to run it again (y/n)?: ");
// other code
}
Firstly, refactor the code into a method. Then you can call the method anywhere in your program (currently, you call it twice, so you can replace both versions with this version.
Then, add a loop...
public static int getRunAgain(rg a) {
int option = 3;
System.out.println("Max number is "+ a.maximum(max));
System.out.println("Average number is "+ a.average(aver));
System.out.println("Min number is "+ a.minimum(min));
while(true) {
System.out.println("Do you want to run it again (y/n)?: ");
option = a.getchoice();
if (option != 3) break;
System.out.println("Invalid. Please enter y/n. ");
}
return option;
}
An alternative method would be to put the loop inside the getChoice method.
do
{
System.out.println("Max number is "+ a.maximum(max));
System.out.println("Average number is "+ a.average(aver));
System.out.println("Min number is "+ a.minimum(min));
System.out.println("Do you want to run it again (y/n)?: ");
option = a.getchoice();
}while(option.equals("Y") || !option.equals("N"));
If user enters Y, it will repeat. Aslo, if he enters neither "Y" nor "N", then it will repeat too.

Categories

Resources