How to write junit for this method: [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
public void declareWinner()
{
compare and declare winner
if(getLive_player1()==0 && getLive_player2()>0)
{
System.out.println("Player 2 wins with "+getLive_player2()+" cells alive.");
}
else if(getLive_player2()==0 && getLive_player1()>0)
{
System.out.println("Player 1 wins with "+getLive_player1()+" cells alive.");
}
else
{
System.out.println("There is a tie.");
}
}

Well, it's clear that you have a handful of different branches in your code, so you'll want to implement unit tests where you can hit your if and else if statements:
player1 = 0 and player2 > 0
player1 = 0 and player1 > 0
As well as a test where you hit your else statement:
Clearly multiple options, but player1 > 0 and player2 > 0 will suffice to reach that branch.
So that's at least three different #Test methods.
I'm assuming your concern is determining how to capture the System.out calls. You can change the out stream to one which points to something that can be captured programmatically. That is achieved with System.setOut():
#Test
public void testSomething() {
ByteArrayOutputStream myOut = new ByteArrayOutputStream();
System.setOut(new PrintStream(myOut));
// do your setup and then execute declareWinner()...
String methodOutput = myOut.toString();
// Use Assert.assertEquals(...) to check methodOutput against expected value...
}
By the way
Based on what I can see, how do you know that two scores > 0 end in a tie? Seems like the else statement hasn't really closed out all of the options. But then again, I'm not sure what you're underlying code is doing...

Related

Better way to reduce if statements [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
So I have just gotten a bunch of old code where I should improve the performance of. After looking for a while I came accross this piece of code:
//Reference on how the global Variables look like:
private static final int PLS_4_SYSTEM_MALFUNCTION_FL = 4;
private static final int SPS1_20_PUFFER_EMPTY = 20;
private static final int SPS1_30_STOPPERFL_LOCKED = 30;
//...
int disturbance1 = bMessage.getDisturbanceSps1().intValue();
int disturbance2 = bMessage.getDisturbanceSps1().intValue();
if (disturbance1 == SPS1_20_PUFFER_EMPTY && disturbance2 == 0) {
checkWarnings(bMessage, PLS_5_PUFFER_EMPTY);
}
if (disturbance1 == SPS1_30_STOPPERFL_LOCKED && disturbance2 == 0) {
checkWarnings(bMessage, PLS_6_STOPPERFL_LOCKED);
}
if (disturbance1 == SPS1_40_DISTURBANCEFL && disturbance2 == 0) {
if (bMessage.getDisturbanceType().intValue() == DISTURBANCETYPE_SYSTEMDISTURBANCE_SHORT) {
checkWarnings(bMessage, PLS_3_SHORTDISTURBANCE_FL);
}
else if (bMeldung.getStoerungsartMde().intValue() == DISTURBANCETYPE_SYSTEMDISTURBANCE_LONG) {
checkWarnings(bMessage, PLS_4_SYSTEMMALFUNCTION_FL);
}
}
//...
This is just a small example of the code. There are like 300+ more lines that goes on like this.
Now I know that there are many answers on the web already, and I have looked at some of them, but I am unsure which answer would help me the best in this case.
You could change that to something like enums, new-style switches etc. This can certainly make the code more readable and maintainable.
However, you were talking about enhancing performance. Changing this code most likely will have hardly any impact on performance, at least not in a positive way.
If you want to improve performance, measure and find the bottlenecks in the code and focus on those.
this might help !!
if(disturbance2 == 0) {
switch (disturbance1){
case SPS1_20_PUFFER_EMPTY:
checkWarnings(bMessage, PLS_5_PUFFER_EMPTY);
break;
case SPS1_30_STOPPERFL_LOCKED:
checkWarnings(bMessage, PLS_5_PUFFER_EMPTY);
break;
case SPS1_40_DISTURBANCEFL:
if (bMessage.getDisturbanceType().intValue() == DISTURBANCETYPE_SYSTEMDISTURBANCE_SHORT) {
checkWarnings(bMessage, PLS_3_SHORTDISTURBANCE_FL);
}
else if (bMeldung.getStoerungsartMde().intValue() == DISTURBANCETYPE_SYSTEMDISTURBANCE_LONG) {
checkWarnings(bMessage, PLS_4_SYSTEMMALFUNCTION_FL);
}
break;
}
}
also you can write
if(disturbance2 != 0){
// return or exit if requires
}
// then start switch() , you can remove one branch of block
Switch on disturbance1 can help.
Check out the new switch style from Java17. It makes code really lean.

opposite of if condition [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to rewrite my if else statement so I skip the //do nothing part but I can't get my around to find the opposite of the if statement.
someone please help?!
if (decision.equals("repay")){
String riskClass = null;
if (doc.hasItem("riskclass")){
riskClass = doc.getItemValueString("riskclass");
}
if ( (null == riskClass) || (riskClass.equals("")) || (riskClass.equals("repay")) ){
//do nothing
} else{
//do something
}
}
You can simply invert the condition. Try the snippet below.
if ( !((null == riskClass) || (riskClass.equals("")) || (riskClass.equals("repay"))) ){
//do something
}
Another way to invert the check is invert individual conditions and replace or's with and's:
if ( (null != riskClass) && (!riskClass.equals("")) && (!riskClass.equals("repay")) ){
Another point:
Avoid call equals on variables passing constants: the constant will never be null. So in this particular case would be better write:
if (!"repay".equals(riskClass) && !"".equals(riskClass))

Repeat String Recursively [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is homework. I get the logic but i got stuck on the code. I've done it with normally way and it takes 1 week to get the code. I need to get repeat string with recursive way in Java.
This is my code :
static String repeatString (final int n, final String[] syllables, final String currentWord) {
if (n == 0) {
System.out.println(currentWord);
} else {
for (int i = 0; i < syllables.length; i++) {
repeatString(n - 1, syllables, currentWord + syllables[i]);
}
}
return "";
}
if i call in main method like
String[] str = {"a", "b"};
repeatString(1, str, " ");
then i get output (a,b) if i change to
repeatString(2,str," ");
then i get output ( aa,ab,ba,bb) if i change to
repeatString(3,str," ");
then i get output (aaa,aab,aba,abb,baa,bab,bba,bbb) and so on.
So basically it is like 2 to the power to n. If n=1, i got 2, if n=3, i got 8, and so on.
I would be grateful if someone can help me to get this code in recursive way.
Any help is much appreciated.
The method you have there is recursive already. Being recursive does NOT mean it should have no for loops. A recursive method in cheap words means the method calls itself, which yours does.

Java LinkedList problems [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
Error :
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2
at java.util.LinkedList.checkElementIndex(LinkedList.java:553)
at java.util.LinkedList.get(LinkedList.java:474)
at InterfacePackage.Main.main(Main.java:116)
Java Result: 1
Code (shortened) :
if(input.length() > 0)
{
if(command.size() == 1)
{
switch(command.get(0).toLowerCase())
{
case "exit":
case "qqq":
active = false;
break;
default:
System.out.println("invalid input, for complete list of commands enter 'help'...");
break;
}
}
else if(command.size() > 1)
{
if(command.get(0).equalsIgnoreCase("shutdown") && command.size()==3)
{
Shutdown shutdown = new Shutdown();
shutdown.Start(command);
}
else if(((command.get(0).equalsIgnoreCase("scan")
&& command.get(1).equalsIgnoreCase("ips"))
|| command.get(3).equalsIgnoreCase("/e"))
&& (command.size()>=2 || command.size()<4))
{
SystemsIPs sips = new SystemsIPs();
sips.Start(command);
}
else
{
System.out.println("invalid input, for complete list of commands enter 'help'...");
}
}
}
The error occurs when the users enters two string within a line that doesn't exist in the else if(command.size() > 1) loop.
For example, if the user would enter : hello world the program produces this error.
So this is a program that does various things based on user input to a console. I've been getting this error and and wanting to know what is causing it. I know I can just catch it, but I really want to know what causing this error.
Your error seems to be caused by
command.get(3).equalsIgnoreCase("/e"))
There is no index 3. Check if that index exists first, before you do that.
You're getting an IndexOutOfBoundsException as it says, and it occurs when you're trying to access a position in a collection/array and that position is empty, you're trying to access to an index that doesnt exist. If you don't want that to happen then force the program to use an Collection with a size more than 3 element.
The problem is in this line:
else if(((command.get(0).equalsIgnoreCase("scan") &&
command.get(1).equalsIgnoreCase("ips")) ||
command.get(3).equalsIgnoreCase("/e")) &&
(command.size()>=2 || command.size()<4))
You are using command.get(3) to retrieve the 3rd element of the LinkedList, but it's not guaranteed that there are at least 3 elements in the list.
So you'd better add a condition command.size() >= 3 before command.get(3).
Ok so here is how I solved the problem :
else if((command.get(0).equalsIgnoreCase("scan") && command.get(1).equalsIgnoreCase("ips")) && (command.size()>=2 || command.size()<4))
So I removed the
|| command.get(3).equalsIgnoreCase("/e"))
... from the code entirely, and improved the case in the separate class that this if statement directs to.
Here is what I did in the separate class...
if(command.size()==3 && command.get(2).equalsIgnoreCase("/e")) { }
else if(command.size()==2) { }
And it works (:

Out of boundaries error with a 2D Array Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am making a game four in a row, where the number of rows and colomns is determined by the player(so can be anything, as long as more than four). So users input is stored in the variables "rows" and "column". The field looks smth like this, so the first row is always numbers.
I have trouble with the search algorithm for the winner.
While my algorithm for the horizontal search works fine, the vertical one with the same logic gives me the out of bound error.If you could please help me to spot the mistake, I would be very grateful. Thank you!
1 2 3 4 5
|-|-|-|-|
|-|-|-|-|
|-|-|-|-|
public static String checkWinner(String [][]field){
//horizontally, which works
for(int i=1; i<=rows; i++){
for (int j=0; j<=column-1;j++){
if (((j>=3 || j==column-1) && field[i][j]!="|_" && field[i][j]==field[i][j-1] && field[i][j]==field[i][j-2] && field[i][j]==field[i][j-3])
|| (field[i][j]!="|_" && field[i][j]==field[i][j+1] && field[i][j]==field[i][j+2] && field[i][j]==field[i][j+3]))
{
return field[i][j];
}
}
}
//vertically which doesn't work
for(int i=0; i<column; i++){
for (int j=1; j<=rows-1;j++){
if (((j>=4 || j==rows-1) && field[j][i]!="|_" && field[j][i]==field[j-1][i] && field[j][i]==field[j-2][i] && field[j][i]==field[j-3][i])
|| (field[j][i]!="|_" && field[j][i]==field[j+1][i] && field[j][i]==field[j+2][i] && field[j][i]==field[j+3][i]))
{
return field[i][j];
}
}
}
return null;
}
In your Horizontally loop logic you are running your loop for column from j=0 to column-1 but then you are accessing field[i][j] with values like j+1, j+2, j+3 which will go beyond column
for example : user enters column value as 5 but your logic of j+2 at j=4 & i=0 will make it to access 6th column (field[0][6]) which is obviously OutOfBound.
check for same error in Vertically Loop logic for rows value
and as NOTE: compare strings using equals() not using equality operators like ==

Categories

Resources