I have to set up a math program that supplies random questions to the user based on their year level, and if they're doing well raise the difficulty. I've set up this code here that runs through questions and if they meet the requirements it displays the harder questions, however if "i" that i use to determinate how member questions they've done if separate the program will run the harder questions then go back and finish the easier questions
So basically I've tried to write a method for global "i" which all other methods will use, however when i replace "i" with the method it stops counting and continues to display questions infinitely and i don't know how to fix this.
import java.util.Scanner;
import java.util.*;
import java.util.Date;
public class Quiz {
public static void main(String[] args) {
int answer;
int correct;
double current_score = 100.00;
// int i = 0;
while (questionsDone() < 10) { // start of question loop
int random = (int) (Math.random() * 9 + 0);
int random2 = (int) (Math.random() * 9 + 0);
System.out.print("What is the sum of" + " ");
System.out.print(random);
System.out.print(" + " + random2 + " ");
System.out.print("=" + " ");
Scanner scan = new Scanner(System.in);
//answer
answer = scan.nextInt();
correct = random + random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10.00);
}
System.out.println("Your current percentage is " + current_score); // end of result display
// i++; // raise number of questions given by 1
if (questionsDone() == 5 && current_score >= 75) { // code to move up or down year level
System.out.println("You are doing well! Let's increase the difficulty a little");
Year1_10Questions();
}
}
}
public static void Year1_10Questions() {
int i = 0;
int answer;
int correct;
double current_score = 100.00;
while (i < 10) { // start of question loop
int random = (int) (Math.random() * 9 + 0);
int random2 = (int) (Math.random() * 9 + 0);
int random3 = (int) (Math.random() * 2 + 1);
String operator = "";
switch (random3) {
case 1:
operator = "+";
break;
case 2:
operator = "-";
break;
}
System.out.print("What is the sum of ");
System.out.print(" " + random + " ");
System.out.print(operator + " ");
System.out.print(random2 + " ");
Scanner scan = new Scanner(System.in);
//answer
answer = scan.nextInt();
if (random3 == 1) {
correct = random + random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10);
}
} else if (random3 == 2) {
correct = random - random2;
if (answer == correct) { // start of result display
System.out.println("You are correct");
} else if (answer != correct) {
System.out.println("That wasn't right");
current_score = (current_score - 10);
}
}
System.out.println("Your current percentage is " + current_score); // end of result display
i++; // raise number of questions given by 1
}
} // end of year 1_10 questions
public static int questionsDone() {
int i = 0;
i++;
return i;
}
}
Since all the methods are in the same class, you can define i on class level:
public class Quiz {
static int i;
...
}
Related
I have to make a dice game using Scanner.
I will have 3 dice and the user will be asked to choose which one to throw.
The user can't throw all at once - just pick one after another.
It's not allowed to use the same die twice in one round of 3 throws, but user can take the dices in the order user wants.
The game is about to hit a sum of 12.
I have tried to use if statements and switch - but I haven't found a solution for that user can't take same die twice.
I erased some code, but I tried again with switch.
My code is:
// Declaring variables
int diceOne = 0;
int diceTwo = 0;
int diceThree = 0;
int rolls;
int rollOne;
int rollTwo;
int rollThree;
int rounds=1;
int sumOfDice =0;
String welcome = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ]";
String userInfo = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";
// Create Scanner to obtain data input from user.
Scanner twelf = new Scanner(System.in);
// Welcome message
System.out.print("\n" + welcome + "\n");
// while loop
while(rounds<=3){
System.out.print("\n"+userInfo + " ");
rolls = twelf.nextInt();
rounds= rounds + 1;
rolls =+ rolls;
switch(rolls){
case 1:
diceOne = (int)(Math.random()*6)+1;
System.out.print("Dice 1 hits " + diceOne);
break;
case 2:
diceTwo = (int)(Math.random()*6)+1;
System.out.print("Dice 2 hits " + diceTwo);
break;
case 3:
diceThree = (int)(Math.random()*6)+1;
System.out.print("Dice 3 hits " + diceThree);
break;
default:
}
It's still a little vague what exactly the program is asking and what the output should be. But it seems that you might need a conditional statement that checks if that certain dice had been rolled already.
int diceOne = 0;
int diceTwo = 0;
int diceThree = 0;
int rolls;
int rollOne;
int rollTwo;
int rollThree;
int rounds = 1;
int sumOfDice = 0;
String welcome = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ]";
String userInfo = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";
// Create Scanner to obtain data input from user.
Scanner twelf = new Scanner(System.in);
// Welcome message
System.out.println("\n"+welcome +"\n");
// while loop
while(rounds<=3)
{
System.out.print("\n" + userInfo + " ");
rolls = twelf.nextInt();
rounds = rounds + 1;
rolls = +rolls;
switch (rolls) {
case 1:
if(diceOne > 0) {
System.out.println("Cannot roll same dice more than once"); // add a condition that meets your needs to check before rolling the die. //
} else {
diceOne = (int) (Math.random() * 6) + 1;
System.out.print("Dice 1 hits " + diceOne);
break;
}
case 2:
if(diceTwo > 0) {
System.out.println("Cannot roll same dice more than once"); // add a condition that meets your needs to check before rolling the die. //
} else {
diceTwo = (int) (Math.random() * 6) + 1;
System.out.print("Dice 2 hits " + diceTwo);
break;
}
case 3:
if(diceThree > 0) {
System.out.println("Cannot roll same dice more than once"); // add a condition that meets your needs to check before rolling the die. //
} else {
diceThree = (int) (Math.random() * 6) + 1;
System.out.print("Dice 3 hits " + diceThree);
break;
}
default:
}
}
}
}
Instead of using switch statements, you may want to use a map to track if dice were rolled or not. rolledDiceMap will store your three dice, it has an Integer key and a Dice value.
For this I created a Dice class that has two fields:
value: the random value that gets rolled);
rolled: boolean flag, if this is true repeat the while loop until the user enters a good value and moves to the next round.
I tried to add some, hopefully, useful comments to the code below:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class RollDice {
public static final String WELCOME = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ] ";
public static final String USER_INFO = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";
public static final String WRONG_DIE_VALUE = "Please enter a good die value";
public static final String DIE_ROLLED = "Die already rolled, please roll a new die";
public static final String CONGRATULATIONS = "You rolled 12, congratulations !";
public static final String GOOD_LUCK = "Good luck next time, your dice rolled: ";
public static void main(String[] args) {
int rounds = 1;
int sum = 0;
// Create Scanner to obtain data input from user.
Scanner twelf = new Scanner(System.in);
System.out.println(WELCOME);
Map<Integer, Dice> rolledDiceMap = new HashMap();
// Generate a key value pair for three dice e.g.: (1, Dice); (2, Dice); (3, Dice)
for (int i = 1; i <= 3; i++) {
rolledDiceMap.put(i, new Dice());
}
while (rounds <= 3) {
System.out.print(USER_INFO);
int rolledValue = twelf.nextInt();
// check if user input is valid (user entered 1,2 or 3)
if (rolledDiceMap.containsKey(rolledValue)) {
Dice rolledDie = rolledDiceMap.get(rolledValue);
// check if die was rolled, if yes, repeat round
if(rolledDie.wasRolled()){
System.out.println(DIE_ROLLED);
// repeat round
continue;
}
// set rolled to true and assign a random value
rolledDie.setRolled(true);
int value = (int) (Math.random() * 6) + 1;
rolledDie.setValue((int) (Math.random() * 6) + 1);
sum += value;
System.out.println("You rolled: " + value);
} else {
System.out.println(WRONG_DIE_VALUE);
// repeat round
continue;
}
// move to next round
rounds++;
}
// print result
if(sum == 12){
System.out.println(CONGRATULATIONS);
} else{
System.out.println(GOOD_LUCK + sum);
}
}
static class Dice {
private Integer value;
private boolean rolled;
public Integer getValue() {
return this.value;
}
public void setValue(Integer value) {
this.value = value;
}
public boolean wasRolled() {
return this.rolled;
}
public void setRolled(boolean rolled) {
this.rolled = rolled;
}
}
}
Edit for the approach described in comments, without using map:
import java.util.Scanner;
public class RollDice {
public static final String WELCOME = "[ Welcome to the game 12! Try to get the total sum of 12 by rolling 1-3 dices ] ";
public static final String USER_INFO = "Enter which dice you want to roll [1,2,3] (Exit game with q): ";
public static final String DICE_ALREADY_ROLLED = "Die already rolled, please roll a new die";
public static final String ROUND_WON = "You rolled 12, you won the round !";
public static final String ROUND_LOST = "Rounds lost, your die rolled more than 12. ";
public static final String ROUND_TIED = "You neither lost, nor won, round tied.";
public static final String INVALID_INPUT = "Please enter a number between 1-3 or Q to quit";
public static final String THANKS_FOR_PLAYING = "Quitting game.. thanks for playing!";
public static void main(String[] args) {
int totalRounds = 1;
int rolledDice, sum = 0;
int roundsWon = 0, roundsLost = 0, roundsTied = 0;
int dice1Value, dice2Value, dice3Value;
boolean dice1Rolled = false, dice2Rolled = false, dice3Rolled = false;
// Create Scanner to obtain data input from user.
Scanner twelf = new Scanner(System.in);
String input;
System.out.println(WELCOME);
while (true) {
System.out.print(USER_INFO);
input = twelf.nextLine();
// The program should continue until the user chooses to cancel the game. Quit the game by pressing 'q' or 'Q'
if(input.equalsIgnoreCase("q")){
System.out.println(THANKS_FOR_PLAYING);
break;
}
// check if user input is valid
try{
rolledDice = Integer.parseInt(input);
}catch(NumberFormatException e){
System.out.println(INVALID_INPUT);
continue;
}
// The program must randomly find a value on the selected dice and then calculate the score.
switch(rolledDice){
case 1:
if(dice1Rolled){
System.out.println(DICE_ALREADY_ROLLED);
continue;
} else{
dice1Value = (int) (Math.random() * 6) + 1;
sum += dice1Value;
dice1Rolled = true;
System.out.println("You rolled " + dice1Value + "; sum of dice: " + sum);
break;
}
case 2:
if(dice2Rolled){
System.out.println(DICE_ALREADY_ROLLED);
continue;
} else{
dice2Value = (int) (Math.random() * 6) + 1;
sum += dice2Value;
dice2Rolled = true;
System.out.println("You rolled " + dice2Value + "; sum of dice: " + sum);
break;
}
case 3:
if(dice3Rolled){
System.out.println(DICE_ALREADY_ROLLED);
continue;
} else{
dice3Value = (int) (Math.random() * 6) + 1;
sum += dice3Value;
dice3Rolled = true;
System.out.println("You rolled " + dice3Value + "; sum of dice: " + sum);
break;
}
default:
System.out.println(INVALID_INPUT);
continue;
}
/* The program should also present the number of wins and the number of rounds lost.
The definition of profit is when the sum of the dice is 12 (regardless of the number of dice) and
the definition of loss is a sum exceeding 12 after all three dice have been rolled.
If the sum after three rolls is less than 12, there will be no profit or loss, but you go straight to the next round*/
// you can move to next round in 2 rounds, by rolling 6 with 2 dice
if(sum == 12){
System.out.println(ROUND_WON);
roundsWon++;
totalRounds++;
// reset dice rolled & sum
dice1Rolled = false;
dice2Rolled = false;
dice3Rolled = false;
sum = 0;
// show rounds won/lost/tied
System.out.println("totalRounds: " + totalRounds + "; roundsWon: " + roundsWon + "; roundsTied: " + roundsTied + "; roundsLost: " + roundsLost);
continue;
}
// If all 3 dice rolled, move to next round
if(dice1Rolled && dice2Rolled && dice3Rolled){
if(sum > 12){
roundsLost++;
System.out.println(ROUND_LOST);
}
if(sum < 12){
roundsTied++;
System.out.println(ROUND_TIED);
}
// reset dice rolled, move to next round
dice1Rolled = false;
dice2Rolled = false;
dice3Rolled = false;
sum = 0;
// show rounds won/lost/tied
System.out.println("totalRounds: " + totalRounds + "; roundsWon: " + roundsWon + "; roundsTied: " + roundsTied + "; roundsLost: " + roundsLost);
}
}
}
}
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%
I have a math quiz game I am making and I am not sure how to loop it, let's say 50 times. It ends after answering only 2 questions. I also want to add lives so after you get three questions wrong it ends the program. How am I able to do this?
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
}else {
System.out.println("Wrong!");
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
System.out.println("You got " + correct + " correct answers.");
After the int correct = 0;
add a lives counter.
eg:
int lives =3;
then start a while loop
while(lives > 0){
reduce the lives if a question is incorrect (where you put "wrong!" message)
lives--;
at the end of the while loop (before no of correct answers is printed out)
remember to put the last }
This will keep looping till you lose your lives
A couple things:
-There are multiple java structures which allow you to loop. The main loops out there in any kind of programming language are for loop, while loop, and do-while loop (uncommon)
-You can create lives by defining a variable and checking it in every iteration (an iteration is each "run" through the code of a loop).
Your code after implementing this 2 things would look like this:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
int lives = 3;
//The for loop is read as: having i equal 25 and the variable lives, iterate if i is lower than 25 AND lives is higher than 0. After an iteration, add 1 to i;
for (int i=25, lives; i<25 && lives > 0; i++) {
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
} else {
System.out.println("Wrong!");
lives--;
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
lives--;
} //Forgot this bracket
} //Closes the for loop
System.out.println("You got " + correct + " correct answers.");
See if below example works as you intend. Here I have given the loop count as 5. So there will be 5 "addition" questions and 5 "multiplication" questions.
I'm printing the question number also. So, now the output is more clear.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int correct = 0;
for (int i = 0; i < 5; i++) {
int Number1 = (int) (20 * Math.random()) + 1;
int Number2 = (int) (20 * Math.random()) + 1;
System.out.println("Question " + (i*2+1));
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
}
else {
System.out.println("Wrong!");
}
System.out.println();
System.out.println("Question " + (i*2+2));
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}
else {
System.out.println("Wrong!");
}
System.out.println();
}
System.out.println("You got " + correct + " correct answers.");
}
}
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?
import java.util.Random;
import java.util.Scanner;
public class HiLo {
/**
* Nick Jones
* 2/10/2015
* High or Low
*/
public static boolean high() {
int x;
boolean answer;
Random randomGenerator = new Random();
x = randomGenerator.nextInt(9 - 1) + 1;
System.out.println("number is " + x);
if (x > 6 && x < 14) {
System.out.println("You win!");
answer = true;
return answer;
} else {
System.out.println("You lose!");
answer = false;
return answer;
}
}
public static boolean low() {
int x;
boolean answer;
Random randomGenerator = new Random();
x = randomGenerator.nextInt(9 - 1) + 1;
System.out.println("number is " + x);
if (x > 0 && x < 7) {
System.out.println("You win!");
answer = true;
return answer;
} else {
System.out.println("You lose!");
answer = false;
return answer;
}
}
public static void main(String[] args) {
int points = 1000;
int risk;
int guess;
boolean answer;
int again;
do {
System.out.println("you have " + points + " points.");
Scanner input = new Scanner (System.in);
System.out.println ("Input number of points to risk: ");
risk = input.nextInt();
System.out.println ("predict <1-high, 0-low>: ");
guess = input.nextInt();
if (guess == 1) {
answer = high();
} if (guess == 0) {
answer = low();
}
if (answer = true) {
points = points + (risk*2);
**} if (answer = false) {
points = points - risk;**
}
System.out.println("You have " + points + " points.");
System.out.println("play again?<yes-1, no-0> ");
again = input.nextInt();
} while (again == 1);
}
}
This program is meant to start with the player having a score of 1000 points a number is then randomly generated and they chose a amount of their score to 'risk' then chose high or low (low - 1-6. high - 8-13) if their guess is correct their risk is doubled and added back into their score. If incorrect then risk is subtracted from score. my boolean statment seems to be stopping the program from
if (answer = false) {
points = points - risk;
this part, so my boolean never returns false is what I believe my problem is. because when run it only ever allows the player to win, never to lose, it will output that 'you lose' but still add the points as if they had won.
You are using the assignment operator =, so answer is always true. The comparison operator for equality is ==, as you have already used elsewhere in your code. But answer is already a boolean. There is no need to use == to compare it; just use it. Change
if (answer = true) {
points = points + (risk*2);
} if (answer = false) {
points = points - risk;
}
to
if (answer) {
points = points + (risk*2);
} else {
points = points - risk;
}