Click here to Skip to main content
15,899,754 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to create any simple compiler using java, that takes input only numbers, addition(+) and subtraction(-) , and perform operations.

What I have tried:

Java
import java.io.InputStream;
import java.io.IOException;

public class Comp {
	private static char firstdigit;
	private static char seconddigit;
	private static int sum;
	
	public static void main(String[] args) throws IOException {

		firstdigit = (char) System.in.read();
		seconddigit = (char) System.in.read();
		
		try {
			expresion();
		}
		catch (ParseException e) {
			System.err.println(e.getMessage());
		}
	}

		private static void expresion()  throws IOException, ParseException{
			System.out.println(firstdigit + " "+ seconddigit );	
			System.out.println(sum);	
		}
		
		
		private static int sum() {
			sum =(firstdigit + seconddigit);
			return sum;
		}


		private static char seconddigit() throws IOException, ParseException{
			if(!Character.isDigit(seconddigit)) {
				throw new ParseException("Integer expected..");
			}
				return seconddigit;
			}
		private static char firstdigit() throws IOException, ParseException{
			if(!Character.isDigit(firstdigit)) {
				throw new ParseException("Integer expected..");
		}
			return firstdigit;

		}
		static class ParseException extends Exception {
			ParseException(String reason){
				super(reason);
			}
		}
}
Posted
Updated 11-Jan-21 20:46pm
v2
Comments
OriginalGriff 12-Jan-21 2:31am    
And?
What does it do that you didn't expect, or not do that you did?
What have you tried to do to find out why?
Are there any error messages, and if so, where and when? What did you do to make them happen?

This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with.
Use the "Improve question" widget to edit your question and provide better information.

1 solution

This should emend your code
Java
private static void expresion()  throws IOException, ParseException{
  int a = firstdigit - '0';
  int b = seconddigit - '0';
  sum = (a+b);
  System.out.println(firstdigit + " "+ seconddigit );
  System.out.println(sum);
}


Anyway I warmly encourage your to
  • Don't mix chars and ints (that is directly gather integers from user input).
  • Don't use the same name for methods and variables (that's rather confusing).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900