This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 9 years ago.
I'm doing a program that presents the student with a math quiz. I am having trouble figuring out how to take the input problem type and turning that string into the arithmetic operator. Here is the method for that part of the code. Please and thanks!
public static String getUserChoice(String choice) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the symbol that corresponds to one of the following problems\n"
+ "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
choice = in.next();
if ("+".equals(choice)){
return +;
}
}
return choice;
Update
Here's the entire code if it helps see what I am doing.
public static void main(String[] args) {
int digit = 0;
int random = 0;
String result1 = getUserChoice("");
digit = getNumberofDigit1(digit);
int number1 = getRandomNumber1(digit);
int number2 = getRandomNumber2(digit);
System.out.println(number1 + result1 + number2);
getCorrectAnswer(number1, result1, number2);
}
public static String getUserChoice(String choice) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the symbol that corresponds to one of the following problems\n"
+ "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
choice = in.next();
return choice;
}
public static int getNumberofDigit1(int digit) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a 1 for problems with one digit, or a 2 for two-digit problems: ");
digit = in.nextInt();
return digit;
}
public static int getRandomNumber1(int numbers) {
int random = 0;
if (numbers == 1) {
random = (int) (1 + Math.random() * 9);
} else if (numbers == 2) {
random = (int) (10 + Math.random() * 90);
}
return random;
}
public static int getRandomNumber2(int numbers) {
int random2 = 0;
if (numbers == 1) {
random2 = (int) (1 + Math.random() * 9);
} else if (numbers == 2) {
random2 = (int) (10 + Math.random() * 90);
}
return random2;
}
public static void getCorrectAnswer(int number1, String result1, int number2) {
}
public static void getUserAnswer() {
Scanner in = new Scanner(System.in);
}
public static void CheckandDisplayResult() {
}
here is the one approach to your problem:
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
final String result1 = getUserChoice();
final int digit = getNumberofDigit1();
final int number1 = getRandomNumber(digit);
final int number2 = getRandomNumber(digit);
System.out.println(number1 + result1 + number2);
final int userAnswer = input.nextInt();
final int correctAnswer = getCorrectAnswer(number1, result1, number2);
System.out.println( (userAnswer == correctAnswer) ? "Ok" : ("Wrong, right is: " + correctAnswer));
input.close();
}
public static String getUserChoice() {
System.out.println("Please enter the symbol that corresponds to one of the following problems\n" + "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
return input.next();
}
public static int getNumberofDigit1() {
System.out.println("Enter a 1 for problems with one digit, or a 2 for two-digit problems: ");
return input.nextInt();
}
public static int getRandomNumber(final int numbers) {
return (int) ( (numbers == 1) ? (1 + Math.random() * 9) : (10 + Math.random() * 90) );
}
public static int getCorrectAnswer(final int number1, final String result1, final int number2) {
if ("+".equals(result1))
return number1+number2;
else if ("-".equals(result1))
return number1-number2;
else if ("*".equals(result1))
return number1*number2;
return -1;
}
and here is a little bit another getCorrectAnswer part:
public interface IMyOperator {
public int operation(final int a, final int b);
};
static class classSum implements IMyOperator {
public int operation(final int a, final int b) {
return a+b;
}
}
static class classSub implements IMyOperator {
public int operation(final int a, final int b) {
return a-b;
}
}
static class classMul implements IMyOperator {
public int operation(final int a, final int b) {
return a*b;
}
}
final static HashMap<String, IMyOperator> operators = new HashMap<String, IMyOperator>(3) {{
put("+", new classSum());
put("-", new classSub());
put("*", new classMul());
}};
public static int getCorrectAnswer(final int number1, final String result1, final int number2) {
return operators.get(result1).operation(number1, number2);
}
First, I want to show you how to test to see if it is what you want.
You can always check to make sure it is a string, or int, or w/e by doing the following.
Scanner scan = new Scanner(System.in);
while(scan.hasNext()) {
if(scan.hasNextInt()) {
int response = scan.nextInt();
}
}
Here is code for what you want to do.
import java.util.Random;
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
// Math Quiz v1.0 //
String printme = "Please choose the quiz type:\n\n"
+ "(1) Addition\n"
+ "(2) Subtraction\n"
+ "(3) Multiplication\n"
+ "(4) Division\n"
+ "(5) Modulus\n\n\n";
System.out.println(printme);
int reponse = in.nextInt();
// Setup //
int a = new Random().nextInt(100);
int b = new Random().nextInt(100);
int answer = -1;
switch(reponse) {
case 1:
System.out.println("What is " + a + " + " + b + "?");
answer = in.nextInt();
if(answer == a + b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 2:
System.out.println("What is " + a + " - " + b + "?");
answer = in.nextInt();
if(answer == a - b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 3:
System.out.println("What is " + a + " * " + b + "?");
answer = in.nextInt();
if(answer == a * b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 4:
System.out.println("What is " + a + " / " + b + "?");
answer = in.nextInt();
if(answer == a / b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 5:
System.out.println("What is " + a + " % " + b + "?");
answer = in.nextInt();
if(answer == a % b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
default:
System.out.println("Error, enter an integer between 1 & 5.");
break;
}
}
}
Related
I have two classes: MyNumbers and MyScanner. I am trying to pass the validated inputs to the calculateSum (int x, int y) method in order to print the final result in the MyScanner class, but I don't know how I can take the user inputs from the MyScanner class to pass them to the validate() method in the MyNumbers class so that it allows the calculateSum() method to perform its task.
P.S. validate() method should be void and parameterless, but calculateSum() method should be string to return the result as a string and take two parameters. I also want the validate() method to prompt for user input and validate the values to make sure that they are in the certain range. This method needs to keep prompting until user inserts a valid number.
How can I achieve this without introducing another variable/implementing setters/ passing variables as a parameter to the validate() method?
public class MyNumbers {
int number1;
int number2;
public void validate() {
if (number1 >= 10 && number1 <= 50) {
if(number2 >= 5 && number2 <= 20){
System.out.println(calculateSum(number1, number2));
}
}
else {
System.out.println("Number should be between 10 and 50");
}
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
validate();
return "Sum: " + number1 + number2;
}
}
public class MyScanner {
public static void main(String[] args) {
MyNumbers myNumbers = new myNumbers();
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
do{
switch(option){
case 1:
System.out.println("Enter number 1");
int x = scanner.nextInt();
System.out.println("Enter number 2");
int y = scanner.nextInt();
myNumbers.calculateSum(x, y);
break;
}
}
while(option!=0);
}
}
EDIT :
import java.util.*;
class MyNumbers {
int number1;
int number2;
public void validate() {
int valid=0;
int x;
int y;
Scanner s = new Scanner(System.in);
System.out.println("Welcome!");
do{
System.out.println("Enter Number 1: ");
x = s.nextInt();
if (x >= 10 && x <= 50) {
valid=2;
}
else {
System.out.println("Number 1 should be between 10 and 50");
}
}while(valid!=2);
do {
System.out.println("Enter Number 2: ");
y = s.nextInt();
if(y >= 5 && y <= 20){
System.out.println(calculateSum(x, y));
valid=3;
}
else {
System.out.println("Number 2 should be between 5 and 20");
}
}while(valid!=3);
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
return "Sum: " + (number1 + number2);
}
}
public class Main {
public static void main(String[] args) {
MyNumbers myNumbers = new MyNumbers();
myNumbers.validate();
}
}
Try
import java.util.*;
class MyNumbers {
int number1;
int number2;
public void validate(int number1 , int number2) {
if (number1 >= 10 && number1 <= 50) {
if(number2 >= 5 && number2 <= 20){
System.out.println(calculateSum(number1, number2));
}
}
else {
System.out.println("Number should be between 10 and 50");
}
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
return "Sum: " + number1 + number2;
}
}
public class Main {
public static void main(String[] args) {
MyNumbers myNumbers = new MyNumbers();
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
switch(option){
case 1:
System.out.println("Enter number 1");
int x = scanner.nextInt();
System.out.println("Enter number 2");
int y = scanner.nextInt();
myNumbers.validate(x, y);
myNumbers.calculateSum(x, y);
break;
}
}
}
I'm working on this project challenge called "Algebra Tutor" for my very first java class.
The program should be able to output a question to decide whether you want to solver for m or b or y in the formula y = mx + b.
Once one of those is pick by a number: "Select 1 to Solve for Y, 2 to Solve for M, 3 to Solve for B and 4 to quit. "
It should give you an output to solve the formula.
I'm working in part 3 of the project which is:
Update your program so that each problem type mode will repeatedly ask questions until the user gets 3 correct answers in a row.
If the attempts more than 3 questions in a particular mode, the program should provide a hint on how to solve problems of this type.
After the student has correctly answered 3 questions in a row, an overall score (the number of questions answered correctly divided by the total number of questions attempted) should be displayed, and the menu is presented again.
So I'm getting stuck on how I can place a counter that starts at 0 and every time the user answers correctly then 1 will be added to the counter and quit if it gets 3 in a row or go back to 0 if the user answer is incorrect.
I will provide my code I'm getting confused on how having a while loop inside of the if statement and then another while loop for the count, it's confusing I know but once you see my code you will see what I'm talking about.
So I know I can place a counter like this:
int counter = 0;
while (counter < 4)
if statement here
counter ++;
else
counter = 0;
import java.util.Scanner;
class AlgebraTutor {
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generate_random(max_value, min_value);
double x_value = generate_random(max_value, min_value);
double b_value = generate_random(max_value, min_value);
double y_value = generate_random(max_value, min_value);
Scanner user_input = new Scanner(System.in);
int user_answer_int = 0;
while ((user_answer_int < 4) && (user_answer_int >= 0)) {
System.out.println("Select 1 to Solve for Y, 2 to Solve for M, 3 to Solve for B and 4 to quit. ");
user_answer_int = user_input.nextInt();
if (user_answer_int == 1) {
check_answer_for_y(m_value, x_value, b_value);
}
else if (user_answer_int == 2) {
check_answer_for_m(x_value, y_value, b_value);
}
else if (user_answer_int == 3) {
check_answer_for_b(m_value, x_value, y_value);
}
else {
System.out.println("You are done");
}
}
}
static void check_answer_for_m(double x_value, double y_value, double b_value) {
System.out.println("Solve For M Problem ");
System.out.println("Given: ");
System.out.println("b = " + b_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of m? ");
Scanner user_input = new Scanner(System.in);
String user_answer_m = "";
user_answer_m = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_m);
int correct_answer_m = (((int)y_value - (int)b_value) / (int)x_value);
if (user_answer_int == correct_answer_m){
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_m);
}
}
static void check_answer_for_b(double m_value, double x_value, double y_value) {
System.out.println("Solve For B Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of b? ");
Scanner user_input = new Scanner(System.in);
String user_answer_b = "";
user_answer_b = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_b);
int correct_answer_b = ((int)y_value - ((int)m_value * (int)x_value));
if (user_answer_int == correct_answer_b){
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_b);
}
}
static void check_answer_for_y(double m_value, double x_value, double b_value) {
System.out.println("Solve For Y Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer_y = "";
user_answer_y = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_y);
int correct_answer_y = (int) m_value * (int) x_value + (int) b_value;
if (user_answer_int == correct_answer_y) {
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_y);
}
}
static int generate_random(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)+ 1)) + min_value);
}
}
Where I stated my while loop for the number entered by user
depending on the number then the if statement jumps in
where can I place my counter to start and catch all the if statements depending on the number the user picks and then if the user gets 3 correct in a row the program should go back to the main question. Can I do another while loop inside the one I already have? Or should I place it inside each if statement?
Place the loop here for each
else if (user_answer_int == 3) {
check_answer_for_b(m_value, x_value, y_value);
}
changing your main function to this.
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generate_random(max_value, min_value);
double x_value = generate_random(max_value, min_value);
double b_value = generate_random(max_value, min_value);
double y_value = generate_random(max_value, min_value);
Scanner user_input = new Scanner(System.in);
int user_answer_int = 0;
while ((user_answer_int < 4) && (user_answer_int >= 0)) {
System.out.println("Select 1 to Solve for Y, 2 to Solve for M, 3 to Solve for B and 4 to quit. ");
user_answer_int = user_input.nextInt();
int i = 0;
if (user_answer_int == 1) {
while (i < 3){
if (check_answer_for_y(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
i++;
}
else {
i = 0;
}
}
}
else if (user_answer_int == 2) {
while (i < 3){
if (check_answer_for_m(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
i++;
}
else {
i = 0;
}
}
}
else if (user_answer_int == 3) {
while (i < 3){
if (check_answer_for_b(generate_random(max_value, min_value), generate_random(max_value, min_value), generate_random(max_value, min_value))) {
i++;
}
else {
i = 0;
}
}
}
else {
System.out.println("You are done");
}
}
}
static boolean check_answer_for_m(double x_value, double y_value, double b_value) {
System.out.println("Solve For M Problem ");
System.out.println("Given: ");
System.out.println("b = " + b_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of m? ");
Scanner user_input = new Scanner(System.in);
String user_answer_m = "";
user_answer_m = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_m);
int correct_answer_m = (((int)y_value - (int)b_value) / (int)x_value);
if (user_answer_int == correct_answer_m){
System.out.println("You are correct!");
return true;
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_m);
return false;
}
}
static boolean check_answer_for_b(double m_value, double x_value, double y_value) {
System.out.println("Solve For B Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("y = " + y_value);
System.out.print("What is the value of b? ");
Scanner user_input = new Scanner(System.in);
String user_answer_b = "";
user_answer_b = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_b);
int correct_answer_b = ((int)y_value - ((int)m_value * (int)x_value));
if (user_answer_int == correct_answer_b){
System.out.println("You are correct!");
return true;
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_b);
return false;
}
}
static boolean check_answer_for_y(double m_value, double x_value, double b_value) {
System.out.println("Solve For Y Problem ");
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer_y = "";
user_answer_y = user_input.next();
int user_answer_int = Integer.parseInt(user_answer_y);
int correct_answer_y = (int) m_value * (int) x_value + (int) b_value;
if (user_answer_int == correct_answer_y) {
System.out.println("You are correct!");
return true;
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer_y);
return false;
}
}
static int generate_random(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)+ 1)) + min_value);
}
Having a problem getting the program to keep running after an error message has occurred. I have tried using different If/Else or While loops to get it to work but none seem to be giving any luck. The current code posted works until you enter something other than y, Y, n, or N. The error message will keep popping up after even if i enter y, Y, n, or N.
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class FutureValueApp {
public static void main(String[] args) {
// Avery Owen
System.out.println("Welcome to the Future Value Calculator\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("DATA ENTRY");
double monthlyInvestment = getDoubleWithinRange(sc,
"Enter monthly investment: ", 0, 1000);
double interestRate = getDoubleWithinRange(sc,
"Enter yearly interest rate: ", 0, 30);
int years = getIntWithinRange(sc,
"Enter number of years: ", 0, 100);
System.out.println();
// calculate the future value
double monthlyInterestRate = interestRate / 12 / 100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlyInvestment, monthlyInterestRate, months);
// print the results
System.out.println("FORMATTED RESULTS");
printFormattedResults(monthlyInvestment, interestRate,
years, futureValue);
// see if the user wants to continue
choice = askToContinue(sc);
}
}
public static double getDoubleWithinRange(Scanner sc, String prompt,
double min, double max) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
d = getDouble(sc, prompt);
if (d <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (d >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return d;
}
public static double getDouble(Scanner sc, String prompt) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextDouble()) {
d = sc.nextDouble();
isValid = true;
} else {
System.out.println("Error! Invalid number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt,
int min, int max) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
i = getInt(sc, prompt);
if (i <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (i >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return i;
}
public static int getInt(Scanner sc, String prompt) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
try {
i = sc.nextInt();
isValid = true;
} catch (InputMismatchException e) {
System.out.println("Error! Enter a whole number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static double calculateFutureValue(double monthlyInvestment,
double monthlyInterestRate, int months) {
double futureValue = 0;
for (int i = 1; i <= months; i++) {
futureValue = (futureValue + monthlyInvestment) *
(1 + monthlyInterestRate);
}
return futureValue;
}
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice = sc.next();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
sc.nextLine(); // discard any other data entered on the line
System.out.println("Error! Enter y or n. Try again.");
}
return choice;
}
private static void printFormattedResults(double monthlyInvestment,
double interestRate, int years, double futureValue) {
// get the currency and percent formatters
NumberFormat c = NumberFormat.getCurrencyInstance();
NumberFormat p = NumberFormat.getPercentInstance();
p.setMinimumFractionDigits(1);
// format the result as a single string
String results
= "Monthly investment: " + c.format(monthlyInvestment) + "\n"
+ "Yearly interest rate: " + p.format(interestRate / 100) + "\n"
+ "Number of years: " + years + "\n"
+ "Future value: " + c.format(futureValue) + "\n";
// print the results
System.out.println(results);
}
}
Try this:
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice = sc.next();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
sc.nextLine(); // discard any other data entered on the line
System.out.println("Error! Enter y or n. Try again.");
System.out.print("Continue? (y/n): "); //this was missing
choice = sc.next(); //take the input again
}
return choice;
}
You are getting stuck in a while loop in case of invalid input and not accepting the input again.
So, the issue is that my program goes fine through the process of collecting the two integers to go into the rational class, but then upon getting to the menu, it just exits after taking the choice. I've no idea why and no one is around to help.
EDIT: After significant fiddling, I've managed to at least get the system to give me some output: that is, that regardless of the number that I put in it is giving me the invalid output. I'm thinking maybe I should go back to the switch/case?
Here's the code:
import java.util.Scanner;
public class RationalDriver
{
private static Scanner in = new Scanner(System.in);
private static char choice;
private static String input;
public static void main(String[] args)
{
printHeading();
Rational first = new Rational();
numberOne(first);
Rational second = new Rational();
numberTwo(second);
menu(first, second);
}
public static void menu(Rational first, Rational second)
{
try{
displayMenu();
getValue(choice);
if(choice == '1')
{
System.out.println("\n" + first + " + " + second + " equals ");
first.add(second);
System.out.println(first);
}
else if(choice == '2')
{
System.out.println("\n" + first + " - " + second + " equals ");
first.subtract(second);
System.out.println(first);
}
else if(choice == '3')
{
System.out.println("\n" + first + " * " + second + " equals ");
first.multiply(second);
System.out.println(first);
}
else if(choice == '4')
{
System.out.println("\n" + first + " / " + second + " equals ");
first.divide(second);
System.out.println(first);
}
else if(choice == '5')
{
System.out.println("\nAre " + first + " and " + second + " equal?");
if(first.equals(second))
{
System.out.println("\nYes!");
}
}
else if(choice == '6')
{
System.out.println("Please enter a new rational number: ");
numberOne(first);
}
else if(choice == '7')
{
System.out.println("Please enter a new rational number: ");
numberTwo(second);
}
else if(choice == '8')
{
System.out.println("You chose to exit.");
System.exit(0);
}
else
{
System.out.println("You did not choose a valid entry.");
}
}
catch (Exception e) { e.printStackTrace(); }
}
private static void printHeading() // printHeading method
{
System.out.println("Oliver, James");
System.out.println("CSC201-02PR");
System.out.println("Dr. Java");
System.out.println("Project 7");
System.out.println("Rational Number");
System.out.println();
}
private static void displayMenu()
{
System.out.println("Enter the corresponding number for the desired action:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Test for Equality");
System.out.println("6. Change 1st Rational Number");
System.out.println("7. Change 2nd Rational Number");
System.out.println("8. Exit");
}
public static char getValue(char choice)
{
System.out.println("\nPlease enter your menu option (1 - 8):");
choice = in.next().charAt(0);
return choice;
}
public static void numberOne(Rational first)
{
int numer = 0;
int denom = 1;
boolean breaker = false;
while(!breaker)
{
System.out.println("Please enter your first numerator:");
input = in.next();
numer = Integer.parseInt(input);
System.out.println("Please enter your first denominator:");
input = in.next();
denom = Integer.parseInt(input);
if(denom == 0)
{
System.out.println("Denominator cannot be undefined.");
denom = in.nextInt();
}
else
breaker = true;
}
first.setNumer(numer);
first.setDenom(denom);
first.normalize();
System.out.println("Your rational number is: " + first + "\n");
}
public static void numberTwo(Rational second)
{
int numer = 0;
int denom = 1;
boolean breaker = false;
while(!breaker)
{
System.out.println("Please enter your second numerator:");
input = in.next();
numer = Integer.parseInt(input);
System.out.println("Please enter your second denominator:");
input = in.next();
denom = Integer.parseInt(input);
if(denom == 0)
{
System.out.println("Denominator cannot be undefined.");
denom = in.nextInt();
}
else
breaker = true;
}
second.setNumer(numer);
second.setDenom(denom);
second.normalize();
System.out.println("\nYour rational number is: " + second + "\n");
}
}
Here's the Rational class that I've made:
public class Rational
{
private int numerator; // instance variable for the numerator
private int denominator; // instance variable for the denominator
public Rational() // Constructor
{
numerator = 0;
denominator = 1;
}
public Rational(int numer, int denom) // Overloaded Constructor
{
numerator = numer;
denominator = denom;
normalize();
}
public void setNumer(int numer) // Setter for the Numerator value
{
numerator = numer;
}
public void setDenom(int denom) // Setter for the Denominator value
{
denominator = denom;
}
public void normalize()
{
if(denominator < 0)
{
denominator = -denominator;
numerator = -numerator;
}
}
public int getNumer() // Numerator Getter
{
return numerator;
}
public int getDenom() // Denominator Getter
{
return denominator;
}
public void add(Rational second) // Addition method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = ((a * d) + (b * c));
denominator = (b * d);
this.normalize();
}
public void subtract(Rational second) // Subtraction Method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = ((a * d) - (b * c));
denominator = (b * d);
this.normalize();
}
public void multiply(Rational second) // Multiplication Method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = (a * c);
denominator = (b * d);
this.normalize();
}
public void divide(Rational second) // Division Method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = (a * d);
denominator = (b * c);
this.normalize();
}
public boolean equals(Object second) // Equals method
{
if(second == null)
{
return false;
}
if(!(second instanceof Rational))
{
return false;
}
Rational other = (Rational)second;
return this.getNumer() * other.getDenom() == other.getNumer() * this.getDenom();
}
public String toString() // toString method
{
if(numerator == 0)
{
return "Result = 0";
}
if(denominator == 1)
{
return Integer.toString(numerator);
}
return Integer.toString(numerator) + "/" + Integer.toString(denominator);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does the array "prevScore" not print the value "points"?
I want it to print out points for prevScore [0], and then null 0
This is the array, after the // is something I thought I could use.
int [] prevScore = new int[10]; //{ 0 };
String [] prevScoreName = new String[10]; //{"John Doe"};
public static int[] scoreChange (int prevScore[], int points)
{
for(int i = 9; i > 0; i--){
prevScore[i] = prevScore[i-1];
}
prevScore[0]= points;
return prevScore;
}
I dont know if the print of prevScore is needed.
//a method that prints high scores
public static void printScores (int prevScore[], String prevScoreName[])
{
for (int i = 10; i > 0; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}
}
Here is the rest of my program I am working on... currently only i get one, 0 John Doe.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
do {
int menuchoice = 0;
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1){
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2){
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName); }
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR"); }
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct){
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ){
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
Use this loop:
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
I think it should solve your problem.
Update
based on your updated program. Move the following code above the start of the 'do' loop.
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
That is you are moving these lines out of the loop. It should work now.
That is the start of your 'main' method should look something like this:
public static void main(String args[]) throws IOException {
int press = 0;
int[] prevScore = new int[] { 0 };
String[] prevScoreName = new String[] { "John Doe" };
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions," + "3 prev score");
Your printScore() method is trying to access element [10] of an array whose index range is 0 - 9, and is never accessing element [0]. You may want to print the most recent score first:
for (int i = 0; i < 10; i++) {
Or conversely, to print the most recent score last:
for (int i = 9; i >= 0; i--) {
Thank you so much! It Works! The only problem still is that the scorelist prints backwards.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
int[] prevScore = new int[10];
String[] prevScoreName = new String[10];
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1) {
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2) {
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName);
}
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR");
}
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct) {
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ) {
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
System.out.println("Scores: ");
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}