I made a little random math generator, which gives out 2 random numbers and a random operator but when I call my check result method in my ok button, I always get the "Errado" ("Wrong") string which means it's not properly comparing the value of the textfield with the result of whatever math problem was presented. Leaving relevent code from both classes down here with comments on where I'm having issues and 2 for ease of understanding. Help's appreciated!
public class geraAritmetica {
ArrayList<Integer> nums = new ArrayList();
int a;
char ops = '?';
int max = 10;
int min = 1;
int range = max - min + 1;
int res;
Random r = new Random();
public int gerarNums(){
for(int i = 0; i<10; i++){
a = (int) (Math.random()*range) + min;
nums.add(a);
}
return a;
}
public char gerarOps(){
switch(r.nextInt(4)){
case 1 : ops = '+';
res = nums.get(0) + nums.get(1);
break;
case 2: ops = '-';
res = nums.get(0) - nums.get(1);
break;
case 3: ops = '*';
res = nums.get(0) * nums.get(1);
break;
case 4: ops = '/';
res = nums.get(0) / nums.get(1);
break;
default: ops = '+';
res = nums.get(0) + nums.get(1);
break;
}
return ops;
}
public boolean checkRes(){ //everytime I call this method always get the same string "Errado" ("Wrong") in the label.
if(Integer.parseInt(FrameEnsinoAritmetica.jTextField1.getText()) == res){
FrameEnsinoAritmetica.jLabel2.setText("Correto!");
return true;
}
else FrameEnsinoAritmetica.jLabel2.setText("Errado!");
return false;
}
}
public class FrameEnsinoAritmetica extends javax.swing.JFrame {
geraAritmetica a = new geraAritmetica(); //creating object of class at the start of my JFrame class
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { //generating numbers and operator (it prints fine in another label)
int b = a.gerarNums();
int c = a.gerarNums();
char s = a.gerarOps();
jLabel1.setText(b + " " +s+ " " + c);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
a.checkRes(); //everytime I call this method always get the same string "Errado" ("Wrong") in the label.
}
You seem to be referencing to the FrameEnsinoAritmetica class directly not the actual instance of your FrameEnsinoAritmetica jFrame that you see on screen. For example, using this in another class will not reference to the frame that you see on screen:
String text = FrameEnsinoAritmetica.jTextField1.getText();
But using this would work:
String text = yourInstanceOfEnsinoAritmetica.jTextField1.getText();
To fix this we could pass the current instance of the FrameEnsinoAritmetica that is shown on screen into the checkRes method, which we do by modifying checkRes like so, and inside the method we replace FrameEnsinoAritmetica with frame to refer to the current instance:
public boolean checkRes(FrameEnsinoAritmetica frame){ //everytime I call this method always get the same string "Errado" ("Wrong") in the label.
if(Integer.parseInt(frame.jTextField1.getText()) == res){
frame.jLabel2.setText("Correto!");
return true;
}
else frame.jLabel2.setText("Errado!");
return false;
}
Then we just update the jButton1ActionPerformed method to pass this which is the current instance of FrameEnsinoAritmetica into the updated checkRes method:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
a.checkRes(this); //everytime I call this method always get the same string "Errado" ("Wrong") in the label.
}
Fix part 2 (for res not being calculated properly)
public class FrameEnsinoAritmetica extends javax.swing.JFrame {
geraAritmetica a = new geraAritmetica();
public static int b;
public static int c;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
b = a.gerarNums();
c = a.gerarNums();
char s = a.gerarOps(this);
jLabel1.setText(b + " " +s+ " " + c + " ");
}
public class geraAritmetica {
ArrayList<Integer> nums = new ArrayList();
int a;
char ops = '?';
int max = 10;
int min = 1;
int range = max - min + 1;
public static int res;
Random r = new Random();
public int gerarNums(){
for(int i = 0; i<10; i++){
a = (int) (Math.random()*range) + min;
nums.add(a);
}
return a;
}
public char gerarOps(FrameEnsinoAritmetica frame){
switch(r.nextInt(4)){
case 1 : ops = '+';
res = frame.b + frame.c; //checking both variables directly from JFrame class instead of getting through index from ArrayList.
break;
case 2: ops = '-';
res = res = frame.b - frame.c;
break;
case 3: ops = '*';
res = frame.b * frame.c;
break;
case 4: ops = '/';
res = frame.b / frame.c;
break;
default: ops = '+';
res = frame.b + frame.c;
break;
}
return ops;
}
public boolean checkRes(FrameEnsinoAritmetica frame){
if(Integer.parseInt(frame.jTextField1.getText()) == res){
frame.jLabel2.setText("Correto!");
return true;
}
else frame.jLabel2.setText("Errado!");
return false;
}
}
Related
This may be a relatively simple question, but why is my program getting this error:Expression.java:93: error: reached end of file while parsing
}
I have tried following multiple guides online, like opening and closing my classes correctly, but unfortunately I still seem to be getting this error.
Here is my code in case this helps:
public class Expression {
private static final String SPACE = " ";
private static final String PLUS = "+";
private static final String MINUS = "-";
public static int rank(String operator) {
switch (operator) {
case "^": //5
return 3;
case "*":
case "/":
return 2;
case PLUS:
case MINUS: //2
return 1;
default:
return -1;
}
}
public static boolean isOperator(String token) { //4
if (rank(token) > 0){
return true;
}
return false;
}
public static int applyOperator(String operator,int op1,int op2){ //7
switch (operator) {
case PLUS:
return op1+op2;
case MINUS:
return op1-op2;
case "*":
return op1*op2;
case "/":
return op1/op2;
default:
return -1;
}
}
public static String toPostfix(String infixExpr) {
StringBuilder output = new StringBuilder();
Stack<String> operators = new ArrayStack<>();
for (String token: infixExpr.split("\\s+")) {
if (isOperator(token)) { // operator //4
// pop equal or higher precedence
while (!operators.isEmpty() &&
rank(operators.peek()) >= rank(token)) {
output.append(operators.pop() + SPACE);
}
operators.push(token);
} else { // operand
output.append(token + SPACE);
}
}
while (!operators.isEmpty()) {
output.append(operators.pop() + SPACE);
}
return output.toString();
}
public class PostFixTest {
public static int evalPostfix(String infixExpr) {
Stack <String> s = new ArrayStack<String>();
String operand = null;
for(int i = 0; i < infixExpr.length(); i++) {
if (Character.isDigit(infixExpr.charAt(i)))
s.push(infixExpr.charAt(i) + "");
else {
if (s.size() > 1) {
int value1 = Integer.parseInt(s.pop());
int value2 = Integer.parseInt(s.pop());
s.push(applyOperator(infixExpr.charAt(i) + "", value1, value2) + "");
}
}
}
return s.pop();
}
}
public static void main(String[] args) {
System.out.println(rank("/"));
String infix = "a * b * c + d ^ e / f";
System.out.println(toPostfix(infix));
System.out.print("Using applyOperator method, 7 * 3 = ");
System.out.println(applyOperator("*", 3, 7));
System.out.print("Using applyOperator method, 50 + 12 = ");
System.out.println(applyOperator("+", 50, 12));
}
You are losing right } in your code last. like:
...
public static void main(String[] args) {
System.out.println(rank("/"));
String infix = "a * b * c + d ^ e / f";
System.out.println(toPostfix(infix));
System.out.print("Using applyOperator method, 7 * 3 = ");
System.out.println(applyOperator("*", 3, 7));
System.out.print("Using applyOperator method, 50 + 12 = ");
System.out.println(applyOperator("+", 50, 12));
}
} // you lost this bracket.
As the title says, I cannot convert my ArrayList into an Array. The data type of my ArrayList is a custom object but I cannot seem to find what my problem is. The error that it gives doesn't show up as a problem until the program is run. The first two classes are the objects, then I have a class calle Tester where the main method is.
Class where error appears:
package backend;
import java.util.ArrayList;
public class Function {
Coefficient[] coefArray;
int constant;
public Function(ArrayList<Coefficient> coefFunction, int constant){
Coefficient[] coefArray = (Coefficient[]) coefFunction.toArray();
this.coefArray = sortArray(coefArray);
this.constant = constant;
}
private Coefficient[] sortArray(Coefficient[] newArray){
int tempPow = -1000000000;
Coefficient[] sortedArray = new Coefficient[newArray.length];
sortedArray = null;
for(int i=0; isFull(sortedArray); i++){
for(Coefficient coef : newArray){
if(coef.pow>tempPow){
tempPow = coef.pow;
sortedArray[i] = coef;
}
}
}
return sortedArray;
}
private boolean isFull(Coefficient[] anArray){
for(Coefficient i : anArray) {
if(i == null) return true;
}
return false;
}
public String toString(){
String compiledString="";
for(Coefficient coef : coefArray){
compiledString += coef.toString()+"+";
}
if(constant==0){
//No constant there
}else{
compiledString = compiledString + constant;
}
return compiledString;
}
}
Coefficient Class:
package backend;
public class Coefficient {
String stringVersion;
public int pow;
public int coefInteger;
public double coefDouble;
//Constructor for variable with a coefficient that is non-fractal and a power higher than 1
public Coefficient(int coef, int pow){
this.coefInteger = coef;
this.pow = pow;
switch(coef){
case 0:
//Do nothing here
case 1:
this.stringVersion = "x^"+pow;
break;
default:
this.stringVersion = coef+"x^"+pow;
break;
}
}
//Constructor for variable with a coefficient that is fractal and a power higher than 1
public Coefficient(double coef, int pow){
this.coefDouble = coef;
this.pow = pow;
this.stringVersion = coef+"x^"+pow;
}
//Constructor for variable with a coefficient but no power
public Coefficient(double coef){
this.coefDouble = coef;
this.pow = 1;
this.stringVersion = coef+"x";
}
//Constructor for variable with a coefficient but no power
public Coefficient(int coef){
this.coefInteger = coef;
this.pow = 1;
this.stringVersion = coef+"x";
}
public String toString(){
return stringVersion;
}
}
Tester:
package backend;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Coefficient> function = new ArrayList<Coefficient>();
Coefficient xVal;
Function printFunction;
System.out.println("Enter the degree of the equation:");
int pow = scan.nextInt();
System.out.println("Enter the x components of the function in the order of coefficient then power. Enter constant last:");
double coef = 0;
while(pow>0){
coef = scan.nextDouble();
if(pow==1){
if((int) coef == coef){
xVal = new Coefficient((int) coef);
}else{
xVal = new Coefficient(coef);
}
}else{
if((int) coef == coef){
xVal = new Coefficient((int) coef, pow);
}else{
xVal = new Coefficient(coef, pow);
}
}
function.add(xVal);
pow--;
}
System.out.println("Enter the constant:");
printFunction = new Function(function, scan.nextInt());
System.out.println(printFunction.toString());
}
}
Error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object;
cannot be cast to [Lbackend.Coefficient;
at backend.Function.<init>(Function.java:11)
at backend.Tester.main(Tester.java:36)
Any and all help is greatly appreciated. If you see something else that needs to be fixed, please point it out.
The error is in this line:
Coefficient[] coefArray = (Coefficient[]) coefFunction.toArray();
If you read the javadoc of toArray(), you can see that it returns an Object[], which you cannot simply cast to Coefficient[].
Instead use toArray(T[] a):
Coefficient[] coefArray = coefFunction.toArray(new Coefficient[coefFunction.size()]);
Disclaimer: I did not review the rest of your code, so the absence of any remarks does not imply that everything else is fine.
This question already has answers here:
Converting Roman Numerals To Decimal
(30 answers)
Closed 9 years ago.
Trying to write program to read in a string of characters that represent a Roman numeral (from user input) and then convert it to Arabic form (an integer). For instance, I = 1, V = 5, X = 10 etc.
Basically, the constructor that takes a parameter of type String must interpret the string (from user input) as a Roman numeral and convert it to the corresponding int value.
Is there an easier way to solve this besides the below in progress (which isn't compiling as yet):
import java.util.Scanner;
public class RomInt {
String roman;
int val;
void assign(String k)
{
roman=k;
}
private class Literal
{
public char literal;
public int value;
public Literal(char literal, int value)
{
this.literal = literal;
this.value = value;
}
}
private final Literal[] ROMAN_LITERALS = new Literal[]
{
new Literal('I', 1),
new Literal('V', 5),
new Literal('X', 10),
new Literal('L', 50),
new Literal('C', 100),
new Literal('D', 500),
new Literal('M', 1000)
};
public int getVal(String s) {
int holdValue=0;
for (int j = 0; j < ROMAN_LITERALS.length; j++)
{
if (s.charAt(0)==ROMAN_LITERALS[j].literal)
{
holdValue=ROMAN_LITERALS[j].value;
break;
} //if()
}//for()
return holdValue;
} //getVal()
public int count()
{
int count=0;
int countA=0;
int countB=0;
int lastPosition = 0;
for(int i = 0 ; i < roman.length(); i++)
{
String s1 = roman.substring(i,i+1);
int a=getVal(s1);
countA+=a;
}
for(int j=1;j<roman.length();j++)
{
String s2= roman.substring(j,j+1);
String s3= roman.substring(j-1,j);
int b=getVal(s2);
int c=getVal(s3);
if(b>c)
{
countB+=c;
}
}
count=countA-(2*countB);
return count;
}
void disp()
{
int result=count();
System.out.println("Integer equivalent of "+roman+" = " +result);
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter Roman Symbol:");
String s = keyboard.nextLine();
RomInt();
}
}
Roman numerals/Decode Example:
class Roman {
private static int decodeSingle(char letter) {
switch (letter) {
case 'M':
return 1000;
case 'D':
return 500;
case 'C':
return 100;
case 'L':
return 50;
case 'X':
return 10;
case 'V':
return 5;
case 'I':
return 1;
default:
return 0;
}
}
public static int decode(String roman) {
int result = 0;
String uRoman = roman.toUpperCase(); //case-insensitive
for (int i = 0; i < uRoman.length() - 1; i++) {//loop over all but the last character
if (decodeSingle(uRoman.charAt(i)) < decodeSingle(uRoman.charAt(i + 1))) {
result -= decodeSingle(uRoman.charAt(i));
} else {
result += decodeSingle(uRoman.charAt(i));
}
}
result += decodeSingle(uRoman.charAt(uRoman.length() - 1));
return result;
}
public static void main(String[] args) {
System.out.println(decode("MCMXC")); //1990
System.out.println(decode("MMVIII")); //2008
System.out.println(decode("MDCLXVI")); //1666
}
}
Use enum, for easy and simple solution. At first define the decimal equivalent weight at roman.
enum Roman{
i(1),iv(4),v(5), ix(9), x(10);
int weight;
private Roman(int weight) {
this.weight = weight;
}
};
This is the method to convert decimal to roman String.
static String decToRoman(int dec){
String roman="";
Roman[] values=Roman.values();
for (int i = values.length-1; i>=0; i--) {
while(dec>=values[i].weight){
roman+=values[i];
dec=dec-values[i].weight;
}
}
return roman;
}
You can try using a Hashmap to store the roman numerals and equivalent arabic numerals.
HashMap test = new HashMap();
test.add("I",1);
test.add("V",5);
test.add("X",10);
test.add("L",50);
test.add("C",100);
test.add("D",500);
test.add("M",1000);
//This would insert all the roman numerals as keys and their respective arabic numbers as
values.
To retrieve respective arabic numeral one the input of the user, you can use following peice of code:
Scanner sc = new Scanner(System.in);
System.out.println(one.get(sc.next().toUpperCase()));
//This would print the respective value of the selected key.This occurs in O(1) time.
Secondly,
If you only have these set of roman numerals, then you can go for simple switch case statement.
switch(sc.next().toUpperCase())
{
case 'I' :
System.out.println("1");
break;
case 'V'
System.out.println("5");
break;
.
.
.
& so on
}
Hope this helps.
How about this:
public static int convertFromRoman(String roman) {
Map<String, Integer> v = new HashMap<String, Integer>();
v.put("IV", 4);
v.put("IX", 9);
v.put("XL", 40);
v.put("CD", 400);
v.put("CM", 900);
v.put("C", 100);
v.put("M", 1000);
v.put("I", 1);
v.put("V", 5);
v.put("X", 10);
v.put("L", 50);
v.put("D", 500);
int result = 0;
for (String s : v.keySet()) {
result += countOccurrences(roman, s) * v.get(s);
roman = roman.replaceAll(s, "");
}
return result;
}
public static int countOccurrences(String main, String sub) {
return (main.length() - main.replace(sub, "").length()) / sub.length();
}
Not sure I've got all possible combinations as I'm not an expert in roman numbers. Just make sure that the once where you substract come first in the map.
Your compilation issue can be resolved with below code. But surely its not optimized one:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter Roman Symbol:");
String s = keyboard.nextLine();
RomInt temp = new RomInt();
temp.getVal(s);
temp.assign(s);
temp.disp();
}
I'm writing a calculator in java that has memory to store variables. It shows the list of variables properly, adds and subtracts, and defines variables, but whenever I try to do something like a = b + 1, it treats b as if it is 0, giving 'a' a value of 1.
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
ArrayList<String> variables = new ArrayList<>();
while(scan.hasNextLine())
{
String line = scan.nextLine();
String[] tokens = line.split(" ");
if(!Character.isDigit(tokens[0].charAt(0)) && !line.equals("clear") && !line.equals("var"))
{
int value = 0;
for(int i=0; i<tokens.length; i++)
{
if(tokens.length==1)
{
if(variables.contains(tokens[0]))
{
printAnswer(values.get(variables.indexOf(tokens[0])));
}
else if(!line.equals("quit"))
{
int width = 4 + tokens[0].length();
System.out.printf("%" + width + "s is not defined\n", tokens[0]);
}
break;
}
if(tokens.length==3)
{
value = Integer.parseInt(tokens[2]);
printAnswer(value);
if(variables.contains(tokens[0]))
{
values.set(variables.indexOf(tokens[0]), value);
variables.set(variables.indexOf(tokens[0]), tokens[0]);
}
else
{
values.add(value);
variables.add(tokens[0]);
}
break;
}
else if(tokens[i].charAt(0) == '+')
{
value = addition(tokens, value, variables, values);
printAnswer(value);
if(variables.contains(tokens[0]))
{
values.set(variables.indexOf(tokens[0]), value);
}
else
{
values.add(value);
variables.add(tokens[0]);
}
break;
}
else if(tokens[i].charAt(0) == '-')
{
value = subtraction(tokens, value);
printAnswer(value);
if(variables.contains(tokens[0]))
{
values.set(variables.indexOf(tokens[0]), value);
}
else
{
values.add(value);
variables.add(tokens[0]);
}
break;
}
else if(i==tokens.length-1)
{
System.out.println("No operation");
break;
}
}
}
if(Character.isDigit(tokens[0].charAt(0)))
{
int value = 0;
for(int i=0; i<tokens.length; i++)
{
if(tokens.length==1)
{
value = Integer.parseInt(tokens[0]);
printAnswer(value);
break;
}
else if(tokens[i].charAt(0) == '+')
{
value = addition(tokens, value, variables, values);
printAnswer(value);
}
else if(tokens[i].charAt(0) == '-')
{
value = subtraction(tokens, value);
printAnswer(value);
}
}
}
if(line.equals("clear"))
{
clear(variables, values);
}
if(line.equals("var"))
{
variableList(variables, values);
}
else if(line.equals("quit"))
{
System.exit(0);
}
}
}
public static int addition(String[] a, int b, ArrayList<String> c, ArrayList<Integer> d)
{
for(String item : a)
{
int i=0;
if(Character.isDigit(item.charAt(0)))
{
int val = Integer.parseInt(item);
b = b + val;
i++;
}
else if(Character.isLetter(item.charAt(0)) && i!=0)
{
int val = d.get(c.indexOf(item));
b = b + val;
}
}
return b;
}
public static int subtraction(String[] a, int b)
{
int i=0;
for(String item : a)
{
if(Character.isDigit(item.charAt(0)))
{
int val = Integer.parseInt(item);
if(i==0)
{
b = b + val;
i++;
}
else
{
b = b - val;
}
}
}
return b;
}
public static void clear(ArrayList<String> a, ArrayList<Integer> b)
{
a.clear();
b.clear();
}
public static void variableList(ArrayList<String> a, ArrayList<Integer> b)
{
for(int i=0; i<a.size(); i++)
{
int width = 4 + a.get(i).length();
System.out.printf("%" + width + "s: %d\n", a.get(i), b.get(i));
}
}
public static void printAnswer(int a)
{
int width = 3;
Integer valueToString = a;
String valueString = valueToString.toString();
for(int j=0; j<=valueString.length(); j++)
{
width++;
}
System.out.printf("%" + width + "d\n",a);
}
Main problem is within the addition method
I could explain to you why your program is setting 'a' to 1 when you enter the command "a + b + 1", but this will not really help you. You need to take a hard look at your code, step through it a bit, and see if you can structure it more logically, because right now it is just a bunch of statements strung together that do not actually define any meaningful behavior. Writing comments and using more meaningful variable names helps a lot.
A few notes on this:
Never in your loop do you check for the '=' sign. This means that the commands:
"a = b + 1"
"a + b + 1"
...get processed exactly the same way, assigning a value of 1 to 'a'
Your addition and subtraction methods do not account for position whatsoever. This means that the first operator encountered is applied to all tokens in the string. I.e:
"a c + d - 3 - - x 5"
...is exactly the same as:
"a c + d + + + 3 5 x"
(Note that both of these strings are utter nonsense)
Try using a debugger to step through your code and see what it is doing. That will help you a lot.
I made this program that evaluates a postfix expression.
It works fine if only single digit numbers are used.
My problem is how do I push multiple-digit numbers if input has spaces?
ex. input: 23+34*- output is -7
but if I input: 23 5 + output is only 3(which is the digit before the space)
it should have an output of 28
my codes:
public class Node2
{
public long num;
Node2 next;
Node2(long el, Node2 nx){
num = el;
next = nx;
}
}
class stackOps2
{
Node2 top;
stackOps2(){
top = null;
}
public void push(double el){
top = new Node2(el,top);
}
public double pop(){
double temp = top.num;
top = top.next;
return temp;
}
public boolean isEmpty(){
return top == null;
}
}
public class ITP {
static stackOps2 so = new stackOps2();
public static final String operator = "+-*/^";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the infix:");
String s = input.next();
String output;
InToPost theTrans = new InToPost(s);
output = theTrans.doTrans();
System.out.println("Postfix is " + output + '\n');
System.out.println(output+" is evaluated as: "+evaluate(output));
}
public static double evaluate(String value)throws NumberFormatException{
for(int i=0;i<value.length();i++){
char val = value.charAt(i);
if(Character.isDigit(value.charAt(i))){
String v = ""+val;
so.push(Integer.parseInt(v));
}
else if(isOperator(val)){
double rand1=so.pop();
double rand2=so.pop();
double answer ;
switch(val){
case '+': answer = rand2 + rand1;break;
case '-': answer = rand2 - rand1;break;
case '*': answer = rand2 * rand1;break;
case '^': answer = Math.pow(rand2, rand1);break;
default : answer = rand2 / rand1;break;
}
so.push(answer);
}
else if(so.isEmpty()){
throw new NumberFormatException("Stack is empty");
}
}
return so.pop();
}
public static boolean isOperator(char ch){
String s = ""+ch;
return operator.contains(s);
}
}
This is a small, self-contained example that does all the string parsing and evaluation. The only difference from your example is that it accepts the whole string at once instead of using a Scanner. Note the use of Integer.parseInt -- that's missing in your example. I think you can easily extend this for your needs.
#SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args) {
final String in = "5 9 + 2 * 6 5 * +";
final Deque<Object> s = new LinkedList();
for (String t : in.split(" ")) {
if (t.equals("+")) s.push((Integer)s.pop() + (Integer)s.pop());
else if (t.equals("*")) s.push((Integer)s.pop() * (Integer)s.pop());
else s.push(Integer.parseInt(t));
}
System.out.println(s.pop());
}