as the title suggests I am doing a program for homework that is a slot machine. I have searched around and I am pretty satisfied that the program works correctly enough for me. The problem Im having is on top of generating the random numbers, I am supposed to assign values for the numbers 1-5 (Cherries, Oranges, Plums, Bells, Melons, Bars). Then I am to display the output instead of the number when my program runs. Can anyone get me pointed in the right direction on how to do this please?
import java.util.Random;
import java.util.Scanner;
public class SlotMachineClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Coins = 1000;
int Wager = 0;
System.out.println("Steve's Slot Machine");
System.out.println("You have " + Coins + " coins.");
System.out.println("Enter your bet and press Enter to play");
while (Coins > 0)
{
int first = new Random().nextInt(5)+1;
int second = new Random().nextInt(5)+1;
int third = new Random().nextInt(5)+1;
Wager = input.nextInt();
if(Wager > Coins)
Wager = Coins;
System.out.println(first + " " + second + " " + third);
if(first == second && second == third)
{ Coins = Coins + (Wager * 3);
System.out.println("You won " + (Wager * 3) + "!!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else if((first == second && first != third) || (first != second && first == third) || (first != second && second == third))
{ Coins = Coins + (Wager * 2);
System.out.println("You won " + (Wager * 2) + "!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else {Coins = Coins - Wager;
System.out.println("You Lost!" + "\nPlay Again? if so Enter your bet.");}
}
while (Wager == 0)
{
System.out.println("You ran out of coins. Thanks for playing.");
}
}
}
If you have an int and want to have some String associated with that, there are a couple of ways to do that.
The first one is to have an array of Strings and look them up.
public static String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
public String getNameForReel(int reelValue) {
return text[reelValue];
}
// And to call it...
System.out.println(getNameForReel(first)); //etc...
Or, you can do it in a switch statement (I don't prefer this, but you might):
public String getNameForReel(int reelValue) {
switch(reelValue) {
case 0: return "Cherry";
case 1: return "Bell";
case 2: return "Lemon";
case 3: return "Bar";
case 4: return "Seven";
}
}
You need a lookup table:
String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
Then you can just do
System.out.println(text[first] + " " + text[second] + " " + text[third]);
without creating more methods.
The non-array solution most likely to be used a by new programmer in an intro course would be a nested if-else:
String fruitToPrint = "";
if (num == 0)
fruitToPrint = "Cherries";
else if (num == 1)
fruitToPrint = "Oranges";
else if (num == 2)
fruitToPrint = "Plums";
else if (num == 3)
fruitToPrint = "Bells";
else if (num == 4)
fruitToPrint = "Melons";
else if (num == 5)
fruitToPrint = "Bars";
else
System.out.println("Couldn't assign fruit from num=" + num);
System.out.println("The corresponding fruit was " + fruitToPrint);
Create an array:
String[] s = {Cherries, Oranges, Plums, Bells, Melons, Bars};
Then you can print s[num-1] instead of num (where num is the random int). E.g. if your random int came out to be 2, print s[2-1] i.e. s[1] which will be Orange.
Here's an alternative solution to the question which I think follows best programming practices. This is probably even less allowed for your assignment than an array, and will be a dead giveaway that you got your answer on StackOverflow, but the problem would lend itself to using an enum type with an int->enum mapping:
enum Fruit {
Cherries(1),
Oranges(2),
Plums(3),
Melons(4),
Bars(5);
private static final Map<Integer, Fruit> lookupMap = new HashMap<Integer, Fruit>();
static {
for (Fruit fruit : Fruit.values()) {
lookupMap.put(fruit.getLookup());
}
}
static Fruit fromLookup(int lookup) {
return lookupMap.get(lookup);
}
private final int lookup;
private Fruit(int lookup) {
this.lookup = lookup;
}
int getLookup() {
return lookup;
}
}
void printEnumExample() {
int fruitToPrint = 4;
System.out.println(Fruit.fromLookup(fruitToPrint)); // <- This will print "Melons"
}
Related
I'm trying to write a program that essentially evaluates a 5 card poker hand that is user-generated. One part of the program is that users can choose one variable to randomly change. The issue lies with setting a value for one of my instance variables, right now, my setCards, getCards, and changeOne methods are:
public void setCards(String str) {
this.cards = str;
calculateScore();
history = history + cards + score + changes;
changes++;
}
public String getCards() {
return this.cards;
}
public void changeOne(int pos) {
getCards();
calculateScore();
history = history + cards + score + changes;
randomChar = allCards.charAt((int)(Math.random()*cards.length()));
this.cards = cards.substring(0, pos) + randomChar + cards.substring(pos + 1, cards.length());
changes++;
}
In a separate class, I'm using:
cards = in.nextLine().toUpperCase();
myCards.setCards(cards);
I'm not sure why but whenever I try to use the changeOne method, keeps giving me the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 3, length 0
Which I assume is because it takes cards to be an empty string. I'm not sure what is happening and why it isn't getting the proper value of cards, help would be greatly appreciated.
Entire code:
First class:
import java.util.Scanner;
public class Assignment4{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
FiveCards myCards = new FiveCards();
int position;
String choice, cards;
char charChoice;
final char NEW = 'A';
final char CHANGE = 'B';
final char DISPLAY = 'C';
final char QUIT = 'Q';
do {
System.out.println("Choose (A: Make New Cards), (B: Change One Card), (C: Display Data), or (Q: Quit)");
choice = in.next();
charChoice = choice.toUpperCase().charAt(0);
switch(charChoice) {
case NEW:
System.out.println("*** Make New FiveCards ***");
System.out.println("Type five letters without space: ");
in.next();
cards = in.nextLine().toUpperCase();
myCards.setCards(cards);
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case CHANGE:
System.out.println("*** Change One Card ***");
System.out.println("Type one position to change (0-4): ");
position = in.nextInt();
myCards.changeOne(position);
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case DISPLAY:
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case QUIT:
System.out.println("*** End of Program ***");
break;
default:
System.out.println("Invalid input. Try Again");
break;
}
}while(charChoice!=QUIT);
}
}
Second class is:
public class FiveCards {
private String cards, history;
private int score, changes, counter;
private String allCards = "1234567890JQK";
private char randomChar;
public FiveCards() {
}
public void setCards(String str) {
this.cards = str;
calculateScore();
history = history + cards + score + changes;
changes++;
}
public String getCards() {
return this.cards;
}
public void changeOne(int pos) {
calculateScore();
history = history + cards + score + changes;
randomChar = allCards.charAt((int)(Math.random()*cards.length()));
this.cards = cards.substring(0, pos) + randomChar + cards.substring(pos + 1, cards.length());
System.out.println(cards);
changes++;
}
public void calculateScore() {
for(int i = 0; i<cards.length(); i++) {
for(int j = 0; j<cards.length(); j++) {
if((cards.charAt(i) == cards.charAt(j)) && (i != j)) {
counter++;
}
}
}
if(counter == 2) {
score = 1;
}
else if(counter == 4) {
score = 2;
}
else if(counter == 6) {
score = 3;
}
else if(counter == 8) {
score = 4;
}
else {
score = 0;
}
}
public String displayData() {
calculateScore();
history = history + cards + score + changes;
if(cards.length()<=1) {
return cards + " " + score + " " + changes;
}
else {
return "Empty" + " " + score + " " + changes;
}
}
}
First problem:
allCards.charAt(...). In the setCards you assign string to cards, but here you pick character from allCards. What is content of allCards? When it is assigned? I it assigned at all? (your code doesn't show this).
And the second problem:
Math.random()*cards.length()
Valid indexes of characters in the String are from 0 to length() - 1 inclusive, but the way you generate random index, you can give you index from 0 to length() inclusive. Change it to the Math.random()*(cards.length() - 1).
So the program works, it just has a few things that I cant seem to fix:
1) It feels like it can be simplified using more/different methods. I don't want ot be redundant.
2) At the end of the program, I can't get figure out how to turn the two final scores into "first" and "second" We aren't allowed to use several sopln's the program has to be able to identify which of the two scores is highest and be able to recognize if it was the first or second applicant. Here is the code
import java.util.Scanner;
public class Admissions {
public static void main(String[] args) {
questionaire();
Scanner console = new Scanner(System.in);
double first = designation(console, " first ");
double second = designation(console, " second ");
System.out.println("First applicant overall score = " + first);
System.out.println("Second applicant overall score = " + second);
System.out.println();
double mostQualified = (Math.max(first,second));
System.out.println("The " + mostQualified + " applicant is better qualified.");
}
// *** Methods ***
public static void questionaire() {
System.out.println(" This program compares two applicants to \n " +
"determine which one is the stronger candidate. \n " +
"For each candidate please provide either SAT \n " +
"or ACT scores, plus a weighted GPA.");
System.out.println();
}
public static double designation(Scanner console, String x) {
System.out.println("Information for the" + x + "applicant: \n" +
"do you have 1) SAT scores or 2) ACT scores?");
int answer = console.nextInt();
if(answer == 2){
return act(console);
} else if (answer == 1){
return sat(console);
}else{
return cheat();
}
}
public static double designation2(Scanner console) {
System.out.println("Information for the second applicant: \n" +
"do you have 1) SAT scores or 2) ACT scores?");
int answer2 = console.nextInt();
if(answer2 == 2){
return act(console);
} else if (answer2 == 1){
return sat(console);
}else {
return cheat();
}
}
public static double act(Scanner console) {
System.out.println("ACT English?");
int actEnglish = console.nextInt();
if ((actEnglish < 1) || (actEnglish > 36)){
return cheat();
}
System.out.println("ACT math?");
int actMath = console.nextInt();
if ((actMath < 1) || (actMath > 36)){
return cheat();
}
System.out.println("ACT reading?");
int actReading = console.nextInt();
if ((actReading < 1) || (actReading > 36)){
return cheat();
}
System.out.println("ACT science?");
int actScience = console.nextInt();
if ((actScience < 1) || (actScience > 36)){
return cheat();
}
System.out.println("Overall GPA?");
double overallGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
System.out.println("Maximum GPA?");
double maxGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
int actScore = ((actScience - 1) + (actMath - 1) + (actReading - 1) + (actEnglish - 1) / (4*35));
double actGPA = ((overallGPA) / (maxGPA) * 100);
double finalActScore = (actScore + actGPA);
return finalActScore;
}
public static double sat(Scanner console){
System.out.println("SAT math?");
int satMath = console.nextInt();
if ((satMath < 200) || (satMath > 800)){
return cheat();
}
System.out.println("SAT verbal?");
int satVerbal = console.nextInt();
if ((satVerbal < 200) || (satVerbal > 800)){
return cheat();
}
System.out.println("Overall GPA?");
double overallGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
System.out.println("Maximum GPA?");
double maxGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
int satScore = ((satVerbal - 200) + (satMath - 200)) / (2*600);
double satGPA = ((overallGPA) / (maxGPA) * 100);
double finalSatScore = (satScore + satGPA);
return finalSatScore;
}
public static double cheat(){
System.out.println("YOU'RE A CHEATER.");
System.exit(-1);
return 0;
}
1) You can factorize part of your code
You already did it with your designation method which is good. You can delete the designation2 method.
In your act method. There is 4 repetitions of this test :
if ((value < 1) || (value > 36)){
return cheat();
}
You can factorise it inside a method like this :
private void checkScoreForAct(int value) {
if ((value < 1) || (value > 36)){
cheat();
}
}
Then in your act method, you call it to check the ACT score for the english, math, reading and science.
System.out.println("ACT English?");
int actEnglish = console.nextInt();
checkScoreForAct(actEnglish);
That's one exemple but you could also factorise the part where you calculate the overall GPA (present in the act and sat method).
Same for when you calculate the satGPA and actGPA, you could put this logic in a method.
2) How to turn the two final scores into first and second ?
You can easily check who is the applicant who have the best score.
public static String FIRST = "first";
public static String SECOND = "second";
public static String BOTH = "both";
String bestApplicant;
if (first == second) {
bestApplicant = BOTH;
} else if (first > second) {
bestApplicant = FIRST;
} else {
bestApplicant = SECOND;
}
double maxScore = (Math.max(first,second));
if (bestApplicant.equals(BOTH)) {
System.out.println("Both applicant are equally qualified with a score of " + maxScore);
} else {
System.out.println("The " + bestApplicant + " applicant is better qualified with a score of " + maxScore);
}
I'm not sure if your parameters exclude this, as what you say you aren't allowed to do makes no sense to me. Here's what you seem to be asking how to do:
String mostQualified = (first > second)? "first" : "second";
double bestScore = Math.max(first, second);
System.out.println("The " + mostQualified
+ " applicant is better qualified, with a score of "
+ bestScore);
Sample result:
The first applicant is better qualified, with a score of 88.1
I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();
So my objective is to create a maths game where the user selects if he/she wants a maths question from a file or a random generate one consisting of the 4 maths elements in 3 difficulties.I have created a lot of methods... I have an idea where im going but now im stuck. I need to have it so it keeps a score of questions answered correctly. How do i return the points to the main method and have the game going until the user presses 3 on the gamePlay()method
public class MathsGameProject2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int score;
int points = 0;
int questionType;
System.out.print("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
questionType = keyboard.nextInt();
while (questionType != 3) {
if (questionType == 1) {
questionFromFile();
} else if (questionType == 2) {
randomQuestion();
} else {
System.out.println("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
}
}
}
public static questionFromFile() {
}
public static randomQuestion() {
Scanner keyboard = new Scanner(System.in);
int difficulty;
System.out.println("Please enter the difficulty you want to play." + "\n 1. Easy" + "\n 2. Medium" + "\n 3. Hard\n");
difficulty = keyboard.nextInt();
if (difficulty == 1) {
easy();
} else if (difficulty == 2) {
medium();
} else if (difficulty == 3) {
hard();
} else {
System.out.println("Please enter a number between 1-3\n");
}
}
public static easy() {
Scanner keyboard = new Scanner(System.in);
int mathElement;
System.out.print("What element of maths do you want?" + "\n1 Additon" + "\n2 Subtraction" + "\n3 Multiplication" + "\n4 Division\n");
mathElement = keyboard.nextInt();
if (mathElement == 1) {
easyAdd();
} else if (mathElement == 2) {
easySub();
} else if (mathElement == 3) {
easyMulti();
} else if (mathElement == 4) {
easyDiv();
} else {
System.out.println("Please enter a number between 1-4\n");
}
}
public static easyAdd() {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
int num = rand.nextInt(10) + 1;
int num2 = rand.nextInt(10) + 1;
int correct = num + num2;
int answer;
System.out.print("What is the answer of " + num + " + " + num2 + " ?");
answer = keyboard.nextInt();
if (answer == correct) {
}
}
In order to keep track of how many questions the user answers successfully, you will need to:
For each question, return whether or not the user answered correctly
Have a counter which increments whenever a user answers a question correctly
Optionally, have a counter which increments whenever a question is answered wrong
For #1, you can use a boolean return value for specifying if the question was answered successfully.
return (answer == correct);
You will want to propagate that return value all the way up to the main() method.
static void main() {
....
boolean isCorrect = randomQuestion();
....
}
static boolean randomQuestion() {
....
return easy();
....
}
static boolean easy() {
....
return easyAdd();
....
}
static boolean easyAdd() {
...
return (answer == correct);
}
Then for #2 and #3, you can increment counter(s) defined in main based on the value returned by randomQuestion()
int numberCorrect = 0;
int numberWrong = 0;
....
boolean isCorrect = randomQuestion();
if (isCorrect) {
numberCorrect++;
} else {
numberIncorrect++;
}
Additionally (no pun intended), you can use a while loop to continuously receive user input until you get your exit code, which in this case is 3. One way to do this is to use a while(true) loop and break out when the user enters 3.
while (true) {
/* Get user input */
....
if (questionType == 3) {
break;
}
}
Finally, after your loop, you can simply print out the value of your numberCorrect and numberIncorrect counters.
Hope this helps.
I am trying to make the program end when total reaches 10, but for some reason my while loop continues counting when it reaches 10. I have the int percent to find the percent once 10 questions are answered.
import java.util.*;
class CAI {
private static Scanner input;
public static void main(String[] arguments) {
menu();// calls menu method
compute();// calls compute method
}
public static void menu() {// method that displays menu
System.out.println(" CAI MENU ");
System.out.println("\n)");
System.out
.println("\n1) DIFFICULTY 1\n2) DIFFICULTY 2\n3) DIFFICULTY 3\n4) DIFFICULTY 4");
}
public static int[] Blop() {
Random rand = new Random();
int arr[] = new int[8];
arr[0] = rand.nextInt(9);
arr[1] = rand.nextInt(9);
arr[2] = rand.nextInt(99);
arr[3] = rand.nextInt(99);
arr[4] = rand.nextInt(999);
arr[5] = rand.nextInt(999);
arr[6] = rand.nextInt(9999);
arr[7] = rand.nextInt(9999);
return arr;
}
public static void compute() {
int difficulty;
input = new Scanner(System.in);
System.out.println("Enter an option: ");
difficulty = input.nextInt();
int total = 0;
int percent = 0;
while (total <= 10) {
if (difficulty == 1) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[0] + " times "
+ num[1] + " ? :");
total++;
System.out.print(total);
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[0] * num[1])) {
System.out.print(Correct);
percent++;
} else {
System.out.print(Wrong);
}
} while (ans != (num[0] * num[1]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
}
if (difficulty == 2) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[2] + " times "
+ num[3] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[2] * num[3])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[2] * num[3]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
if (difficulty == 3) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[4] + " times "
+ num[5] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[4] * num[5])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[4] * num[5]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
if (difficulty == 4) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[6] + " times "
+ num[7] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[6] * num[7])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[6] * num[7]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
System.out.print(100 / 10 * percent);
}
}
Your while loop is declared:
"while total is less than or equal to ten"
which means it will run once again at 10.
just make it while total <10
edit: you also don't increment total anywhere.
total++;
will do it.
edit: it appears you do. sorry the code is hard to read on a phone.
There could be multiple reasons for this happening. One such reason is that if the variable difficulty does not equal one(this variable is nowhere to be found in your code also), then total will never be incremented, and as a result the first while loop will last forever. Because you have not shared all of your code, it could also be that ans != (num[0] * num[1] is never true, and as a result, the innermost do/while loop is executed forever. If you post the rest of your code, we will be able to assist you more.
EDIT: OK, thanks. It looks like your problem is due to the fact that while the user continues to get the question wrong, they cannot escape the inner while loop, therefore not being able to escape the outer while loop. The solution to that is easy, simply changing while (ans != (num[4] * num[5])); to ans != (num[0] * num[1]) && total < 10, thereby giving the code a way to escape while the user is getting the question wrong.