I'm trying to learn Java, but I'm struggling a little bit. I'm trying to do an assignment from a textbook, so I did it in javascript and was using my limited knowledge of Java to convert it over. (Here's the original instructions - http://i518.photobucket.com/albums/u341/ACrippledFerret/5ea8ec0e-02aa-4b96-b207-a83c52f8db48_zps2cd2ab7f.jpg)
I think I've got most of it correct, but I'm running into a couple of errors. Almost all of it is "(variable) cannot be resolved to a variable". It happens to lots of variables in my last method. I also seem to have an issue with a bracket somewhere... "Syntax error on token "}", { expected after this token".
If anyone can help fix this code, I would be very grateful. I am new to Java so this is a bit tough for me to translate. The first set of code is the javascript, the second set of code is my translated java (That's not working). Thanks for any help.
JAVASCRIPT
window.onload=function(){
var difficulty = 1,
operators = ['plus', 'minus', 'times', 'divided by'],
selectedOperator = 1,
correctAnswers = 0,
answeredTyped = 0;
var difficultyInput = parseInt(prompt('Please choose the difficulty. Enter the number of digits to use in each problem.'), 10);
if(difficultyInput > 0) {
difficulty = difficultyInput;
}
var arithmeticMethod = parseInt(prompt('Choose an arithmetic problem to study:\n1 = Addition Only\n2 = Subtraction Only\n3 = Multiplication Only\n4 = Division Only\n5 = Random Problems'), 10);
if(arithmeticMethod == 5 || operators[arithmeticMethod - 1]) {
selectedOperator = arithmeticMethod;
}
function checkResponse(primaryInt, secondaryInt, operatorText, suggestedAnswer) {
var result = false;
switch (operatorText) {
case 'plus':
return (primaryInt + secondaryInt) == suggestedAnswer;
case 'minus':
return (primaryInt - secondaryInt) == suggestedAnswer;
case 'times':
return (primaryInt * secondaryInt) == suggestedAnswer;
case 'divided by':
return (primaryInt / secondaryInt) == suggestedAnswer;
default:
return false;
}
}
function displayResponse(isCorrect) {
var randomIndex = Math.floor(Math.random() * (4 - 1 + 1)) + 1;
switch (randomIndex) {
case 1:
return isCorrect ? 'Very good!' : 'No. Please try again.';
case 2:
return isCorrect ? 'Excellent!' : 'Wrong. Try once more.';
case 3:
return isCorrect ? 'Nice Work!' : 'Don\'t give up!';
case 4:
return isCorrect ? 'Keep up the good work!' : 'No. Keep trying.';
default:
return 'Woops...';
}
}
function askQuestion() {
var correctAnswer = false;
var primaryInt = Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
secondaryInt = Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
operatorText = (selectedOperator == 5) ? operators[Math.floor(Math.random() * operators.length)] : operators[selectedOperator - 1];
while(!correctAnswer && answeredTyped < 10) {
var response = parseFloat(prompt('How much is ' + primaryInt + ' ' + operatorText + ' ' + secondaryInt + '?'));
correctAnswer = checkResponse(primaryInt, secondaryInt, operatorText, response);
alert(displayResponse(correctAnswer));
answeredTyped++;
if(correctAnswer)
correctAnswers++;
}
}
while(answeredTyped < 10) {
askQuestion();
}
if((correctAnswers / answeredTyped) >= 0.75) {
alert('Congratulations, you are ready to go on the next level!');
} else {
alert('Please ask your teacher for extra help.');
}
}
JAVA
import java.util.*;
import javax.swing.JOptionPane;
/**
*
*/
/**
* #author Tyler
*
*/
public class Assignment2 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int difficulty = 1;
String[] operators = {"plus", "minus", "times", "divided by"};
int selectedOperator = 1;
int correctAnswers = 0;
int answeredTyped = 0;
int difficultyInput = Integer.parseInt(JOptionPane.showInputDialog("Please choose the difficulty. Enter the number of digits to use in each problem."));
if (difficultyInput > 0) {
difficulty = difficultyInput;
}
int arithmeticMethod = Integer.parseInt(JOptionPane.showInputDialog("Choose an arithmetic problem to study: 1 = Addition Only, 2 = Subtraction Only, 3 = Multiplication Only, 4 = Division Only, 5 = Random Problems" ));
selectedOperator = arithmeticMethod;
}
public static boolean checkResponse (double primaryInt, double secondaryInt, String operatorText, float response){
boolean result = false;
switch (operatorText){
case "1":
return (primaryInt + secondaryInt) == response;
case "2":
return (primaryInt - secondaryInt) == response;
case "3":
return (primaryInt * secondaryInt) == response;
case "4":
return (primaryInt / secondaryInt) == response;
}
return false;
}
public static String displayResponse (boolean isCorrect){
int randomIndex = (int) (Math.floor(Math.random() * (4 - 1 + 1)) + 1);
switch (randomIndex){
case 1:
return isCorrect ? "Very Good!" : "No. Please try again.";
case 2:
return isCorrect ? "Excellent!" : "Wrong. Try once more.";
case 3:
return isCorrect ? "Nice Work!" : "Don\'t give up!";
case 4:
return isCorrect ? "Keep up the good work!" : "No. Keep trying.";
}
return "Oops...";
}
public static void askQuestion(int difficulty, String operatorText, int selectedOperator, int answeredTyped, String[] operators, int correctAnswers){
boolean correctAnswer = false;
double primaryInt = Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
double secondaryInt = Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
operatorText = (selectedOperator == 5) ? operators[(int) Math.floor(Math.random() * operators.length)] : operators[selectedOperator - 1];
while(!correctAnswer && answeredTyped < 10) {
float response = Float.parseFloat (JOptionPane.showInputDialog("How much is " + primaryInt + " " + operatorText + " " + secondaryInt + "?"));
correctAnswer = checkResponse (primaryInt, secondaryInt, operatorText, response);
JOptionPane.showMessageDialog(null, displayResponse(correctAnswer));
answeredTyped++;
if(correctAnswer)
correctAnswers++;
}
{
while(answeredTyped < 10){
askQuestion(0, null, 0, 0, null, 0);
}
if((correctAnswers / answeredTyped) >= 0.75) {
JOptionPane.showMessageDialog(null, "Congratulations, you are ready to go on to the next level!");
}
else{
JOptionPane.showMessageDialog(null, "Please ask your teacher for extra help.");
}
}
}
}
The scoping is different in Java than in Javascript; Java variables defined in a method (static or instance) will be valid only within that method, so you can't reference variables such as difficulty (defined in main()) from other methods such as askQuestion(). You could make them static class member variables, but that's generally bad practice in Java (and also in Javascript, really), so the better option is to pass them into methods such as askQuestion() as arguments to the method.
Related
Sorry if this is a simple error, I am still very new to Java and have trouble with all the rules. I am trying to create a calculator that takes in roman numerals, converts them to integers, them performs operations with them, and then converts them back roman numerals to print by calling methods. I put this together looking at some examples and it seems to almost all work out except for the convertFromRoman method. If anyone sees any other errors please let me know because I really feel lost. Heres the code:
package roman_calculator;
import java.util.Scanner;
public class RomanCalculator {
public static Scanner kbInput = new Scanner(System.in);
public static String doMath(char operator, int firstNum, int secondNum) {
switch (operator) {
case '+':
return convertToRoman(firstNum + secondNum);
case '-':
return convertToRoman(firstNum - secondNum);
case '*':
return convertToRoman(firstNum * secondNum);
case '/':
return convertToRoman(firstNum / secondNum);
}
return "omething";
/*
* This method will perform the arithmetic
* indicated by the operator (+ -* /),
* invoke convertToRoman to convert answer to Roman number,
* then return answer
* */
}
public static char getOperator() {
System.out.println("please choose an operator: +, - , * , or /");
return kbInput.next().charAt(0);
}
public static int getOperands(int which) {
while (true) {
System.out.print("Enter operand" + ": ");
String roman = kbInput.nextLine().toUpperCase();
int romanNum = convertFromRoman(roman);
if (romanNum >= 0)
return romanNum;
else
System.out.println("Bad operand, please try again");
/*This routine should prompt the user to enter Roman number.
convertFromRoman needs to be invoked to convert the Roman number to an integer.
If the input is invalid (-1 returned from convertFromRoman)
then complain and prompt the user again.
*/
}
public static int convertFromRoman(String roman) {
int result = 0;
for (int i = 0; i < roman.length(); i++) {
int s1 = num(roman.charAt(i));
if (s1 < 0) {
System.out.println("Invalid operand");
}
if (i + 1 < roman.length()) {
int s2 = num(roman.charAt(i + 1));
if (s2 < 0) {
System.out.println("Invalid operand");
}
if (s1 >= s2) {
result = result + s1;
} else {
result = result + s2 - s1;
i++;
}
} else {
result = result + s1;
i++;
}
}
return result;
}
/*
* This method will convert Roman number to integer
* return -1 when input is invalid
*
* */
}
public static String convertToRoman(int num) {
System.out.println(num);
String roman = "";
while (num > 0) {
while (num >= 1000) {
roman = roman + "M";
num -= 1000;
}
while (num >= 500) {
roman = roman + "M";
num -= 500;
}
while (num >= 100) {
roman = roman + "D";
num -= 100;
}
while (num >= 50) {
roman = roman + "C";
num -= 50;
}
while (num >= 10) {
roman = roman + "X";
num -= 10;
}
while (num >= 5) {
roman = roman + "V";
num -= 5;
}
while (num >= 1) {
roman = roman + "I";
num -= 1;
}
}
return roman;
}
static int num (char r) {
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
/*
* This method will convert integer to Roman number
* */
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String result;
do {
result = doMath(getOperator(), getOperands(), getOperands());
System.out.println(result);
System.out.println("do you want to continue? y/n");
kbInput.nextLine();
} while (kbInput.nextLine().charAt(0) == 'y');
System.out.println("Have a nice day!");
}
}
You have a missing } in the following code, the last } was missing.
public static int getOperands(int which) {
while (true) {
System.out.print("Enter operand" + ": ");
String roman = kbInput.nextLine().toUpperCase();
int romanNum = convertFromRoman(roman);
if (romanNum >= 0)
return romanNum;
else
System.out.println("Bad operand, please try again");
}
}
And you need to remove the last } from the methode convertFromRoman.
Also there is a error in the line result = doMath(getOperator(), getOperands(), getOperands()); where you either need to pass a parameter to getOperands() or change the method signiture to getOperator() or whatever you are trying.
A tip for you: Formating your code makes it easier to read and see the layers (e.g for Eclispe IDE is it Ctrl + Shift + F)
The title says this is homework, I have been beating my head into the wall for hours, so please help. It works fine, at least the math part does, I work the conversion it worked just fine. I went to change the output dialog box to list what the ending unit was, instead of just listing the variable e.g. your lbs is the end. And not to allow negative starting weights.
Now I can't get the dialog box to not give me an error. (Lines 145 -148) I put in a sample dialog box using the Return option that doesn't work, but if I set it to a variable in my case test, it will work fine. He gave us starting code, I recopied his original code and that doesn't work. The next error I get is I wrote a method that takes two doubles and a char. When I call the function I pass it two doubles and a char it says it can't convert a string (Line 255).
This has been frustrating I over engineered this and now to have it not work is killing me. I don't understand how I can copy his original code in and it no longer works. Dialog boxes confuse me but I think I understand them.
return JOptionPane.showConfirmDialog(A)(null(B), display(C),0,1);
A is the call of the for the box what type
B is the object type my understanding its always call
C is the string, text message of the box
The last two got to do with the the icon and button displayed.
He got us started on eclipse, which said I had error in code where there none, I spent hours looking at them, they went away once I reloaded my code.
Please any thing would be helpful, but an example or corrected code (I know that is a lot) with explanations on why there are correct would be helpful. My husband knows java but not dialog boxes, so he can't help. And the method call looks right to both of us.
/*
* Uses: methods, dialog boxes, and a menu to convert weights
*
*/
import javax.swing.JOptionPane;
public class WeightCon {
char choices, choicee;
public static char menu() {
char choice;
int typeNum = 3;
boolean OK;
String prompt, results, title;
prompt = "Choose Starting Unit\n";
prompt += "A. Pounds\n";
prompt += "B. Kilograms\n";
prompt += "C. Stones\n";
prompt += "D. ounces\n";
prompt += "E. Netons\n";
prompt += "F.Grams\n";
prompt += "\n\nEnter the letter of your choice:";
title = "Weights";
do {
results = JOptionPane.showInputDialog(null,prompt,title, typeNum);
choice = results.toUpperCase().charAt(0);
if(choice >= 'A' && choice <= 'F') {
OK = true;
}
else {
OK = false;
title = "Not Valid Input!";
typeNum = 0;
}
}while(! OK);
return choice;
}
public static double LbstoKG(double k) {
return k * 0.453592;
}
public static double KtoLBS(double L) {
return L / 0.453592;
}
public static double LbstoStone(double S) {
return S / 14;
}
public static double LBStoOunce(double O) {
return O / .0625;
}
public static double LbstoNewton(double N) {
return N * 4.4482216282509;
}
public static double LBStoGarm(double G) {
return G / 0.00220462 ;
}
public static double KtoL(double L) {
return L / 0.453592;
}
public static double stoneToLbs(double L) {
return L * 14;
}
public static double ounceToLBS(double L) {
return L * .0625;
}
public static double NewtonToLBS(double L) {
return L / 4.4482216282509;
}
public static double GramtoLBS(double L) {
return L * 0.00220462 ;
}
//public static double
public static double getDouble(String prompt) {
boolean OK;
double val=0;
String temp, title = "Enter a double value";
int typeNum = 3;
do {
OK = true;
temp = JOptionPane.showInputDialog(null, prompt, title, typeNum);
try {
val = Double.parseDouble(temp);
}
catch(Exception e) {
OK = false;
title = "Error! Invalid input. Must be a double value";
typeNum = 0;
}
try {
val = Double.parseDouble(temp);
}
catch(Exception b) {
if( val < 0) {
title = "Error! Invalid input. Must be a positive double value";
typeNum = 0;
}
}while(! OK);
}while(! OK);
return val;
}
public static String outputResults(double start, double end, char choices){
int test;
String end1;
if(choices == 'A') {
end1 = "Your end weight is the following pounds: ";
} else if (choices == 'B') {
end1 = " Your end weight is the following kilograms: ";
} else if (choices == 'C') {
end1 = " Your end weight is the following stones: ";
} else if (choices == 'D') {
end1 = " Your end weight is the following ounces: ";
} else if (choices == 'E') {
end1 = " Your end weight is the following newtons: ";
} else if (choices == 'F') {
end1 = " Your end weight is the following grams: ";
} else {end1 = " ERROR ERROR UNDEFINDED ERROR PLEASE CONSOLT DOCUMENTATION";}
String endreal = String.valueOf(end);
String display = "" + end1 + endreal;
//int input =
test = JOptionPane.showConfirmDialog(null, display,0,1);
test = JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display,0,1);
}
//display += "Do again?";
//return JOptionPane.showConfirmDialog(null,"test",0,1);
//return JOptionPane.showConfirmDialog(null,display,0,1);}}
//return JOptionPane.showConfirmDialog(null, "test",0,1);}}
//}
//
public static void main(String[] args) {
double get;
double lbs=0,ounce=0,kgs=0, stone=0,newton=0,gram=0 ;
double temp,start, end;
char choice, choices;
int button;
//String end1;
start =-99;
end = -999;
get = 0;
temp = 0;
do {
choice = menu();
choices = choice;
switch(choice) {
case 'A':
get = getDouble("Enter pounds : ");
lbs = get;
start = get; //LbstoKG(get);
temp = kgs;
break;
case 'B':
get = getDouble("Enter kilograms : ");
kgs = get;
start = KtoL(get);
temp = lbs;
break;
case 'C':
get = getDouble("Enter Stones : ");
stone = get;
start = stoneToLbs(get);
temp = lbs;
break;
case 'D':
ounce = getDouble("Enter Ounces : ");
start = ounceToLBS(get);
temp = lbs;
break;
case 'E':
get= getDouble("Enter Newtons : ");
newton = get;
start = NewtonToLBS(get);
temp = lbs;
break;
case 'F':
get = getDouble("Enter grams : ");
gram = get;
start = GramtoLBS(get);
temp = lbs;
break;
}
//button = outputResults(get,get);
//} while(button == 0);
// do {
choice = menu();
switch(choice) {
case 'A':
//get = getDouble("Enter pounds : ");
//lbs = getDouble("Enter pounds : ");
//kgs = get;
end = start;
break;
case 'B':
//get = getDouble("Enter kilograms : ");
end = LbstoKG(start);
break;
case 'C':
//get = getDouble("Enter Stones : ");
//stone = get;
end = LbstoStone(start);
break;
case 'D':
//ounce = getDouble("Enter Ounces : ");
end = LBStoOunce(start);
break;
case 'E':
//get= getDouble("Enter Newtons : ");
end = LbstoNewton(start);
System.out.printf("Hello");
break;
case 'F':
//get = getDouble("Enter grams : ");
end = LBStoGarm(start);
break;
}
button = outputResults(end,start,choice);
} while(button == 0);
}}
After copying and pasting your code into my compiler, there were multiple errors.
First Mistake in outputResults(): Remove the 0, and the 1.
The method showConfirmDialog(Component, Object, String, int) in the type JOptionPane
is not applicable for the arguments (null, String, int, int)
Line:
test = JOptionPane.showConfirmDialog(null, display,0,1);
Correction:
test = JOptionPane.showConfirmDialog(null, display);
Second and Third Mistake also in outputResults(): You cannot return two objects. Also, your method returns a String.
return JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display,0,1); // 0, 1 again.
// The second return statement is dead code, and this also makes the first mistake again
Your method returns a String.
JOptionPane.showConfirmDialog(null, display); returns an int.
So in your method returning a String, if you return an int instead, it will be a compiler error. For example:
... String outputResults(...){
return JOptionPane.showConfirmDialog(null, display);
}
1 quick fix: change return type to int (method: String outputResults(double, double, char))
Fourth Mistake in main(): Fix your Third Mistake and ignore this fix.
int button = ...;
...
button = outputResults(end,start,choice); // Returns String, but button is an int
// Change button to a string?
// Integer.parseInt(outputResults(end,start,choice)); ?
I'm creating a math program that asks the user how many digits they'd like to use, then asks them what kind of math they want to do. It then asks the user 10 math questions based on their answers. It then decides if they're right or wrong and displays an appropriate message. It then calculates their percentage of correct answers and displays a message based on the percentage.
The problem is that the program never stops after 10 questions and never calculates the percentage or displays the final message. I believe this is at least partially occurring because I'm not passing the new "answeredTyped" value from the "askQuestion" method. Can someone explain how I can easily pass this new value back to the main method so that it'll stop at 10? Or perhaps tell me what else is keeping this from working correctly?
I've asked quite a few questions about this program already, so I appreciate everyone's patience with me learning Java and having very little knowledge of the language.
Thank you for any help! (also I apologize for any bad formatting here! After changing about a million things, it got ugly)
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Assignment2 {
public static int answeredTyped = 0;
public static int correctAnswers = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int difficulty = 1;
String[] operators = { "plus", "minus", "times", "divided by" };
int selectedOperator = 1;
int difficultyInput = Integer
.parseInt(JOptionPane
.showInputDialog("Please choose the difficulty. Enter the number of digits to use in each problem."));
if (difficultyInput > 0) {
difficulty = difficultyInput;
}
int arithmeticMethod = Integer
.parseInt(JOptionPane
.showInputDialog("Choose an arithmetic problem to study: 1 = Addition Only, 2 = Subtraction Only, 3 = Multiplication Only, 4 = Division Only, 5 = Random Problems"));
selectedOperator = arithmeticMethod;
new Assignment2().askQuestion(difficulty, null, selectedOperator,
answeredTyped, operators, correctAnswers);
while (answeredTyped < 10) {
askQuestion(difficulty, null, selectedOperator, answeredTyped,
operators, correctAnswers);
answeredTyped++;
if (answeredTyped>= 10) {
if (((float) correctAnswers / answeredTyped) >= 0.75) {
JOptionPane
.showMessageDialog(null,
"Congratulations, you are ready to go on to the next level!");
} else {
JOptionPane.showMessageDialog(null,
"Please ask your teacher for extra help.");
}
}
}
}
public static boolean checkResponse(double primaryInt, double secondaryInt,
String operatorText, double response) {
if (operatorText.equals("plus")) {
return (primaryInt + secondaryInt) == response;
} else if (operatorText.equals("minus")) {
return (primaryInt - secondaryInt) == response;
} else if (operatorText.equals("times")) {
return (primaryInt * secondaryInt) == response;
} else if (operatorText.equals("divided by")) {
return (primaryInt / secondaryInt) == response;
}
return false;
}
public static String displayResponse(boolean isCorrect) {
int randomIndex = (int) (Math.floor(Math.random() * (4 - 1 + 1)) + 1);
switch (randomIndex) {
case 1:
return isCorrect ? "Very Good!" : "No. Please try again.";
case 2:
return isCorrect ? "Excellent!" : "Wrong. Try once more.";
case 3:
return isCorrect ? "Nice Work!" : "Don\'t give up!";
case 4:
return isCorrect ? "Keep up the good work!" : "No. Keep trying.";
}
return "Oops...";
}
public static void askQuestion(int difficulty, String operatorText,
int selectedOperator, int answeredTyped, String[] operators,
int correctAnswers) {
boolean correctAnswer = false;
double primaryInt = Math.floor(Math.pow(10, difficulty - 1)
+ Math.random() * 9 * Math.pow(10, difficulty - 1));
double secondaryInt = Math.floor(Math.pow(10, difficulty - 1)
+ Math.random() * 9 * Math.pow(10, difficulty - 1));
operatorText = (selectedOperator == 5) ? operators[(int) Math
.floor(Math.random() * operators.length)]
: operators[selectedOperator - 1];
double response = Double.parseDouble(JOptionPane
.showInputDialog("How much is " + primaryInt + " "
+ operatorText + " " + secondaryInt + "?"));
correctAnswer = checkResponse(primaryInt, secondaryInt,
operatorText, response);
JOptionPane.showMessageDialog(null, displayResponse(correctAnswer));
if (correctAnswer)
correctAnswers++;
}
}
You have two while loops, so it will call askQuestion() ten times, and then there is askQuestion's own while loop:
main()
while (answeredTyped < 10) {
askQuestion()
while (!correctAnswer && answeredTyped < 10) {
Try using only a single while loop, and putting the evaluation of the answers in total outside of the askQuestion() method
You have to increment answeredType in the while loop of the main method,not within another method,since you have not declared the variable as global
I'm trying to create a Java math training program. I have a working version in Javascript and some of you guys have already helped me convert it over to Java. It's supposed to ask the user a difficulty (which then uses that amount of digits for each number in the questions). It then asks the user what type of math to do (addition, subtraction, multiplication, division, random). It then asks the user 10 questions. As the user answers, it tells them if they're right or wrong. If wrong, they get to continue attempting the question. At the end of 10 questions, it calculates if you got over 75% of them right and displays an appropriate response. Full instructions:
I finally got most of it working correctly, only to find out that the math itself is wrong.
Sometimes if I enter a difficulty of 2, it only gives 1 digit (it basically doesn't calculate the difficulty right). Also, it always tells me my math is wrong. Is there any chance you guys can spot anything wrong with the logic?
Thanks for any help.
import java.util.*;
import javax.swing.JOptionPane;
public class Assignment2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int difficulty = 1;
String[] operators = {"plus", "minus", "times", "divided by"};
int selectedOperator = 1;
int correctAnswers = 0;
int answeredTyped = 0;
int difficultyInput = Integer.parseInt(
JOptionPane.showInputDialog(
"Please choose the difficulty. " +
"Enter the number of digits to use in each problem."));
if (difficultyInput > 0) {
difficulty = difficultyInput;
}
int arithmeticMethod = Integer.parseInt(
JOptionPane.showInputDialog(
"Choose an arithmetic problem to study: " +
"1 = Addition Only, 2 = Subtraction Only, " +
"3 = Multiplication Only, 4 = Division Only, " +
"5 = Random Problems" ));
selectedOperator = arithmeticMethod;
new Assignment2().askQuestion(
difficulty, null, arithmeticMethod,
arithmeticMethod, operators, arithmeticMethod);
}
public static boolean checkResponse (
int primaryInt, int secondaryInt,
String operatorText, float response){
boolean result = false;
switch (operatorText) {
case "1":
return (primaryInt + secondaryInt) == response;
case "2":
return (primaryInt - secondaryInt) == response;
case "3":
return (primaryInt * secondaryInt) == response;
case "4":
return (primaryInt / secondaryInt) == response;
}
return false;
}
public static String displayResponse (boolean isCorrect) {
int randomIndex = (int) (Math.floor(Math.random() * (4 - 1 + 1)) + 1);
switch (randomIndex) {
case 1:
return isCorrect ? "Very Good!" : "No. Please try again.";
case 2:
return isCorrect ? "Excellent!" : "Wrong. Try once more.";
case 3:
return isCorrect ? "Nice Work!" : "Don\'t give up!";
case 4:
return isCorrect ? "Keep up the good work!" : "No. Keep trying.";
}
return "Oops...";
}
public static void askQuestion(
int difficulty, String operatorText,
int selectedOperator, int answeredTyped,
String[] operators, int correctAnswers) {
boolean correctAnswer = false;
int primaryInt = (int) Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
int secondaryInt = (int) Math.floor(Math.pow(10, difficulty-1) + Math.random() * 9 * Math.pow(10, difficulty-1));
operatorText = (selectedOperator == 5) ? operators[(int) Math.floor(Math.random() * operators.length)] : operators[selectedOperator - 1];
while(!correctAnswer && answeredTyped < 10) {
float response = Float.parseFloat (JOptionPane.showInputDialog("How much is " + primaryInt + " " + operatorText + " " + secondaryInt + "?"));
correctAnswer = checkResponse (primaryInt, secondaryInt, operatorText, response);
JOptionPane.showMessageDialog(null, displayResponse(correctAnswer));
answeredTyped++;
if(correctAnswer)
correctAnswers++;
}
{
while(answeredTyped < 10) {
askQuestion(0, null, 0, 0, null, 0);
}
if((correctAnswers / answeredTyped) >= 0.75) {
JOptionPane.showMessageDialog(
null, "Congratulations, you are ready to " +
"go on to the next level!");
} else {
JOptionPane.showMessageDialog(
null, "Please ask your teacher for extra help.");
}
}
}
}
In you code where you are calling askQuestion you have done
new Assignment2().askQuestion(arithmeticMethod, null, arithmeticMethod, arithmeticMethod, operators, arithmeticMethod);
}
But looking at your method definition it should be, you are passing arthmeticMethod instead of difficulty level
new Assignment2().askQuestion(difficulty, null, arithmeticMethod, arithmeticMethod, operators, arithmeticMethod);
}
I'm going insane..I'm so close to getting this code to work the way I want to I just can't figure it out. I'm trying to solve a postfix equation for ex. 3 2 + , this equals 5. When I put for example
"3 2 +" in the mainmethod it works fine but as soon as I enter a 3rd digit like "3 2 + 2 *" (which equals 10) I get a arrayoutofboundserror relating back to number2 = s.pop() as you will see in the code below. Any help is greatly appreciated.
Heres the postfix meethod:
public int PostfixEvaluate(String e){
int number1;
int number2;
int result=0;
String[] tokens = e.split(" ");
for(int j = 0; j < tokens.length; j++){
String token = tokens[j];
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
String Operator = tokens[j];
number1 = s.pop();
number2 = s.pop();
if (Operator.equals("/")){
result = number1 / number2;}
else if(Operator.equals("*")){
result = number1 * number2;}
else if(Operator.equals("+")){
result = number1 + number2;}
else if(Operator.equals("-")){
result = number1 - number2;}
else System.out.println("Illeagal symbol");
}
s.push(result);
s.pop();
}
//s.pop();
System.out.println("Postfix Evauation = " + result);
return result;
}
public static void main(String[] args) {
Stacked st = new Stacked(100);
//String y = new String("((z * j)/(b * 8) ^2");
String x = new String("2 2 2 * +");
TestingClass clas = new TestingClass(st);
//clas.test(y);
clas.PostfixEvaluate(x);
}
}
/**
* Evaluate postfix arithmetic expression
*
* #example "1 12 23 + * 4 5 / -" => 34.2
* #author Yong Su
*/
import java.util.Stack;
class PostfixEvaluation {
public static void main(String[] args) {
String postfix = "1 12 23 + * 4 5 / -";
Double value = evaluate(postfix);
System.out.println(value);
}
/**
* Evaluate postfix expression
*
* #param postfix The postfix expression
*/
public static Double evaluate(String postfix) {
// Use a stack to track all the numbers and temporary results
Stack<Double> s = new Stack<Double>();
// Convert expression to char array
char[] chars = postfix.toCharArray();
// Cache the length of expression
int N = chars.length;
for (int i = 0; i < N; i++) {
char ch = chars[i];
if (isOperator(ch)) {
// Operator, simply pop out two numbers from stack and perfom operation
// Notice the order of operands
switch (ch) {
case '+': s.push(s.pop() + s.pop()); break;
case '*': s.push(s.pop() * s.pop()); break;
case '-': s.push(-s.pop() + s.pop()); break;
case '/': s.push(1 / s.pop() * s.pop()); break;
}
} else if(Character.isDigit(ch)) {
// Number, push to the stack
s.push(0.0);
while (Character.isDigit(chars[i]))
s.push(10.0 * s.pop() + (chars[i++] - '0'));
}
}
// The final result should be located in the bottom of stack
// Otherwise return 0.0
if (!s.isEmpty())
return s.pop();
else
return 0.0;
}
/**
* Check if the character is an operator
*/
private static boolean isOperator(char ch) {
return ch == '*' || ch == '/' || ch == '+' || ch == '-';
}
}
The number1 assignment should be after the number2 assignment. Remember that s.pop() will remove and return the number that is on the top.
number2 = s.pop();
number1 = s.pop();
Are you popping immediately after pushing?
s.push(result);
s.pop();
There is another logical error in this solution. You need to do:
number2 = s.pop();
number1 = s.pop();
your solution won't work if you had 32/ because you will evaluate it to 2/3.