Unhandled exception type SimulationException - java

My question is why I am still getting a Unhandled exception type SimulationExcpetion on calling damOverflowed() when that isn't declared in the interface for that method. The `levelTooLow method is declared in the interface and in the class and is fine. I added the interface methods at the bottom if that helps.
package asgn1Solution;
import asgn1Question.SimulationException;
import asgn1Question.Log;
import asgn1Question.Actions;
public class DamActions implements Actions{
private Integer capacity;
private Integer nomRelease;
private Integer duration;
private Log logging;
public DamActions(Integer damCapacity, Integer defaultRelease, Integer jobDuration, WaterLog damLog) {
capacity = damCapacity;
nomRelease = defaultRelease;
duration = jobDuration;
logging = damLog;
}
public boolean levelTooLow() throws SimulationException {
if (logging.getEntry(0) < capacity*.25) {
return true;
} else {
return false;
}
}
public boolean damOverflowed() {
if (logging.getEntry(0) > capacity) {
return true;
} else {
return false;
}
}
In Actions.java :
public boolean levelTooLow() throws SimulationException;
public boolean damOverflowed();

From your other question, in your WaterLog class you have declared the following method:
public Integer getEntry(Integer index) throws SimulationException {
if (thelog.isEmpty() || thelog.size() < index) {
return null;
}
return thelog.get(index);
}
The important thing to note here is the throws SimulationException clause in the method signature. This indicates that any method that calls getEntry must either handle a SimulationException or declare that it may be thrown*.
*This isn't strictly true, if the declared exception is an unchecked exception (i.e. a derivative of RuntimeException), then you aren't forced to handle it, even if you declare it in the throws clause. However, that you are getting compilation errors regarding this exception indicates that SimulationException is a checked exception, so does need to be handled or declared.
Thus, you have three options. First, you can enclose your call to getEntry in a try-catch block like so:
public boolean damOverflowed() {
try {
if (logging.getEntry(0) > capacity) {
return true;
} else {
return false;
}
} catch (SimulationException ex) {
// Do something here
}
}
Alternatively, you can declare that damOverflowed can also throw that exception:
public boolean damOverflowed() throws SimulationException {
Finally, as WaterLog#getEntry(Integer) doesn't actually appear to ever throw that exception (despite declaring that it can), your third option is to simply remove the declaration from the method signature:
public Integer getEntry(Integer index) {
if (thelog.isEmpty() || thelog.size() < index) {
return null;
}
return thelog.get(index);
}
I would also recommend reading through the Lesson: Exceptions tutorial from Oracle.

Related

correcting the return type of the method

I have the below code as shown below of which I want to correct the return type
public boolean deleteById(Integer id) throws ResourceNotFoundException {
abcRepository.deleteById(id);
return true;
}
what I am looking to correct it as
if (abcRepository.deleteById(id))
{
return true;
} else
return false;
Now this repository is calling the Jpa repository method of which return type in decompiler I have check is shown below
void deleteById(ID var1);
Now please advise how smartly I can change the return type
Seems you want your method to return true when an object is deleted, and false when object is not found.
The method you are calling is void because is uses exception ResourceNotFoundException to indicate object not found, so you need to catch that exception and return false, instead of making the exception bubble up:
public boolean deleteById(Integer id) { // <-- removed throws
try {
abcRepository.deleteById(id);
return true;
} catch (ResourceNotFoundException ignored) {
return false;
}
}

How to call linked list without array implementation?

For this assignment, I write a program, which will calculate the results of Reverse Polish expressions that are provided by the user.
I must use a linked list to maintain the stack for this program (array implementations of the stack will not receive full credit).
I must handle the following situations (errors):
Too many operators (+ - / *)
Too many operands (doubles)
Division by zero
The program will take in a Polish expression that separates the operators and operands by a single space, and terminates the expression with an equals sign.
The program will continue to take and evaluate expressions until the user enters a zero (0) on a line by itself followed by a new line.
my sample output should show the handling of all the error conditions as well as make use of all of the operators. But when I execute the program it says
Error: Main method not found in class program1.Program1, please define the main method as:
public static void main(String[] args)
Java Result: 1
I have no idea how to call linked list without array implementations. Also
RefObject class and TryparseHelper are below in the same package. tnx
package program1;
import java.util.*;
import java.lang.IllegalStateException;
public class Program1 {
public class Node<T>
{
public T Data;
public Node<T> Next;
}
public class Stack<T>
{
private Node<T> top = null;
public final void Push(T value)
{
top = new Node<T>();
top.Data = value;
top.Next = top;
}
public final T Pop()
{
if (top == null)
{
throw new IllegalStateException("Cannot pop if the stack is empty.");
}
T topValue = top.Data;
top = top.Next;
return topValue;
}
public final boolean IsEmpty()
{
return top == null;
}
public final void Clear()
{
top = null;
}
}
public class ReversePolishCalculator
{
public final void Calculator()
{
String expression = "";
while (!expression.equals("0"))
{
System.out.print("Enter expression: ");
expression = new Scanner(System.in).nextLine();
try
{
System.out.println(" = " + Calculate(expression));
}
catch (RuntimeException ex)
{
System.err.println(ex.getMessage());
}
}
}
private Stack<Double> stack = new Stack<Double>();
private double Calculate(String expression)
{
double result = 0.0;
stack.Clear();
String[] tokens = expression.split("[ ]", -1);
for (String token : tokens)
{
double value = 0;
RefObject<Double> tempRef_value = new RefObject<Double>(value);
if (TryParseHelper.tryParseDouble(token, tempRef_value))
{
value = tempRef_value.argValue;
stack.Push(value);
}
else
{
value = tempRef_value.argValue;
DoOperation(token);
}
}
if (!stack.IsEmpty())
{
result = stack.Pop();
}
if (!stack.IsEmpty())
{
throw new IllegalStateException("Too many operands.");
}
return result;
}
private void DoOperation(String token)
{
if (stack.IsEmpty())
{
throw new IllegalStateException("Too many operators.");
}
double rhs = stack.Pop();
if (stack.IsEmpty())
{
throw new IllegalStateException("Too many operators.");
}
double lhs = stack.Pop();
switch (token)
{
case "+":
stack.Push(lhs + rhs);
break;
case "-":
stack.Push(lhs - rhs);
break;
case "*":
stack.Push(lhs * rhs);
break;
case "/":
if (rhs == 0.0)
{
throw new IllegalStateException("Divide by zero.");
}
stack.Push(lhs / rhs);
break;
default:
throw new IllegalStateException("Unexpected operator: " + token);
}
}
}
}
package program1; TryParseHelper
/**
*
* #author David
*/
public final class TryParseHelper
{
public static boolean tryParseInt(String s, RefObject<Integer> result)
{
try
{
result.argValue = Integer.parseInt(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseShort(String s, RefObject<Short> result)
{
try
{
result.argValue = Short.parseShort(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseLong(String s, RefObject<Long> result)
{
try
{
result.argValue = Long.parseLong(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseByte(String s, RefObject<Byte> result)
{
try
{
result.argValue = Byte.parseByte(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseDouble(String s, RefObject<Double> result)
{
try
{
result.argValue = Double.parseDouble(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseFloat(String s, RefObject<Float> result)
{
try
{
result.argValue = Float.parseFloat(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseBoolean(String s, RefObject<Boolean> result)
{
try
{
result.argValue = Boolean.parseBoolean(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
}
package program1; RefObj
/**
*
* #author David
*/
public final class RefObject<T>
{
public T argValue;
public RefObject(T refArg)
{
argValue = refArg;
}
}
As the error message you've pasted says: To run your program, add to Program1 class a method with this signature public static void main(String[] args). Write in it the code you want to run, e.g., System.out.println("hi"); or whatever.
Update: As I understood from your comment, it seems like your problem is trying to call a non-static method Calculator() from main(...). First, you need a background on class vs object and static vs non-static.
A class is a template or a blueprint. An object is an instantiation of that blueprint. For example, a description of a car is a class, any car is an object. Another example is your Stack class and the Stack<Double> stack = new Stack<Double>() object you've used to calculate an expression.
When you call pop() it needs a specific stack to run on. A specific object. For example, you could have 2 stacks at the same time, and calling pop() on one of them shouldn't affect the other. That's why the method pop() is non-static.
Now, let's think of the Program1 class: Are you really thinking of creating multiple program1 and running them/calling their methods in your code? And would each program1 have a different state from the other? Each stack could have different contents at any time, but program1 doesn't really have any content or state.
When you have a method that doesn't depend on any specific object or a particular state, you mark it as static. For example, a method that adds 2 numbers should be static. Same goes for your Calculator() method.
So, back to your question, to call non-static method Calculator() from main(...), you'll either have to:
(1) convert Calculator() into a static method. You need to ask yourself "Is this method related only to a specific instance, a specific object?". For example, the pop() method of Stack is very related to a certain stack object. If you call it on 2 stack objects, it'll give different results. That's why it should be a non-static method, i.e., a method that depends on a particular instance.
However, Calculator() seems like a method that doesn't really depend on anything else. The fact that it uses a member variable called stack is accidental. You can move the stack variable inside Calculator(). Or you could just make stack static as well.
(2) You could, although it wouldn't make much sense, create an instance of Program1 then call Calculator() on it.
I know the difference between class and object, and static and non-static, can be confusing in the beginning. Read more on it, you'll get comfortable with it with time.
For the without-arrays question: If I understand correctly, you have a problem with the array in main(String[] args). The array here is a must for the program to run and is not related to the stack's implementation. So, I don't expect you teacher to mind having it.
Finally, note that the code, I think, has some problems so don't expect it to run from the first time. And that's absolutely normal, and you'll need to know how to trace a code. Good luck!

Java return type generic

I'm newbie in using generic in java, i have simple method that i would like to return any type from that, this method return other class getters methods, for example i have channels class and that have getChannelId() method, i want to return that from this method:
#SuppressWarnings("unchecked")
public <T extends Channels> T getChannelColumn(ChannelContentModel.channelColumns column) {
switch (column) {
case id:
return (T) channel.getId();
break;
case title:
return (T) channel.getChannelTitle();
break;
}
return null;
}
getId is int and getChannelTitle is string, how can i fix this method to return any type?
in my code channel is instance of Channels class, Thanks in advance
As commented by #Geckstar;
Java is statically typed
But it is possible to clear your code sample from compile errors.
Remove breaks, because there is no need to break after return statement.
extend return type from object. T extends Object instead T extends Channel
id must be Integer, not int or change to (T)(Integer) channel.getId()
This is not a good solution, it only fixes compile errors.But this method's usage may cause runtime failures.
#SuppressWarnings("unchecked")
public <T extends Object> T getChannelColumn(ChannelContentModel.channelColumns column) {
switch (column) {
case id:
return (T) channel.getId(); //int must be Integer
case title:
return (T) channel.getChannelTitle();
}
return null;
}
You can create property wrapper which will hold the value in string data format when required it will convert to a specific data type.
public class MyProperty {
private String stringVal;
public MyProperty(String stringVal) {
this.stringVal = stringVal;
}
public Integer getInteger() throws IllegalArgumentException {
return integerValue.getValue();
}
public String getString() {
return stringValue.getValue();
}
private PropertyValue<String> stringValue = new PropertyValue<String>() {
protected String parse(String rep) {
return rep;
}
};
private PropertyValue<Integer> integerValue = new PropertyValue<Integer>() {
protected Integer parse(String rep) throws NumberFormatException {
return Integer.valueOf(rep);
}
};
private abstract class PropertyValue<T> {
private T value;
protected abstract T parse(String rep) throws Exception;
public T getValue() throws IllegalArgumentException {
try {
value = (stringValue == null) ? null : parse(stringVal);
} catch (Exception e) {
value = null;
}
return value;
}
}
}
you can make specialize class or one class having the access method to get the value with specified data type
#SuppressWarnings("unchecked")
public MyProperty getChannelColumn(ChannelContentModel.channelColumns column) {
switch (column) {
case id:
return new MyProperty(channel.getId());//
break;
case title:
return new MyProperty(channel.getChannelTitle());
break;
}
return null;
}

How can I return the right data type of a instance when this instance might have different data type?

I have this code in Modula-2,
PROCEDURE Prune(typeExp: TypeExp): TypeExp;
BEGIN
CASE typeExp.^class OF
| VarType:
IF typeExp^.instance = NIL THEN
RETURN typeExp;
ELSE
typeExp^.instance = Prune(typeExp^.instance);
RETURN typeExp^.instance;
END;
| OperType: RETURN typeExp;
END;
END Prune;
I have several problems when I try to convert this code into java. I can create an instance and judge if its instance is null and then choose what to return. But I don't really know what to do with the case 2, which is the instance might be a new Opentype(); because only one value can be returned in this case.
public TypeExp Prune(TypeExp typeExp){
TypeExp r = new VarType();
if (r.instance == null) {
return r;
}
else {
r.instance = Prune(r.instance);
return r.instance;
}
}
The second issue is I don't think I can call the function Prune() inside itself, so what can I do? Thanks in advance.
I dont really know Modula-2, but it might be something like this:
public TypeExp Prune(TypeExp typeExp) {
if (typeExp instanceof VarType) {
if (typeExp.instance == null) {
return typeExp;
}
else {
typeExp.instance = Prune(typeExp.instance);
return typeExp.instance;
}
} else if (typeExp instanceof OperType) {
return typeExp;
}
//if typeExp is not an instance of VarType or OperType
return null;
}
The Modula code does not return in all code paths. Thats not possible in Java. I inserted return null in those cases. Thats probably wrong for your application though.
Below example not same as your func, but I think you can modify to your needs. It hides your return types behind Type class => you can return objects of two classes.
Main
package com.type;
public class Main {
public static void main(String[] args) {
Type first = new FirstType();
Type second = new SecondType();
System.out.println(func(first).getTypeName());
System.out.println(func(first).getTypeName());
System.out.println(func(second).getTypeName());
}
public static Type func(Type type) {
if(type instanceof FirstType) {
type.setTypeName("First");
} else {
type.setTypeName("Second");
// something here
}
return type;
}
}
Type
package com.type;
public class Type {
private String typeName;
public Type() {}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
FirstType
package com.type;
public class FirstType extends Type {
}
SecondType
package com.type;
public class SecondType extends Type {
}

exception handling in parentheses matching using stacks in java

I am trying to write a program that checks for parentheses matching using stacks.This is my ArrayStack class.
public class ArrayStack{
private final int DEFAULT_SIZE=10;
public int tos;
Object[] array;
public ArrayStack(){
array =new Object[DEFAULT_SIZE];
tos=-1;
}
public void push(Object e)throws OverFlowException{
if (isFull()){
throw new OverFlowException("OverFlow");
}
else{
array[tos+1]=e;
tos++;
}
}
public Object topAndpop() throws EmptyStackException{
Object returnPop;
if (isEmpty())
throw new EmptyStackException("Stack empty");
else{
returnPop=top();
pop();
}
return returnPop;
}
public void pop() throws EmptyStackException{
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
tos--;
}
public Object top() throws EmptyStackException{
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
return array[tos];
}
public boolean isEmpty(){
return tos==-1;
}
public boolean isFull(){
if(tos==array.length)
return true;
else
return false;
}
public void makeEmpty() throws EmptyStackException{
while (tos>=0){
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
pop();
}
}
public void print(){
for (int i=0;i<=tos;i++){
System.out.println(array[i]);
}
}
public static void main (String args[]) throws EmptyStackException,OverFlowException {
ArrayStack newStack=new ArrayStack();
newStack.push("S");
newStack.push("apple");
newStack.push("D");
newStack.topAndpop();
newStack.push("P");
newStack.print();
}
}
And this is my matching class.
public class Matching{
ArrayStack match_Stack=new ArrayStack();
Object popped;
Object[] array_match={"{","}"};
public boolean matching() {
for(int i=0;i< array_match.length;i++){
if (array_match[i]=="{" || array_match[i]=="[" ||array_match[i]=="(" )
match_Stack.push(array_match[i]);
if(array_match[i]=="}" || array_match[i]=="]" || array_match[i]==")"){
if (match_Stack.isEmpty())
return false;
if (match_Stack.topAndpop()==array_match[i]);
return true;
}
}
if (match_Stack.isEmpty())
return true;
else
return false;
}
public static void main (String args[]) throws EmptyStackException,OverFlowException {
}
}
This is EmptyStackException class :
public class EmptyStackException extends Exception{
public EmptyStackException(){
super();
}
public EmptyStackException(String s){
super(s);
}
public void print(){
System.out.println("OverFlow");
}
}
But the problem is when I compile matching I get an error as unreported exception EmptyStackException.must be caught or declared to be thrown.
I think the problem is with exceptions which I don't have a good knowledge of.I am stuck here for days and because of this exception issue I am unable to study the rest of data structures. So any help on how I can fix this and run this would be greatly helpful.
You really should read a tutorial about exceptions and work it through completely. This way you will get a better understanding of exceptions.
Your problem is the method Matching.matching(). You are using the methods ArrayStack.push(Object) and ArrayStack.topAndpop() in the method's implementation. But these methods are declared to (potentially) throw an EmptyStackException.
Your matching method does not deal with that exception. The exception must be either caught or thrown. This is what the compiler does tell you. So for a first coming-through declare the method as
public boolean matching() throws EmptyStackException

Categories