How can we set value of some integer variable in a method under test in Junit? This is just a made up code to reproduce the problem I have. Here is the code:
void someMethod(long l) {
int i = 0;
while (i < l) {
if (i == Integer.MAX_VALUE) {
throw new RuntimeException;
}
i++;
}
I need to set i to 2,147,483,647 in test to check that when the if condition is true, it properly throws the exception.
First of all, my question was not descriptive of the problem that i had.
I was able to create an instance variable
int maxVal = Integer.MAX_VALUE
So, the method looked like this:
void someMethod(long l) {
int i = 0;
while (i < l) {
if (i == maxVal) {
throw new RuntimeException;
}
i++;
}...
and then set the instance variable to a different value at the test case, 0 in case of the code above, and it threw exception like i had wanted.
Thanks Turing85 for that clue.
You can pass argument long l to be Integer.MAX_VALUE+1 this will allow i to be equal to Integer.MAX_VALUE and you will get exception thrown.
Related
I am very new at programming and the problem thus might seem very silly. The below mentioned method has a return type as an int array. When we don't throw any unchecked exception it throws an error which I understand. But why does including an unchecked exception removes that error? It still does not have any return statement, isn't it correct?
public static int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
//throw new IllegalArgumentException("No two sum solution");
}
There is no actual requirement for there to be a return statement in a method with a non-void return type. For example:
int huh() {
while (true) {}
}
is legal.
The requirement is that the method can't complete normally (JLS):
If a method is declared to have a return type (§8.4.5), then a compile-time error occurs if the body of the method can complete normally (§14.1).
Normal completion is basically when execution "falls off the bottom" of the method, that is, reaches the end of the method without encountering a return or throw statement.
So, if you put a throw statement at the end of your method, execution can't reach the end of the method, so it's legal.
In the case of the huh() example above, the while loop doesn't complete normally, so execution cannot reach the end of the method, so you don't need a return or throw there.
There are cases where your program never reaches the inner return statement. E.g. if nums has a length of 0 or if nums[j] == target - nums[i] is never true. For these cases the method needs either return something or it can throw an exception. It is your decision what is the correct behaviour for your use case. If nothing is defined for such cases and your IDE would let you get through with it you would have broken code. If you throw an exception instead of doing nothing your IDE says its fine because your code is correct on a technical level.
The exception forcibly punts you from the called method. The calling method is then forced to catch the exception and continue computation without access to the return value of the called method.
If the exception is unavoidable / unconditional, then a return statement that follows is never necessary or useful.
Not sure where I'm going wrong with this. I've asked someone in my class and they said there should be an argument with "toonRijSterren". when I do this I just get more errors, could someone have a look and tell me where I'm going wrong?
public static void main(String[] args) {
int aantal = 0;
toonRijSterren(aantal);
toonSterrenVierkant(aantal);
}
public static void toonRijSterren(int mpAantal) {
while (mpAantal < 6) {
System.out.print(" * ");
mpAantal++;
}
}
public static void toonSterrenVierkant(int mpAantal) {
for (int mpAatal = 0; mpAantal < 6; mpAantal++) {
System.out.println(toonRijSterren());
}
}
ther error line is in the brackets of the last toonRijSterren());
toonRijSterren is void method which means it does not return any value and therefore you can not put it inside System.out.println() or you can not assign it to some variable.
toonRijSterren expects an int argument which you have missed while calling it.
Given below is an example of how you should call toonRijSterren:
public static void toonSterrenVierkant(int mpAantal) {
for (int mpAatal = 0; mpAatal < 6; mpAatal++) {
toonRijSterren(mpAantal);
}
}
You are not passing the argument when you call your method.
Try this:
System.out.println(toonRijSterren(mpAatal));
First of all, your function toonRijSterren takes an int type parameter (according to its declaration), so you need to pass to it another argument. For example:
toonRijSterren(mpAantal)
Second, the function toonRijSterren returns void. That means, it just does an operation (in this case, printing) without returning anything. What you're trying to do is to use its return value (which doesn't exist) as an argument to System.out.println, which causes an error (because println expects an argument of some type).
You could achieve what I think you're trying to do with the line:
toonRijSterren(mpAantal);.
The function itself prints the values, so the println here is unnecessary and causes an error.
You are missing the parameter in your toonSterrenVierkant() function where you calling toonRijSterren.
Here is the corrected version of your code:
public static void toonSterrenVierkant(int mpAantal) {
for (; mpAantal < 6; mpAantal++) {
toonRijSterren(mpAatal);
}
}
As your methed toonSterrenVierkant(int mpAantal) has a int parameter, you must pass an int value as an argument in the last toonRijSterren(). For example, replace the line System.out.println(toonRijSterren()); with System.out.println(toonRijSterren(1));
I have read the similar question and learnt that it is not possible to use a ternary operation instead of if statement, which does not have else statement. Because, if-without else statements are binary not ternary. My question is more best-practice.
In my code, there are lots of code snippet like that
if( calculation < 1 ){
calculation= 0;
}
I would like to shorten these with tenary. Is it a good practice to change these statements with the following.
calculation = calculation < 1 ? 0 : calculation;
You could create a class (or classes) that would create a nice fluent API. Such that your line would be:
calculationTo = replace(calculationTo).with(0).when(calculationTo < 1)
In my opinion it doesn't read much better than a standard if statement, but it also depends on the conditions that you have.
Example implementation:
public class Replacer<T> {
private final T value;
private T replacementValue;
private Replacer(T value) {
this.value = value;
}
public static <V> Replacer<V> replace(V value) {
return new Replacer<V>(value);
}
public Replacer<T> with (T replacementValue) {
this.replacementValue = replacementValue;
return this;
}
public T when(boolean condition) {
if (condition) {
return replacementValue;
} else {
return value;
}
}
}
import static somepackage.Replacer.replace;
public class Main {
public static void main(String[] args) {
int calculationTo = 3;
calculationTo = replace(calculationTo).with(0).when(calculationTo < 1);
}
}
You might expand it or make condition a function so it can be used with lambda, etc. I would also make method with return object of different class (e.g. ReplacerWithValue) so that calling with twice in one chain would result in compilation error.
Since you're asking for a best practice, I'll point out something where you could do better and then I'll tell you why I like the ternary operator.
Let me rephrase you're code snippet:
if (calculatedValueAfterStep1 < 1) {
calculatedValueAfterStep2 = 0;
} else {
calculatedValueAfterStep2 = calculatedValueAfterStep1;
}
When you read your code and somebody asks you "what does 'calculation' represent?" then you cannot answer this question without asking for the line number. The meaning of "calculation" changes over the course of the program code. If you cannot explain what a variable means, you cannot give it a good name. This is why I like my Version better. There is a clear Definition of what meaning the variables "calculatedValueAfterStep1" and "calculatedValueAfterStep2" are. Yes, the names are bad. Change them to your domain accordingly.
Now when you look at the code, you'll notice that "calculatedValueAfterStep2" is not declared. So let's Change the code:
int calculatedValueAfterStep2 = -1;
if (calculatedValueAfterStep1 < 1) {
calculatedValueAfterStep2 = 0;
} else {
calculatedValueAfterStep2 = calculatedValueAfterStep1;
}
Now it gets ugly. The same person asking the earlier question will now ask "why is 'calculatedValueAfterStep2' initialized with '-1'?". So here comes the ternary operator:
int calculatedValueAfterStep2 = (calculatedValueAfterStep1 < 1) ? 0 : calculatedValueAfterStep2;
beautiful!
I want to create a set method to insert maximum temperature for a specific place and I want that temperature to be of type Double,the method will check if the entered number is >= to 100 or <= to 100
if yes then it will be inserted in the maximum temperature field..
else I have to throw a user defined exception that will tell me that the number I entered is out of the supposed limits!
I wrote the Exception and the method this way:
public class OutOfSensibleLimits extends Exception
{
private Double max;
public OutOfSensibleLimits(Double max)
{
this.max = max;
}
public Double getMax()
{
return max;
}
public String toString()
{
return "The maximum Tempreture you entered: '" + maxTemp +
"' is out of sensible limits.";
}
}
public void setMaxTemp(Double max){
if ( max >= -100 || max <= 100)
{
maxTemp = max;
}
else throw new OutOfSensibleLimits();
}
and it gives me an error, what am I doing wrong?
Problems:
This is not how exceptions work -- you need to call the appropriate super constructor with the appropriate String if you want it to show a String, and
You're not calling your own exception's constructor properly. You've written it to accept a Double, and you're not passing in a Double (you're passing in nothing).
the toString method is unnecessary and confusing since it will never be called and the String will never be seen.
You state, "and it gives me an error,...", but don't show us any error message. I'm guessing that the compiler is complaining that you're not calling your class's constructor correctly, but please don't leave us guessing -- show the complete unabridged error message.
Your setMaxTemp uses the wrong boolean operator: if ( max >= -100 || max <= 100). This is always true. You want to use && instead.
Suggestions:
Yes, pass in a double the constructor
And then use that double to create an appropriate error/exception message that is passed into the super's constructor.
Get rid of your exception class's fields and toString() method.
Most important, I urge you to first read the Exception tutorial before trying anything else.
Also simplify as you're making things overly complex. Your Exception class could easily be nothing more than a constructor and that's it.
Make sure that the method that might throw the exception declares that it throws this exception.
For example:
public class TestSensibleLimits {
private Double maxTemp;
public void setMaxTemp(double max) throws OutOfSensibleLimits {
if (max >= -100 && max <= 100) { // use && not ||
maxTemp = max;
} else
throw new OutOfSensibleLimits(max);
}
public Double getMaxTemp() {
return maxTemp;
}
public static void main(String[] args) {
TestSensibleLimits test = new TestSensibleLimits();
try {
test.setMaxTemp(200);
} catch (OutOfSensibleLimits e) {
e.printStackTrace();
}
}
}
#SuppressWarnings("serial")
public class OutOfSensibleLimits extends Exception {
private static final String FORMAT = "The maximum Temperature you "
+ "entered: %.2f is out of sensible limits.";
public OutOfSensibleLimits(Double max) {
super(String.format(FORMAT, max));
}
}
Why I am not getting any Exception in the following code?
After running this code I am getting an infinite loop mentioning at test.fact(t.java:32)
No Compile-Time Error was found.
class test
{
int fact(int m) throws Exception
{
if (m==1)
{
return 1;
}
else
return (fact ((m-1)*m));
}
}
class main
{
public static void main(String ar[]) throws Exception
{
test t = new test();
System.out.println(t.fact(5));
}
}
while say for example i am using
return(a+b);
it executes successfully whats the problem with the recursion
to show an error???
You have a mistake in the return value expression of fact method.
It should be
return fact(m-1) * m;
Another way to calculate factorial using cycle (with no recursion):
int fact(int m) throws Exception
{
int f = 1;
for (int i = 0; i < m; f *= ++i);
return f;
}
return (fact ((m-1)*m));
returns
fact(20)
which returns
fact (380)
which returns
fact (379*380)
which ....
which never returns anything and should make a stack overflow (too much memory is used on the call stack).
return fact(m-1) * m;
should work.
I highly recommend you reading again the basics, and examples ( here, for example - http://www.toves.org/books/java/ch18-recurex/index.html)
Try writing the recursion tree yoursels, in order to understand what happens.