Nesting of Methods Compilation Error? - java

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);

Related

Evaluate a prefix expression using stacks

I have to evaluate a prefix expression using stacks, I did it but I don't understand why the code doesn't work properly, it marks 2 bugs when I compile the code, they are:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at evaluationprefix.EvaluationPreFix.EvaluationPrefix(EvaluationPreFix.java:56)
at evaluationprefix.EvaluationPreFix.main(EvaluationPreFix.java:25)
public class EvaluationPreFix {
public static void main(String[] args) {
Stack st = new Stack();
Scanner sc = new Scanner(System.in);
System.out.println("enter the size of expression");
int t = sc.nextInt();
sc.nextLine();
for (int i = 0; i < t; i++) {
System.out.println("enter an element");
String element = sc.nextLine();
st.push(element);
}
int r = EvaluationPrefix(st); //marks an Error here
System.out.println("Result: " + r);
}
public static int EvaluationPrefix(Stack st) {
Stack st2 = new Stack();
while (!st.isEmpty()) {
Object e = st.pop();
if (e.equals('+')) {
st2.push((Integer) st2.pop() + (Integer) st2.pop());
} else if (e.equals('-')) {
st2.push((Integer) st2.pop() - (Integer) st2.pop());
} else if (e.equals('*')) {
st2.push((Integer) st2.pop() * (Integer) st2.pop());
} else if (e.equals('/')) {
st2.push((Integer) st2.pop() / (Integer) st2.pop());
} else {
st2.push(e);
}
}
return (Integer) st2.pop();//marks an error here
}
}
Changes made:
In the main method, changed the stack, st, to String type.
In the EvaluationPrefix method,
changed the parameter stack to String type.
changed the stack, st2, to Integer type.
changed the arithmetical operators within equals to String.
Here you go,
public class EvaluationPreFix {
public static void main(String[] args) {
//1. parameterized with String
Stack<String> st = new Stack();
Scanner sc = new Scanner(System.in);
System.out.println("enter the size of expression");
int t = sc.nextInt();
sc.nextLine();
for (int i = 0; i < t; i++) {
System.out.println("enter an element");
String element = sc.nextLine();
st.push(element);
}
int r = EvaluationPrefix(st); //marks an Error here
System.out.println("Result: " + r);
}
//2. parameterized with String
public static int EvaluationPrefix(Stack<String> st) {
//3. parameterized with Integer
Stack<Integer> st2 = new Stack();
while (!st.isEmpty()) {
String e = st.pop();
//4. arithmetic sign comparison to string instead
//of character
if (e.equals("+")) {
st2.push(st2.pop() + st2.pop());
} else if (e.equals("-")) {
st2.push(st2.pop() - st2.pop());
} else if (e.equals("*")) {
st2.push(st2.pop() * st2.pop());
} else if (e.equals("/")) {
st2.push(st2.pop() / st2.pop());
} else {
st2.push(Integer.valueOf(e));
}
}
return st2.pop();
}
}
Assuming we are talking about java.util.stack - this is just a Collection storing what you push into it, and you are using it as raw type.
Stack st = new Stack();
That means you can push objects of any type onto this stack. It seems that you only want to store Integers - tell the compiler about that by using generics.
Stack<Integer> st = new Stack<>();
This will tell you that the problem is wherever you try to convert e to an Ìntegerby casting, because in your case, the values ofeare theStrings you pused intostinmain()`.
You should also replace the declaration of st in main with
Stack<String> st = new Stack<>();
and the method declaration to
public static int EvaluationPrefix(Stack<String> st)
to highlight the problem.
When you have a String and want to convert it to an Integer, you need to parse it, for example using Integer.parseInt. But you need to be aware that this method will throw a NumberFormatException if the String is not a number. You will have to handle this exception, for example by catching it and printing a helpful error message.

How do i incorporate ADT into this program

I have a task to write a program that takes in a profit score and multiplies it by 2, takes hard work score and multiplies it by 5, adds the two together, divides by 7 and then multiplies by 5000 to give a "bonus".
This would be very simple but the specification states i must use at least 9 methods not including main, use functions and getter/setter methods. The rest i can do but i don't know how to use ADT in a program like this.
This is what i've got so far...it does what its supposed to but its missing ADT.
import java.util.Scanner;
class bonus {
public static void main(String[] args) {
int i1 = inputProfit();
int w1 = inputWork();
int p1 = performanceScore(i1, w1);
int f1 = finalbonus(p1);
output(f1);
System.exit(0);
}//end main method
public static int inputProfit() {
Scanner scanner = new Scanner(System.in);
System.out.println("Profit score?");
int profitScore = scanner.nextInt();
return profitScore;
}
public static int inputWork() {
Scanner scanner1 = new Scanner(System.in);
System.out.println("Hard work score?");
int workScore = scanner1.nextInt();
return workScore;
}
public static int profit(int profitScore) {
profitScore = profitScore*2;
return profitScore;
}
public static int work(int workScore) {
workScore = workScore*5;
return workScore;
}
public static int performanceScore(int profitScore, int workScore) {
int p = profit(profitScore);
int w = work(workScore);
int performance = ((p + w)/7);
return performance;
}
public static int finalbonus(int performance) {
int payOut = performance * 5000 ;
return payOut;
}
public static void output(int payOut) {
System.out.println("Your bonus is " + payOut + " pounds");
}
}//end class bonus

How to ADD in java through a runner class and a methods class?

ADDn - The first n (0 ≤ n ≤ 4) bits replicate and are concatenated to the first n bits. The last n bits are deleted
e.g. ADD3 ABCDEFGH becomes ABCABCDE
METHODS -
public class Methods
{
public String ADD(String x, int y)
{
if(y > 0)
{
String output = x.substring(0,y);
String output2 = x.substring(y, x.length() - y);
return output + output + output2;
}else {
return x;
}
}
RUNNER -
import java.io.*;
import java.util.*;
public class Runner
{
public static void main(String []args)throws FileNotFoundException
{
Scanner in = new Scanner(new File("data.txt"));
Methods md = new Methods();
String cell = in.nextLine();
String methods = in.nextLine();
for (int x = 0; x < 5; x++)
{
if(methods.equals(("ADD2"))
{
int i = Integer.parseInt(methods);
System.out.println( );
}
DATAFILE-
ADD2 ABBCDFGG
I need it to print ABABBCDF
class Problem {
public static void main(String[] args) {
for (int num = 1000; num <= 2000; num++) {
if (String.valueof(num).contains("3")) {
System.out.println(num);
}
}
}
}

How can i calculate a string mix of operators and operands

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.

How do I call a private method with arguments

I'm having an extremely difficult time getting a private method with arguments to be usable in my toString method but have no idea how to get the two methods to cooperate.
main class:
import static java.lang.System.*;
public class Triples
{
private int number;
public Triples()
{
//this(0);
}
public Triples(int num)
{
number = num;
}
public void setNum(int num)
{
number = num;
}
private int greatestCommonFactor(int a, int b, int c)
{
int max = number;
for(int n = 1; n <= max; n++)
{
for(a = n; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
String last = a + "" + b + c;
}
}
}
}
}
}
}
return 1;
}
public String toString()
{
String output="";
output = output + this.greatestCommonFactor( ) + " \n";
return output;
}
}
and for cross-referencing my runner class:
import static java.lang.System.*;
import java.util.Scanner;
public class Lab11j
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
String choice="";
do{
out.print("Enter the max number to use : ");
int big = keyboard.nextInt();
//instantiate a TriangleThree object
Triples triple = new Triples(big);
//call the toString method to print the triangle
out.println( triple );
System.out.print("Do you want to enter more data? ");
choice=keyboard.next();
}while(choice.equals("Y")||choice.equals("y"));
}
}
if you find you need clarification of this lab, here's a Google docs of the labsheet: https://docs.google.com/open?id=0B_ifaCiEZgtcX08tbW1jNThZZmM
The variables a, b & c can be used as local variables here. This would allow you to remove them from the argument list of greatestCommonFactor:
private int greatestCommonFactor() {
int a = 0;
int b = 0;
int c = 0;
...
as they are only required within the scope of the method.
Well, yeah. You're not passing anything to greatestCommonFactor. I'm not sure what you expected to happen in your toString() method when you didn't pass enough arguments to a method.
you need to pass them like
output = output + this.greatestCommonFactor(1,2,3) + " \n";
the thing is, unless you are passing parameters to toString, without this, this code seems very limited. Alternatively you need to set some fields on the class with what will be passed into your function.

Categories