It goes like this: The purpose of the Project4Appclass is to create a math game for children to play thatwill strengthen their addition and subtraction skills. In order for the game to allow the student to get enough practice, the game will ask the student 10 questions. If the student gets the first 10 questions correct, the game should end. Otherwise, the game should continue until one of two things happen: 1) the student’s percent of correct answers reaches at least 85%, or 2) the student hascompleted 20 questions. When the game ends, the student should be told the number of addition questions he/she got correct and incorrect as well as the number of subtraction questions he/she got correct and incorrect. It should also give a score which isthe percent of questions he/she got correct. (and use no "Break")
package proj3;
import java.util.Random;
public class Question {
private int operand1;
private int operand2;
private char operator;
/**
* <p> Name: main method </p>
*
*/
public Question()
{
Random rand = new Random();
boolean random = rand.nextBoolean();
if(rand.nextBoolean())
{
operator = '+';
operand1 = rand.nextInt(13);
operand2 = rand.nextInt(13);
}
else
{
operator = '-';
operand1 = rand.nextInt(13 - 6) + 6;
operand2 = rand.nextInt((operand1 - 0) + 1) + 0;
}
}
/**
* getOperand1 method - returns what's stored in the instance variable value
* #return the state of the instance variable value
*/
public int getOperand1()
{
return operand1;
}
/**
* getOperand2 method - returns what's stored in the instance variable value
* #return the state of the instance variable value
*/
public int getOperand2()
{
return operand2;
}
/**
* getOperator method - returns what's stored in the instance variable value
* #return the state of the instance variable value
*/
public char getOperator()
{
return operator;
}
/**
* toString method - this method returns the state of the Question object
* #return a reference to a String object that contains
* the operands and the operator
*/
public String toString()
{
String question;
question = operand1 + " " + operator + " " + operand2 + " " + "=";
return question;
}
/**
* determineAnswer method - this method returns the state of the card object
* #return a reference to a Question object that contains the answer to
* a random question.
*/
public int determineAnswer()
{
if(operator == '+')
return operand1 + operand2;
else
return operand1 - operand2;
}
}
This is what Project4App currently looks like(stuck on)
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
int percentage = 0;
int questions = 0;
while( questions > 10 && questions < 20 && percentage >= 85.0)
{
Question q = new Question();
System.out.println("What is the result?");
System.out.println(q);
int answer = scan.nextInt();
if(answer == q.determineAnswer())
System.out.println("Congratulations, you got it correct!");
else
System.out.println("The correct answer for " + q + " is " + q.determineAnswer());
}
/**for(int i =0; i <= 20; i++)
{
Question q = new Question();
System.out.println("What is the result?");
System.out.println(q);
int answer = scan.nextInt();
if(answer == q.determineAnswer())
{
System.out.println("Congratulations, you got it correct!");
}
else
System.out.println("The correct answer for " + q + " is " + q.determineAnswer());
}
**/
}
}
Any advice will be appreciated on how to continue.
I did not test
boolean isOver = false;
while( !isOver ){
questions++;
Question q = new Question();
System.out.println("What is the result?");
System.out.println(q);
int answer = scan.nextInt();
if(answer == q.determineAnswer())
System.out.println("Congratulations, you got it correct!");
else
System.out.println("The correct answer for " + q + " is "+ q.determineAnswer());
if( (questions > 10 && percentage >= 85.0) || questions == 20){
isOver = true;
}
}
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
What's the simplest way to print a Java array?
(37 answers)
Closed 10 months ago.
I have a method called processClaims() which takes input from the user "by asking how many files need to be claimed". The method is shown below.
public void processClaims() {
int size = 0, j = 0, k = 0;
String suffix = " ", aClaim = " ";
System.out.println("How many claims will be filed?");
size = input.nextInt();
while (size <= 0) {
System.out.println("Invalid integer! Re-enter the number of claims to be filed: ");
size = input.nextInt();
}
EarthquakeInsurance[] claims = new EarthquakeInsurance[size];
for (int i = 0; i >= 0; i++) {
j = (i + 1) % 10;
k = (i + 1) % 100;
suffix = j == 1 && k != 11 ? "st" :
j == 2 && k != 12 ? "nd" :
j == 3 && k != 13 ? "rd" : "th";
claims[i] = new EarthquakeInsurance();
if (i > 0) {
System.out.println("Is this " + i + suffix + " claim for the same property owner? 'Y' or 'N': ");
cont = input.next().charAt(0);
if (cont == 'n' || cont == 'N') {
claims[i].setInsured();
}
else{
claims[i].setInsured(claims[i].getInsured());
}
}
else
{
claims[i].setInsured();
claims[i].setHomeInsVal();
claims[i].setRichter();
}
input.nextLine();
aClaim = String.format("%n%nPAYOUT FOR EARTHQUAKE DAMAGE"
+ "%n%nHomeowner: %S"
+ "%n%nDate: %tD"
+ "%nTime: %tr%n"
+ "%n%-52s %4s $%,20.2f"
+ "%nDeductible %47s %,20.2f"
+ "%n%46s TOTAL %4s $%,20.2f%n",
claims[i].getInsured(), dateTime, dateTime, claims[i].getMessage(), " ",
claims[i].getPayout(), " ",
claims[i].getDeductible(), " ",
" ", claims[i].getPayout() +
claims[i].getDeductible());
aClaim += claimsReport;
for ( EarthquakeInsurance eachClaim : claims);
System.out.println(claims);
}
}
The problem is with the array or the for loop I belive. The output is shown below which isn't correct
[LInsuranceSystem$EarthquakeInsurance;#548c4f57
If that is wrong here is the whole code, I am having trouble debugging this.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
public class Slack
{
public static void main(String[] args) throws FileNotFoundException {
InsuranceSystem insuranceSystem = new InsuranceSystem();
insuranceSystem.start();
}
}
class InsuranceSystem {
Scanner input = new Scanner(System.in);
Calendar dateTime = Calendar.getInstance();
ArrayList<String> claimsReport = new ArrayList<>();
EarthquakeInsurance[] claims;
String fileName = " ";
char cont = ' ', correct = ' ';
public InsuranceSystem() {
}
public void start() throws FileNotFoundException {
System.out.println("MUTUALLY ACCIDENTAL INC.");
System.out.println("Do you want an analysis of earthquake coverage for your property? Enter 'Y' or 'N': ");
cont = input.next().charAt(0); //reads user input from input and applies to it var cont
input.nextLine(); //clears buffer
if (cont == 'y' || cont == 'Y') {
processClaims();
writeClaimsRecords();
checkInputFile();
}
printThankYou();
}
public void processClaims() {
int size = 0, j = 0, k = 0;
String suffix = " ", aClaim = " ";
System.out.println("How many claims will be filed?");
size = input.nextInt();
while (size <= 0) {
System.out.println("Invalid integer! Re-enter the number of claims to be filed: ");
size = input.nextInt();
}
EarthquakeInsurance[] claims = new EarthquakeInsurance[size];
for (int i = 0; i >= 0; i++) {
j = (i + 1) % 10;
k = (i + 1) % 100;
suffix = j == 1 && k != 11 ? "st" :
j == 2 && k != 12 ? "nd" :
j == 3 && k != 13 ? "rd" : "th";
claims[i] = new EarthquakeInsurance();
if (i > 0) {
System.out.println("Is this " + i + suffix + " claim for the same property owner? 'Y' or 'N': ");
cont = input.next().charAt(0);
if (cont == 'n' || cont == 'N') {
claims[i].setInsured();
}
else{
claims[i].setInsured(claims[i].getInsured());
}
}
else
{
claims[i].setInsured();
claims[i].setHomeInsVal();
claims[i].setRichter();
}
input.nextLine();
aClaim = String.format("%n%nPAYOUT FOR EARTHQUAKE DAMAGE"
+ "%n%nHomeowner: %S"
+ "%n%nDate: %tD"
+ "%nTime: %tr%n"
+ "%n%-52s %4s $%,20.2f"
+ "%nDeductible %47s %,20.2f"
+ "%n%46s TOTAL %4s $%,20.2f%n",
claims[i].getInsured(), dateTime, dateTime, claims[i].getMessage(), " ",
claims[i].getPayout(), " ",
claims[i].getDeductible(), " ",
" ", claims[i].getPayout() +
claims[i].getDeductible());
aClaim += claimsReport;
for ( EarthquakeInsurance eachClaim : claims);
System.out.println(claims);
}
}
public void writeClaimsRecords() throws FileNotFoundException
{
String record = " ";
Scanner input = new Scanner(System.in);
System.out.println("Enter the file name for the claims' records (WARNING: This will erase a pre-existing file!): ");
fileName = input.nextLine();
PrintWriter outputFile = new PrintWriter(fileName);
for(int i = 0; i < claims.length; i++){
record = String.format("%s, %f, %f%n", claims[i].insured, claims[i].homeInsVal, claims[i].richter);
}
outputFile.printf(record);
outputFile.close();
System.out.println("Data written to the" + fileName + " file.");
}
public void checkInputFile() throws FileNotFoundException {
String fileRecord = " ";
File file = new File("Claims.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()) {
fileRecord = inputFile.nextLine();
System.out.println(fileRecord);
System.out.println("");
inputFile.close();
}
}
public void printThankYou() {
System.out.println("Thank you for using the Earthquake Coverage Analyzer.");
}
class EarthquakeInsurance {
//STUDENTS INSERT LINE COMMENTS DESCRIPTIVE OF THE PURPOSE OF EACH VARIABLE.
private String insured;
private String coverage;
private String message;
private double homeInsVal;
private double richter;
private double payout;
private double deductible;
private Scanner input = new Scanner(System.in);
private boolean repeat;
private char correct;
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public EarthquakeInsurance() {
}//END Default Constructor
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public EarthquakeInsurance(String insured, double homeInsVal, double richter) {
setInsured(insured);
setHomeInsVal(homeInsVal);
setRichter(richter);
}//END EarthquakeInsurance(String, double, double)
/**
* STUDENTS CODE copy() AND PROVIDE METHOD BOX COMMENTS.
*/
public String copy() {
String insuranceObj = " ";
return insuranceObj;
}
/**
* STUDENTS CODE equals AND PROVIDE METHOD BOX COMMENTS.
*/
public boolean equals(String aClaim) {
boolean isEqual = false;
if (isEqual = false) {
isEqual = true;
}
return isEqual;
}
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setInsured(String insured) {
this.insured = insured;
}//END setInsured(String): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setHomeInsVal(double homeInsVal) {
this.homeInsVal = homeInsVal;
}//END setHomeInsVal(double): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setRichter(double richter) {
this.richter = richter;
}//END setRichter(double): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setInsured() {
String insuredCopy = null, first = null, last = null;
int indexOfSpace = 0;
do {
System.out.printf("%nMUTUALLY ACCIDENTAL, INC."
+ "%nEarthquake Coverage Analyzer"
+ "%n%nPlease enter your name: ");
insured = input.nextLine();
insuredCopy = new String(insured).replace(" ", "");
while (!isAlpha(insuredCopy)) {
System.out.printf("%nInvalid name! Please re-enter: ");
insured = input.nextLine();
insuredCopy = new String(insured).replace(" ", "");
}//while insured's name is NOT alphabetic
System.out.printf("%nYour Name: %s"
+ "%n%nIs this name correct? \'Y\' or \'N\': ",
insured);
correct = input.nextLine().toLowerCase().charAt(0);
repeat = correct == 'y' ? false : true;
} while (repeat); //do-while insured name is not correct
indexOfSpace = insured.indexOf(" "); //Locate where the space is in insured.
if (indexOfSpace > 0) {
first = Character.toUpperCase(insured.charAt(0))
+ insured.substring(1, indexOfSpace).toLowerCase();
last = Character.toUpperCase(insured.charAt(indexOfSpace + 1))
+ insured.substring(indexOfSpace + 2, insured.length()).toLowerCase();
insured = first + " " + last;
}//if there is more than one name, capitalize the first letter in each
else {
insured = Character.toUpperCase(insured.charAt(0))
+ insured.substring(1, insured.length()).toLowerCase();
}//else capitalize first letter of a single name
}//END setInsured(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setHomeInsVal() {
do {
do {
System.out.printf("%nPlease enter the insured value of your home: ");
repeat = !input.hasNextDouble();
validateNumber();
} while (repeat); //END do-while repeats when homeInsVal is invalid
homeInsVal = input.nextDouble();
if (homeInsVal < 0) {
System.out.printf("%nThe insured value of your home cannot be less than or equal to 0.%n");
repeat = true;
}//END if homeInsVal less than zero then prompt again
else {
System.out.printf("%nHome\'s Insured Value: $%,.0f"
+ "%n%nIs this insured value correct? \'Y\' or \'N\': ",
homeInsVal);
correct = input.next().toLowerCase().charAt(0);
repeat = correct == 'y' ? false : true;
}//END else validate the correctness of insured value
} while (repeat); //END do-while repeats when homeInsVal is not correct
}//END setHomeInsVal(): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setRichter() {
do {
do {
System.out.printf("%nRichter Scale Damage Assessment"
+ "%n 9.0+ Total destruction."
+ "%n 8.0 Most structures fell."
+ "%n 7.0 Many buildings destroyed."
+ "%n 6.0 Many buildings considerably damaged, some collapsed."
+ "%n 4.5 Damage to poorly constructed buildings."
+ "%n 3.5 Felt by many people, no destruction."
+ "%n 0 Generally not felt by people."
+ "%n%nPlease enter the Richter scale value for the earthquake: ");
repeat = !input.hasNextDouble();
validateNumber();
} while (repeat); //END do-while repeats when richter is invalid
richter = input.nextDouble();
if (richter < 0) {
System.out.printf("%nInvalid! Richter cannot be negative. Please re-enter.%n");
repeat = true;
}//END if richter less than zero then prompt again
else {
System.out.printf("%nRichter Scale: %.2f"
+ "%n%nIs this richter value correct? \'Y\' or \'N\': ",
richter);
correct = input.next().toLowerCase().charAt(0);
input.nextLine();
repeat = correct == 'y' ? false : true;
}//END else validate the correctness of richter
} while (repeat); //END do-while repeats when homeInsVal is not correct
testRichter();
}//END setRichter(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
private void testRichter() {
if (richter >= 9.0) {
payout = homeInsVal * .90;
deductible = homeInsVal * .10;
message = "Total destruction.";
}//END if richter >= 9.0 else richter < 9.0
else if (richter >= 8.0) {
payout = homeInsVal * .80;
deductible = homeInsVal * .20;
message = "Most structures fell.";
}//END if richter >= 8.0 else richter < 8.0
else if (richter >= 7.0) {
payout = homeInsVal * .70;
deductible = homeInsVal * .30;
message = "Many buildings destroyed.";
}//END if richter >= 7.0 else richter < 7.0
else if (richter >= 6.0) {
payout = homeInsVal * .60;
deductible = homeInsVal * .40;
message = "Many buildings considerably damaged, some collapsed.";
}//END if richter >= 6.0 else richter < 6.0
else if (richter >= 4.5) {
payout = homeInsVal * .50;
deductible = homeInsVal * .50;
message = "Damage to poorly constructed buildings.";
}//END if richter >= 4.5 else richter < 4.5
else if (richter >= 3.5) {
payout = 0;
deductible = 0;
message = "Felt by many people, no destruction.";
}//END if richter >= 3.5 else richter < 3.5
else if (richter >= 0) {
payout = 0;
deductible = 0;
message = "Generally not felt by people.";
}//END if richter >= 0 else richter < 0
}//END testRichter(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public String getInsured() {
return insured;
}//END getInsured(): int
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getHomeInsVal() {
return homeInsVal;
}//END getHomeInsVal(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getRichter() {
return richter;
}//END getRichter(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getPayout() {
return payout;
}//END getPayout(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getDeductible() {
return deductible;
}//END getDeductible(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public String getMessage() {
return message;
}//END getMessage(): String
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void validateNumber() {
if (repeat) //AS LONG AS THE INPUT IS "NOT" AN INTEGER OR DOUBLE
{
input.next(); //CONSUME NON-NUMERIC VALUE.
System.out.printf("%nWarning: You entered an invalid integer or "
+ "floating-point value.%n"); //RE-PROMPT
}//END if repeat when a number is an invalid type
}//END validateNumber(boolean): void
/**
* chars() returns the integer values of the characters in word.
* <p>
* allMatch determines whether the integer values for each character
* matches the predicate (criterion) that each character is a letter.
* <p>
* The :: is a method reference operator for calling isLetter from
* the Character class.
*
* #param word is the incoming String value to test.
* #return is true when the word is not empty and is alphabetic
* or false when it isn't.
*/
public final boolean isAlpha(String word) {
/* Test to see if the word is not empty AND if each letter
* in a word is an alphabetic character.
*/
return word != null && word.chars().allMatch(Character::isLetter);
}//END isAlpha(String): final boolean
}//END CLASS EarthquakeInsurance
}
Mistake 1)
for ( EarthquakeInsurance eachClaim : claims);
remove semi
Mistake 2)
System.out.println(claims);
Yes you are print the whole list
See also How do I print my Java object without getting "SomeType#2f92e0f4"?
This code is supposed to get check whether a number is a palindrome.
Whenever I run the method check Palindrome its comes up with a java.lang.StringOutOfBoundsException.
Please help.
import java.util.*;
/**
* Lab 1 .
* #author Kevin Rasquinha
* #version 30 July 2016
*/
public class Lab1
{
private Scanner scan = new Scanner(System.in);
/**
* count the number of digits in a number
* #param num the number to analyse
* #return the number of digits it has
*/
public int numDigits (int num)
{
int nDigits = 0;
int digit;
while (num>0)
{
digit = num % 10; // take off the last digit
num = num /10; // reduce the number
nDigits = nDigits + 1; // increment count of digits
}
return nDigits;
}
/**
* Read a number from the keyboard, and report how many digits it has.
* Ensure the number is within a desired range.
*/
public void countDigits ()
{
int num=0;
while (num<1 || num > 1000)
{
System.out.print("What number (1 to 1000)? ");
num = scan.nextInt();
scan.nextLine();
System.out.println("Num = " + num);
if (num<1 || num > 1000)
System.out.println("1 to 1000, please");
}
System.out.println (num + " has " + numDigits(num) + " digits");
}
/**
* method used to if a number is the sum of the cube of its digits
* #param args (not used)
*/
public void sumCubesDigits ()
{
for (int initial = 1; initial < 1000; initial ++)
{
int num = initial;
int thirddig = num%10;
num = num / 10;
int secdig = num%10;
num = num / 10;
int firstdig = num%10;
int sum = (thirddig*thirddig*thirddig) + (secdig*secdig*secdig) + (firstdig*firstdig*firstdig);
if (sum == initial)
{
System.out.println ("The number " + initial + " is equal to the sum of the cube of its digits.");
}
}
}
/**
* Recieves an int and writes the same int backwards
* #param args (not used)
*/
public int backwards(int num)
{
int rev = 0;
int value = num;
while (value != 0)
{
rev = rev*10;
rev = rev + value%10;
value /= 10;
}
return rev;
}
/**
* Receives digit from method backwards
* Asses whether backwards = the original number
* #param args (not used)
*/
public boolean palindrome (int num, int digit)
{
boolean a = false;
int normal = num;
int reversed = digit;
if( reversed == digit)
{
a = true;
}
return a;
}
/**
* Recieves int from user - num
* Sends num to backwards
* Sends num to palindrome
* Recieves boolean from palindrome
* Outputs message to user
*/
public void checkPalindrome ()
{
System.out.println ("Enter number to be see if it is a palindrome");
int num = scan.nextInt();
int digit = backwards(num);
boolean check = palindrome (num, digit);
if (check = true)
{
System.out.println("Your number is a palindrome");
}
}
/**
* Present a menu to the user, and obtain their selection. If they
* type an erroneous value, report it and try again. Either upper
* case or lower case input is accepted.
* #return an upper case character showing the user's choice
*/
public char menuChoice ()
{
System.out.println("");
System.out.println("What do you want to do?");
System.out.println("(c) Count the digits in a number");
System.out.println("(g) Find out the numbers where the the sum of the cube of its digits is equal to it");
System.out.println("(p) Find out if a number is a palindrome");
System.out.println("(q) Quit");
System.out.print("Your choice? ");
char answer = ' ';
boolean ok = false;
while (! ok)
{
answer = scan.nextLine().trim().toUpperCase().charAt(0);
ok = (answer == 'C' || answer == 'Q' || answer == 'G' || answer == 'P');
if (! ok)
{
System.out.println("Please type one of c,C,q,Q,g,G,p,P");
System.out.print("Your choice? ");
}
}
return answer;
}
/**
* test driver for the program
*/
public void test()
{
char answer = ' ';
while (answer != 'Q')
{
answer = menuChoice();
switch (answer)
{
case 'C': countDigits(); break;
case 'G': sumCubesDigits(); break;
case 'P': checkPalindrome();break;
case 'Q': break;
}
}
}
/**
* main program: create a test driver and let it loose
* #param args (not used)
*/
public static void main (String [] args)
{
Lab1 l1 = new Lab1();
l1.test();
}
}
A StringIndexOutOfBoundsException is mostly thrown when you use charAt to select a character from a string that isn't there.
I guess your issue is here:
answer = scan.nextLine().trim().toUpperCase().charAt(0);
because that is the only charAt in your code.
What would that line do if the user entered nothing? Throw an Exception of course!
You should change if (check = true) to if (check == true) and answer = scan.nextLine().trim().toUpperCase().charAt(0); to answer = scan.nextLine();
if(answer != null)
answer = answer.trim().toUpperCase().charAt(0);
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;
}
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;
...
}
What I am supposed to do is this:Write a program that gives the user 10 random math problems, asks for the answer each time, and then tells the user if they were right or wrong. Each problem should use 2 random numbers between 1 and 20, and a random operation (+, -, *, or /). You will need to re-randomize the numbers for each math problem. You should also keep track of how many problems they get right. At the end, tell the user how many problems they got right and give them a message based on their result. For example, you may say “good job” or “you need more practice.”
So far I am at a loss
import java.util.Scanner;
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
if (operator == 1)
System.out.println("+");
if (operator == 2)
System.out.println("-");
if (operator == 3)
System.out.println("*");
if (operator == 4)
System.out.println("/");
}
}
I mostly need to know how to turn these random numbers and operators into a problem, and how to grade each question to see if they are wrong.
Well, what you need to add is:
to count answers:
a variable that counts correct answers (increment it every time the user answers correctly);
a variable to store current correct answer;
a variable to store current user answer (refresh it every next problem, no need to store it forever, cause in your case only statistics is needed);
a function (let it be called e.g. gradeTheStudent() ) which uses several conditions to decide what to print out according to number of correct answers;
to create a problem:
put problem generation and answer evaluation into a cycle, which repeats 10 times;
in your switch (i.e. when you choose operators) also calculate the correct answer:
switch(operator){
case 1: {
operation = "+";
correctResult = number1 + number2;
break;
}
case 2: ....
case 3: ....
case 4: ....
default: break;
}
don't forget to check if the user entered a number or something else (you could use either an Exception or a simple condition).
So, a "pseudocode"solution for your problem would look something like this:
String[] reactions = ["Awesome!","Not bad!","Try again and you will get better!"]
num1 = 0
num2 = 0
operator = NIL
userScore = 0
userAnswer = 0
correctAnswer = 0
def function main:
counter = 0
for counter in range 0 to 10:
generateRandomNumbers()
correctAnswer = generateOperatorAndCorrectAnswer()
printQuestion()
compareResult()
gradeStudent()
def function generateRandomNumbers:
# note that you have already done it!
def function generateOperatorAndCorrectAnswer:
# here goes our switch!
return(correctAnswer);
def function printQuestion:
print "Next problem:" + "\n"
print num1 + " " + operator + " " + num2 + " = " + "\n"
def function compareResult(correctAnswer):
# get user result - in your case with scanner
if(result == correctAnswer)
print "Great job! Correct answer! \n"
userScore++
else print "Sorry, answer is wrong =( \n"
def function gradeStudent (numOfCorrectAnswers):
if(numOfCorrectAnswers >= 7) print reactions[0]
else if(numOfCorrectAnswers < 7 and numOfCorrectAnswers >= 4) print reactions[1]
else print reactions[2]
General advice: don't try to solve the problem all at once. A good approach is to create small functions, each doing its unique task. The same with problem decomposition : you just should write down what you think you need in order to model the situation and then do it step by step.
Note: as far as I can see from your current function, you are not familiar with object oriented programming in Java. This is why I am not providing any tips about how great it would be to use classes. However, if you are, then please let me know, I will add info to my post.
Good luck!
For example you can use something like that:
public class Problem {
private static final int DEFAULT_MIN_VALUE = 2;
private static final int DEFAULT_MAX_VALUE = 20;
private int number1;
private int number2;
private Operation operation;
private Problem(){
}
public static Problem generateRandomProblem(){
return generateRandomProblem(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE);
}
public static Problem generateRandomProblem(int minValue, int maxValue){
Problem prob = new Problem();
Random randomGen = new Random();
int number1 = randomGen.nextInt(maxValue + minValue) + minValue;
int number2 = randomGen.nextInt(maxValue + minValue) + minValue;
prob.setNumber1(number1);
prob.setNumber2(number2);
int operationCode = randomGen.nextInt(4);
Operation operation = Operation.getOperationByCode(operationCode);
prob.setOperation(operation);
return prob;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public Operation getOperation() {
return operation;
}
public void setNumber1(int number1) {
this.number1 = number1;
}
public void setNumber2(int number2) {
this.number2 = number2;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
}
And another class for holding operations:
public enum Operation {
PLUS,
MINUS,
MULTIPLY,
DIVIDE;
public double operationResult(int n1, int n2) {
switch (this) {
case PLUS: {
return (n1 + n2);
}
case MINUS: {
return n1 - n2;
}
case MULTIPLY: {
return n1 * n2;
}
case DIVIDE: {
return n1 / n2;
}
}
throw new IllegalArgumentException("Behavior for operation is not specified.");
}
public static Operation getOperationByCode(int code) {
switch (code) {
case 1:
return PLUS;
case 2:
return MINUS;
case 3:
return MULTIPLY;
case 4:
return DIVIDE;
}
throw new IllegalArgumentException("Operation with this code not found.");
}
}
But you not must throw IllegalArgumentException, there are another options for handling unexpected arguments.
Printout the numbers and the operation , read the user input using file IO , and perform your logic of keeping a track of answered questions
Code :
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
if (operator == 1)
operation="+";
if (operator == 2)
operation="-";
if (operator == 3)
operation="*";
if (operator == 4)
operation="/";
System.out.println("Question "+number1+operation+number2);
}
}
Keep a track of result and compare with the user input and verify its right or wrong
public static void main(String[] args) throws IOException{
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
int result=0;
if (operator == 1){
operation="+";
result=number1+number2;
}
if (operator == 2) {
operation="-";
result=number1-number2;
}
if (operator == 3){
operation="*";
result=number1*number2;
}
if (operator == 4){
operation="/";
result=number1/number2;
}
System.out.println("Question "+number1+operation+number2);
String result1 = new BufferedReader(new InputStreamReader(System.in)).readLine();
if(result==Integer.parseInt(result1))
System.out.println("Right");
else
System.out.println("Wrong");
}
Since I do not want to hand you a full solution to this problem, and you seem to have some knowledge in the Java language I will just write down how I would continue/change what you have as a start.
First I would store the result in your operator if statements. Result is an int.
if (operator == 1) {
operation="+";
result=number1+number2;
}
After this I would print the math question and wait for the user to answer.
System.out.println("What is the answer to question: " +number1+operation+number2);
userResult = in.nextLine(); // Read one line from the console.
in.close(); // Not really necessary, but a good habit.
At this stage all you have to do is compare the result with the user input and print a message.
if(Integer.parseInt(userResult) == result) {
System.out.println("You are correct!");
} else {
System.out.println("This was unfortunately not correct.");
}
This solution is more or less psudo code and some error handling (if user enters test in the answer for example) is missing, also I would split it up into methods rather than have it all in main(). Next step would be to make it object oriented (Have a look at the answer from demi). Good luck in finalizing your program.
In regard to generating random math operations with +, -, * & / with random numbers your can try the following;
import java.util.*;
public class RandomOperations{
public static void main(String[] args){
Random `mathPro` = new Random();
//for the numbers in the game
int a = mathPro.nextInt(50)+1;
int b = mathPro.nextInt(50)+1;
//for the all the math operation result
int add = a+b;
int sub = a-b;
int mult = a*b;
int div = a/b;
//for the operators in the game
int x = mathPro.nextInt(4);
/*
-so every random number between 1 and 4 will represent a math operator
1 = +
2 = -
3 = x
4 = /
*/
if(x == 1){
System.out.println("addition");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(add);
}else if(x == 2){
System.out.println("subtraction");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(sub);
}else if(x == 3){
System.out.println("multiplication");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(mult);
}else{
System.out.println("division");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(div);
}
//This os for the user to get his input then convert it to a numbers that the program can
//understand
Scanner userAnswer = new Scanner(System.in);
System.out.println("Give it a try");
int n = `userAnswer.nextInt();