How can i calculate a string mix of operators and operands - java

It is giving error when operator is encountered in between.I know operator cannot be into
converted int or other format.I am using operator for calculation by reading byte codes and passing it to enum defined.But as my string having operators so i am having prob in handling these.Please help me on this.
----My Inputs is 1 + 2
----Expected Output-- 1 + 2=3---
Error in line ---- b = Integer.parseInt(st.nextToken());
--Error in during exceution-----
Enter the series--
1 + 2
no of tokens:3
yo
1
go
1
available
byte info:10
.......
Exception in thread "main" java.lang.NumberFormatException: For input string: "+"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:484)
at java.lang.Integer.parseInt(Integer.java:527)
at Abc.main(Abc.java:42)
I am not able to rectify it. Below is my code
import java.io.*;
import java.util.StringTokenizer;
public class Abc{
public static void main(String[] args) throws Exception
{
System.out.println("Hello World");
System.out.println("Enter the series");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
int a=0;
int b=0;
System.out.println(s);
while ((br.readLine()) != null)
{
StringTokenizer st=new StringTokenizer(s);
while (st.hasMoreTokens())
{
int i=0;
i=st.countTokens();
System.out.println("no of tokens:"+i);
String token = st.nextToken();
System.out.println("yo");
System.out.println(token);
System.out.println("go");
a=Integer.parseInt(token);
System.out.println(a);
if (st.hasMoreTokens()) // before consuming another token, make sure
{
System.out.println("available");
byte b1=(byte)br.read();
System.out.println("byte info:"+b1);
// there's one available
if (st.hasMoreTokens()){
System.out.println(".......");
b = Integer.parseInt(st.nextToken());
System.out.println("///////");
System.out.println(a);
System.out.println("reached");
System.out.println(b);
}
if (b1==43)
{
System.out.println("go");
int foo = Integer.parseInt(calculate(operator.ADDITION, a, b));
}
else if (b1==45)
{
int foo = Integer.parseInt(calculate(operator.SUBTRACTION, a, b));
}
else if (b1==42)
{
int foo = Integer.parseInt(calculate(operator.MULTIPLY, a, b));
}
else if (b1==47)
{
int foo = Integer.parseInt(calculate(operator.DIVIDE, a, b));
}
}
}
}
}
public enum operator
{
ADDITION("+") {
public int apply(int x1, int x2) {
return x1 + x2;
}
},
SUBTRACTION("-") {
public int apply(int x1, int x2) {
return x1 - x2;
}
},
MULTIPLY("*") {
public int apply(int x1, int x2) {
return x1 * x2;
}
},
DIVIDE("/") {
public int apply(int x1, int x2) {
return x1 / x2;
}
};
// You'd include other operators too...
private final String text;
private operator(String text) {
this.text = text;
}
// Yes, enums *can* have abstract methods. This code compiles...
public abstract int apply(int x1, int x2);
public String toString() {
return text;
}
}
public static String calculate(operator op, int x1, int x2)
{
return String.valueOf(op.apply(x1, x2));
}
}

Couple of Issues:
You are just asking for input in string s but not processing it, hence rmeove that s variable and wherever its referenced.
Define a String line; variable Modify and update your while loop as:
while ((line = br.readLine()) != null)
You dont need this line byte b1=(byte)br.read(); as it will just have line feed i.e. enter key that you pressed when entering the line
Your while loop should be:
declare operand1, operand2, count as int
declare operator as char
while tokenizer has more tokens
do
optional validate String with token count as 3 with middle token as operator.
read token
if count == 0 then operand1 = int(token)
else if count == 1 then operator = char(token)
else operand2 = int(token)
done

If you can do it, it would be much easier to use Java's ScriptEngine class to evaluate a user given string, like so:
ScriptEngineManager engine = new ScriptEngineManager();
ScriptEngine javaScript = engine.getEngineByName("JavaScript");
System.out.print("Please enter a mathematical operation: ");
String op = new Scanner(System.in).nextLine();
try {
Object a = javaScript.eval(op);
System.out.println("Result: " + a.toString());
} catch (ScriptException ex) {
System.out.println("Error in the input!");
}
I've tested it an it works fine.

Related

Nesting of Methods Compilation Error?

I am writing a java program to compare two numbers using nesting methods but receiving the error`
class HelloWorld {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter First Number");
int X = s.nextInt();
System.out.println("Enter Second Number");
int y = s.nextInt();
Nesting nest = new Nesting(int, int);
nest.disp();
}
}
class Nesting {
int m, n;
Nesting(int X, int y) {
m = X;
n = y;
}
int largest() {
if (m > n) {
return m;
} else {
return n;
}
}
void disp() {
int ans = largest();
System.out.println("My Result is " + ans);
}
}
While compiling receiving the following error
Line: 11
'.class' expected
Line: 11
'.class' expected
When you call a method or constructor, you should not pass the type, instead you have to pass the values, you have to change :
Nesting nest = new Nesting(int, int);
To this :
Nesting nest = new Nesting(X, y);

Intro to Java Parrot Program

We have an assignment for an intro to java class im taking that requires us to program a parrot.
Essentially we have an output
" What do you want to say?
The User types in his input
" Blah Blah Blah"
And then the parrot is supposed to repeat
"Blah Blah Blah"
I have achieved this.
package parrot;
import java.util.Scanner;
public class Parrot {
public static void main(String[] args) {
System.out.print(" What do you want to say? ");
Scanner input = new Scanner(System.in);
String Parrot = input.nextLine();
System.out.println("Paulie Says: " + Parrot);
}
}
This gives me the exact results I need, but then I read in the lab instructions it wants us to do it in 2 files?
 Add 2 files to the project: Parrot.java and ParrotTest.java
 In Parrot.java do the following:
 Create a public class called Parrot
 Inside the class create a public method called speak. The method speak has one String parameter named word and no return value (i.e. return type void) The method header looks like this: public void speak(String word)
 The parrot repeats anything he is told. We implement this behavior by printing the word passed as an argument
And what I think im being asked to do is call it from another file? Can someone explain to me how to do this as im not exactly sure whats going on?
Yes your program performs the given task, but not in the manner you are asked. Your main method should be executed from inside the ParrotTest.java file. In this file (ParrotTest.java), you will need to create an instance of a class (you can call it Parrot) by calling a constructor.
Inside your Parrot.java you will create a method called 'speak' which accepts String word.
Going back to the main method: Here you will ask for user input, capture the input in a String 'word' and pass it as an argument to the speak method you created. Once your method has this argument, you can print it's content out to the console.
Parrot would have the following
public class Parrot
{
public void speak( String word )
{
System.out.printf("%s", word);
}
}
Parrot Test would have the following
import java.util.Scanner;
public class ParrotTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("What would you like to say to the parrot?: ");
String words = input.nextLine();
Parrot myParrot = new Parrot();
myParrot.speak(words);
}
}
I don't know if you have to use scanner but this is how i would do it.BTW this code works with Jcreator.
public static void main(String[] args) {
String say = IO.getString("Say something") // This is asking the user to say something
System.out.print(name);
}
If you want it to loop 10 times then
then do this
public static void main(String[] args) {
String say = IO.getString("Say something"); // This is asking the user to say something
int count = 10; // it will loop 10 times
while (count >= 10) {
System.out.print(name);
say = IO.getString("Say something");
count++;
}
By the way if you don't have IO class you can you this. Just copy this code into jcreator and say it where you save all your codes.
/**
* #(#)IO.java
* This file is designed to allow HCRHS students to collect information from the
* user during Computer Science 1 and Computer Science 2.
* #author Mr. Twisler, Mr. Gaylord
* #version 2.01 2014/12/21
* *Updated fix to let \t work for all input/output
* *Added input methods to allow for console input
* *Allowed all get methods to work with all objects
* *Updated format methods to use String.format()
*/
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
public class IO {
// Shows a message in a popup window
public static void showMsg(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
JOptionPane.showMessageDialog(null, text, "HCRHS",
JOptionPane.PLAIN_MESSAGE);
}
/*********************************User Input Methods***************************
* All user input methods get the data type mentioned in their name and return
* a default value if the user enters an incorrect responce.
******************************************************************************/
// Returns String typed by user, default value is ""
public static String getString(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
String ans = JOptionPane.showInputDialog(null, text, "HCRHS",
JOptionPane.QUESTION_MESSAGE);
if(ans == null) {
return "";
}
return ans;
}
public static String nextString() {
Scanner scan = new Scanner(System.in);
String ans = scan.nextLine();
scan.close();
if(ans == null) {
return "";
}
return ans;
}
// Returns int typed by the user, default value is 0
public static int getInt(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
try {
return Integer.parseInt(JOptionPane.showInputDialog(null, text,
"HCRHS", JOptionPane.QUESTION_MESSAGE));
} catch (NumberFormatException e) {
//System.out.println("Not a valid int");
return 0;
}
}
public static int nextInt() {
Scanner scan = new Scanner(System.in);
int ans;
try {
ans = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
//System.out.println("Not a valid int");
ans = 0;
}
scan.close();
return ans;
}
// Returns double typed by the user, default value is 0.0
public static double getDouble(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
try {
return Double.parseDouble(JOptionPane.showInputDialog(null, text,
"HCRHS", JOptionPane.QUESTION_MESSAGE));
} catch (NumberFormatException|NullPointerException e) {
//System.out.println("Not a valid double");
return 0;
}
}
public static double nextDouble() {
Scanner scan = new Scanner(System.in);
double ans;
try {
ans = Double.parseDouble(scan.nextLine());
} catch (NumberFormatException|NullPointerException e) {
//System.out.println("Not a valid double");
ans = 0;
}
scan.close();
return ans;
}
// Returns char typed by the user, default value is ' '
public static char getChar(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
try {
return JOptionPane.showInputDialog(null, text, "HCRHS",
JOptionPane.QUESTION_MESSAGE).charAt(0);
} catch (NullPointerException|StringIndexOutOfBoundsException e) {
//System.out.println("Not a valid char");
return ' ';
}
}
public static char nextChar() {
Scanner scan = new Scanner(System.in);
char ans;
try {
ans = scan.nextLine().charAt(0);
} catch (NullPointerException|StringIndexOutOfBoundsException e) {
//System.out.println("Not a valid char");
ans = ' ';
}
scan.close();
return ans;
}
// Returns boolean typed by the user, default value is false
public static boolean getBoolean(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
int n = JOptionPane.showOptionDialog(null, text, "HCRHS",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, new Object[]{"True", "False"}, 1);
return (n == 0);
}
public static boolean nextBoolean() {
Scanner scan = new Scanner(System.in);
String bool = scan.nextLine().toLowerCase();
scan.close();
if (bool.equals("true") || bool.equals("t") || bool.equals("1")) {
return true;
} else {
return false;
}
}
/******************************Formatting Methods******************************
* Format is overloaded to accept Strings/int/double/char/boolean
******************************************************************************/
public static String format(char just, int maxWidth, String s) {
if (just == 'l' || just == 'L') {
return String.format("%-" + maxWidth + "." + maxWidth + "s", s);
} else if (just == 'r' || just == 'R') {
return String.format("%" + maxWidth + "." + maxWidth + "s", s);
} else if (just == 'c' || just == 'C') {
return format('l', maxWidth, format('r',
(((maxWidth - s.length()) / 2) + s.length()), s));
} else {
return s;
}
}
public static String format(char just, int maxWidth, int i) {
return format(just, maxWidth, String.format("%d", i));
}
public static String format(char just, int maxWidth, double d, int dec) {
return format(just, maxWidth, String.format("%,." + dec + "f", d));
}
public static String format(char just, int maxWidth, char c) {
return format(just, maxWidth, String.format("%c", c));
}
public static String format(char just, int maxWidth, boolean b) {
return format(just, maxWidth, String.format("%b", b));
}
/*********************************Fancy Expirmental Methods********************/
public static String choice(String... options) {
String s = (String)JOptionPane.showInputDialog(null,
"Pick one of the following", "HCRHS",
JOptionPane.PLAIN_MESSAGE, null, options, null);
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
return s;
}
return "";
}
public static String readFile(String fileName) {
String ans ="";
try {
Scanner scanner = new Scanner(new File(fileName));
scanner.useDelimiter(System.getProperty("line.separator"));
while (scanner.hasNext()) {
ans += scanner.next()+"\n";
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return ans;
}
public static void writeFile(String fileName, String data) {
try {
FileWriter fw = new FileWriter(fileName, true);
fw.write(data);
fw.close();
} catch(java.io.IOException e) {
e.printStackTrace();
}
}
}

Math Expression Parser

I found the code of Math Expression Parser from Dreamincode Forum.
My question is, on that code I think everything is going all right, but when I had a testcase '(2(3+5)' , that was valid, whereas this test case is completely wrong
but if I give the test case '(3+5)2)' it was detect as non valid input.
Anyone knows why this is happening?
//enum for Operator "objects"
import java.util.*;
public enum Operator {
ADD("+", 1)
{
double doCalc(double d1, double d2) {
return d1+d2;
}
},
SUBTRACT("-",1)
{
double doCalc(double d1, double d2) {
return d1-d2;
}
},
MULTIPLY("*", 2)
{
double doCalc(double d1, double d2) {
return d1*d2;
}
},
DIVIDE("/",2)
{
double doCalc(double d1, double d2) {
return d1/d2;
}
},
STARTBRACE("(", 0)
{
double doCalc(double d1, double d2) {
return 0;
}
},
ENDBRACE(")",0)
{
double doCalc(double d1, double d2) {
return 0;
}
},
EXP("^", 3)
{
double doCalc(double d1, double d2) {
return Math.pow(d1,d2);
}
};
private String operator;
private int precedence;
private Operator(String operator, int precedence) {
this.operator = operator;
this.precedence = precedence;
}
public int getPrecedenceLevel() {
return precedence;
}
public String getSymbol() {
return operator;
}
public static boolean isOperator(String s) {
for(Operator op : Operator.values()) { //iterate through enum values
if (op.getSymbol().equals(s))
return true;
}
return false;
}
public static Operator getOperator(String s)
throws InvalidOperatorException {
for(Operator op : Operator.values()) { //iterate through enum values
if (op.getSymbol().equals(s))
return op;
}
throw new InvalidOperatorException(s + " Is not a valid operator!");
}
public boolean isStartBrace() {
return (operator.equals("("));
}
//overriding calculation provided by each enum part
abstract double doCalc(double d1, double d2);
}
//error to be thrown/caught in ProjectOne.java
class InvalidOperatorException extends Exception {
public InvalidOperatorException() {
}
public InvalidOperatorException(String s) {
super(s);
}
}
//reading in a string at doing the parsing/arithmetic
public static void main (String[] args) {
String input = "";
//get input
System.out.print("Enter an infix exp<b></b>ression: ");
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
try {
input = in.readLine();
}
catch (IOException e)
{
System.out.println("Error getting input!");
}
doCalculate(input);
}
// Input: user entered string
// Output: Display of answer
public static void doCalculate(String equation) {
//our stacks for storage/temp variables
Stack<Operator> operatorStack;
Stack<Double> operandStack;
double valOne, valTwo, newVal;
Operator temp;
//initalize
StringTokenizer tokenizer = new StringTokenizer(equation, " +-*/()^", true);
String token = "";
operandStack = new Stack();
operatorStack = new Stack();
try {
while(tokenizer.hasMoreTokens()){ //run through the string
token = tokenizer.nextToken();
if (token.equals(" ")) { //handles spaces, goes back up top
continue;
}
else if (!Operator.isOperator(token)){ //number check
operandStack.push(Double.parseDouble(token));
}
else if (token.equals("(")) {
operatorStack.push(Operator.getOperator(token));
}
else if (token.equals(")")) { //process until matching paraentheses is found
while (!((temp = operatorStack.pop()).isStartBrace())) {
valTwo = operandStack.pop();
valOne = operandStack.pop();
newVal = temp.doCalc(valOne, valTwo);
operandStack.push(newVal);
}
}
else { //other operators
while (true) { //infinite loop, check for stack empty/top of stack '('/op precedence
if ((operatorStack.empty()) || (operatorStack.peek().isStartBrace()) ||
(operatorStack.peek().getPrecedenceLevel() < Operator.getOperator(token).getPrecedenceLevel())) {
operatorStack.push(Operator.getOperator(token));
break; //exit inner loop
}
temp = operatorStack.pop();
valTwo = operandStack.pop();
valOne = operandStack.pop();
//calculate and push
newVal = temp.doCalc(valOne, valTwo);
operandStack.push(newVal);
}
}
}
}
catch (InvalidOperatorException e) {
System.out.println("Invalid operator found!");
}
//calculate any remaining items (ex. equations with no outer paraentheses)
while(!operatorStack.isEmpty()) {
temp = operatorStack.pop();
valTwo = operandStack.pop();
valOne = operandStack.pop();
newVal = temp.doCalc(valOne, valTwo);
operandStack.push(newVal);
}
//print final answer
System.out.println("Answer is: " + operandStack.pop());
}
This calculator does not work with implicit multiplication. you can use:
2((2+2)+1)
And see that it gives the wrong answer as opposed to:
2*((2+2)+1)
The false-positive expression you've used does not pass with explicit multiplication.
A quick for-the-lazy fix to add implicit multiplication would be something of that sort:
public static void doCalculate(String equation) {
// make it explicit:
System.out.println("Got:" + equation);
Pattern pattern = Pattern.compile("([0-9]+|[a-z\\)])(?=[0-9]+|[a-z\\(])");
Matcher m = pattern.matcher(equation);
System.out.println("Made it: "+ (equation = m.replaceAll("$1*")));
//our stacks for storage/temp variables
Stack<Operator> operatorStack;
Stack<Double> operandStack;
double valOne, valTwo, newVal;
Operator temp;
This is an attempt to capture implicit multiplication using regex and make it explicit.
It fixes all cases we've come up with.

Java program grading

I've been working on this program for hours and I can't figure out how to get the program to actually print the grades from the scores Text file
public class Assign7{
private double finalScore;
private double private_quiz1;
private double private_quiz2;
private double private_midTerm;
private double private_final;
private final char grade;
public Assign7(double finalScore){
private_quiz1 = 1.25;
private_quiz2 = 1.25;
private_midTerm = 0.25;
private_final = 0.50;
if (finalScore >= 90) {
grade = 'A';
} else if (finalScore >= 80) {
grade = 'B';
} else if (finalScore >= 70) {
grade = 'C';
} else if (finalScore>= 60) {
grade = 'D';
} else {
grade = 'F';
}
}
public String toString(){
return finalScore+":"+private_quiz1+":"+private_quiz2+":"+private_midTerm+":"+private_final;
}
}
this code compiles as well as this one
import java.util.*;
import java.io.*;
public class Assign7Test{
public static void main(String[] args)throws Exception{
int q1,q2;
int m = 0;
int f = 0;
int Record ;
String name;
Scanner myIn = new Scanner( new File("scores.txt") );
System.out.println( myIn.nextLine() +" avg "+"letter");
while( myIn.hasNext() ){
name = myIn.next();
q1 = myIn.nextInt();
q2 = myIn.nextInt();
m = myIn.nextInt();
f = myIn.nextInt();
Record myR = new Record( name, q1,q2,m,f);
System.out.println(myR);
}
}
public static class Record {
public Record() {
}
public Record(String name, int q1, int q2, int m, int f)
{
}
}
}
once a compile the code i get this which dosent exactly compute the numbers I have in the scores.txt
Name quiz1 quiz2 midterm final avg letter
Assign7Test$Record#4bcc946b
Assign7Test$Record#642423
Exception in thread "main" java.until.InputMismatchException
at java.until.Scanner.throwFor(Unknown Source)
at java.until.Scanner.next(Unknown Source)
at java.until.Scanner.nextInt(Unknown Source)
at java.until.Scanner.nextInt(Unknown Source)
at Assign7Test.main(Assign7Test.java:25)
Exception aside, you actually are printing objects of type Record. What you would need to do is override toString() to provide a decent representation of your object.
#Override
public String toString() {
return "Something meaningful about your Record object.";
}
I also note that you're advancing the Scanner by use of nextLine() in System.out.println('...'). You may want to comment that part out of your code.
The reason you are getting this error is because of the fact that you are expecting an integer, but the next thing your scanner reads is not a number.
Also, put this in your toString of your record to stop printing out addresses.
i.e.
public static class Record {
public Record() {
}
public Record(String name, int q1, int q2, int m, int f)
{
}
public String toString(){}//print out stuff here.
}
change your Record to something like this
public static class Record {
String name;
int q1;
int q2;
int m;
int f;
public Record() {}
public Record(String name, int q1, int q2, int m, int f) {
// here you save the given arguments localy in the Record.
this.name = name;
this.q1 = q1;
this.q2 = q2;
this.m = m;
this.f = f;
}
#Override
public String toString(){
//here you write out the localy saves variables.
//this function is called when you write System.out.println(myRecordInstance);
System.out.println(name + ":" + q1 + ":" + q2 + ":" + m + ":" + f);
}
}
What it does: you have to save the argments by creating the Record.
Additional you have to override the toString method if you want to use System.out.println(myRecordInstance); instead you could write an other function returning a String in your Record and print out the return values of this function like System.out.println(myRecordInstace.writeMe()); Then you ne to add the function to the record.
public String writeMe(){
System.out.println(name + ":" + q1 + ":" + q2 + ":" + m + ":" + f);
}

Getting a function to return two integers

I am writing a function and I want it two return two integers as results. However, I cannot get it to do this. Could someone help me? Here is my best shot
public static int calc (int s, int b, int c, int d, int g)
{
if (s==g)
return s;
else if (s+b==g)
return s && b;
else if (s + c==g)
return s && c;
else if (s+d==g)
return s && d;
else
System.out.println("No Answer");
}
You could have the method return an array of int:
public static int[] calc (int s, int b, int c, int d, int g)
Make a "pair" class and return it.
public class Pair<T,Y>
{
public T first;
public Y second;
public Pair(T f, Y s)
{
first = f;
second = s;
}
}
Make a small inner class that has two integers.
private static class TwoNumbers {
private Integer a;
private Integer b;
private TwoNumbers(Integer a, Integer b) {
this.a = a;
this.b = b;
}
}
You create a instance of the class and return that instead.
For this specific problem, since the answer always returns s:
....
return s;
....
return s && b;
....
return s && c;
....
return s && d;
....
you could just return the 2nd value. I use 0 to indicate "just s" since the first case (if (s==g)) could be thought of as if (s+0==g). Use a different sentinel value than 0 for this, if necessary.
public static int calc (int s, int b, int c, int d, int g)
{
if (s==g)
return 0;
else if (s+b==g)
return b;
else if (s+c==g)
return c;
else if (s+d==g)
return d;
else {
// System.out.println("No Answer");
// Probably better to throw or return a sentinel value of
// some type rather than print to screen. Which way
// probably depends on whether "no answer" is a normal
// possible condition.
throw new IndexOutOfBoundsException("No Answer");
}
}
If no exception is thrown, then s is always the first result:
try {
int result1 = s;
int result2 = calc(s, b, c, d, g);
} catch (IndexOutOfBoundsException ex) {
System.out.println("No Answer");
}
package calcultor;
import java.util.*;
import java.util.Scanner;
public class Calcultor{
public static void main(String args[]){
input();
}
public static void input(){
Scanner FirstNum = new Scanner(System.in);
System.out.print("Enter the First number: ");
int num01 = FirstNum.nextInt();
Scanner secondNum = new Scanner(System.in);
System.out.print("Enter the second number: ");
int num02 = secondNum.nextInt();
output(num01, num02);
}
public static void output(int x ,int y){
int sum = x + y;
System.out.println("Sum of Two Number: "+sum);
//return sum;
}
}
why do you want to do this? and if you have some need like this can't you change your return type to string, because in case of string you can have separator between two values which will help you in extracting values.... say 10&30 ,
I agree this is a wrong way of solving...i assumed that there is limitation of sticking to primitive datatype

Categories