Unit Testing – Bowling Kata in Java

I share my kata with bowling score, which was created in Java. It is available to anyone who wants to check it with code.
I am happy about comments.

Class BowlingGameScore {

private int[] pinsKnockedDown = new int[21];
private int currentRoll = 0;

void roll (int pinsKnockedDown) {
this.pinsKnockedDown[currentRoll++] = pinsKnockedDown;
}

int score () {
int total score = 0;
int rollNumber = 0;

for (int frameNumber = 0; frameNumber <10; frameNumber ++) {
int frame score;

if (isSpare (rollNumber)) {
frameScore = 10 + getSpareBonus (rollNumber);
rollNumber + = 2;

} else if (isStrike (pinsKnockedDown[rollNumber])) {
frameScore = 10 + getStrikeBonus (rollNumber);
rollNumber ++;

} else {
frameScore = pinsKnockedDown[rollNumber] + pinsKnockedDown[rollNumber + 1];
rollNumber + = 2;
}

total score + = frame score;
}

return total score;
}

private int getStrikeBonus (int roll) {
return pinsKnockedDown[roll + 1] + pinsKnockedDown[roll + 2];
}

private boolean isStrike (int roll) {
Discard == 10;
}

private int getSpareBonus (int roll) {
return pinsKnockedDown[roll + 2];
}

private boolean isSpare (int roll) {
return pinsKnockedDown[roll] + pinsKnockedDown[roll + 1] == 10;
}}

And his tests:

Class BowlingGameScoreTest {
private bowling game score game;

@BeforeEach
void setUp () {
game = new bowling game score ();
}

@Exam
Empty
game_no_pins_get_hit () {
rollMany (0, 20);

Assertions.assertEquals (0, game.score ());
}

@Exam
Empty
game_just_1_pin_get_hit () {
rollMany (1, 20);

Assertions.assertEquals (20, game.score ());
}

@Exam
Empty
game_with_1_spare () {
rollSpare ();
game.roll (3);
rollMany (0, 17);

Assertions.assertEquals (16, game.score ());
}

@Exam
Empty
game_with_1_strike () {
game.roll (10);
game.roll (3);
game.roll (4);
rollMany (0, 16);

Assertions.assertEquals (24, game.score ());
}

@Exam
Empty
game_of_strikes () {
rollMany (10, 12);

Assertions.assertEquals (300, game.score ());
}

@Exam
Empty
knockdown_nine_and_miss_ten_times () {

int firstRollPinsKnockedDown = 9;
int secondRollPinsKnockedDown = 0;
int repeatTimes = 10;
rollPair (repeatTimes, firstRollPinsKnockedDown, secondRollPinsKnockedDown);

Assertions.assertEquals (90, game.score ());
}


@Exam
Empty
knockdown_five_and_spare_ten_times_and_fice () {
rollPair (10, 5, 5);
game.roll (5);

Assertions.assertEquals (150, game.score ());
}

private void rollPair (int repeatTimes, int firstRollPinsKnockedDown, int secondRollPinsKnockedDown) {
for (int i = 0; i <repeatTimes; i ++) {
game.roll (firstRollPinsKnockedDown);
game.roll (secondRollPinsKnockedDown);
}
}

private void rollSpare () {
game.roll (5);
game.roll (5);
}


private void rollMany (int pins, int times) {
for (int i = 0; i <times; i ++) {
game.roll (pins);
}
}

}

Java – How to read HTML from URL.openStream () after 500 return code causes exception?

I'm creating a learning terminal application that gets a website URL.openStream (), Based on the query, the page may return a 500 error code. However, there is a valuable error description in the body that I want to show.

Unfortunately, URL.openStream () triggers an IOException if the return code 500 is found, and I have no way to read the stream once the exception has been caught.

BufferedReader in = null;
To attempt {
URL url_connection = new URL (url);
in = new BufferedReader (new InputStreamReader (url_connection.openStream ()));
} catch (IOException e) {
}

The variable in the stays null, because the exception is thrown before openStream returns.

How do I read the HTML code from the HTTP response?

Java – Do you handle exceptions when reading Excel data with Apache POI?

I have the following code that works, but I'm not happy with it and it seems like an ugly hack.

NppColumn is an enumeration that contains the column indexes. The problem is when a POI line can not be stored in the vehicle object and a class transformation exception is thrown. I want to know which column caused this so I can alert the user to the cause of the error. I do not like many things about the code.

  • The switch statement is big and ugly.
  • At first I thought the enumeration was a good idea, so we can easily change which column contains which value, but now I'm not so sure.
  • Intercepting the runtime exception and setting the error messages for the vehicle object seems to be wrong.
  • Much code seems to be superfluous.
Private vehicle convertPoiRowToVehicle (Row inputPoiRow) {
Vehicle vehicle = new vehicle ();

for (NppColumn nppColumn: NppColumn.values ​​()) {
int index = nppColumn.getValue ();

Cell currentCell = inputPoiRow.getCell (index, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);

if (currentCell! = null) {

switch (nppColumn) {
Case ECS:
To attempt {
String cellValue = currentCell.getStringCellValue ();
vehicle.seteConstructionSeries (cellValue);
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("E Construction Series has a formatting error");
}
break;
Suitcase ENGINE:
To attempt {
vehicle.setEngine (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("Engine has a formatting error");
}
break;
Housing MODEL:
To attempt {
vehicle.setModel (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("model has a formatting error");
}
break;
Case CVS:
To attempt {
vehicle.setCountry_version (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("A formatting error occurred in the country version");
}
break;
Case STG:
To attempt {
vehicle.setSteering (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("Streering has a formatting error");
}
break;
case MODEL_CODE_2:
To attempt {
vehicle.setModelcode (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("model code 2 has a formatting error");
}
break;
case TRIM_LEVEL:
To attempt {
vehicle.setTrimLevel (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("Trim Level has a formatting error");
}
break;
Case L_02:
To attempt {
vehicle.setRegionLevel2 (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("Region Level 2 has a formatting error");
}
break;
Suitcase PLU:
To attempt {
vehicle.setPlanningUnit (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("Planning Unit has a formatting error");
}
break;
case PRICE_STATUS:
To attempt {
Object priceStatus = getValueForDateColumn (currentCell);
vehicle.setPriceStatus ((LocalDate) priceStatus);
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("price status has a formatting error");
}

break;
case CURRENCY:
To attempt {
vehicle.setCurrency (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("Currency has a formatting error");
}
break;
case PRICE:
To attempt {
String priceValue = currentCell.getStringCellValue ();
priceValue = priceValue.replace (".", "");
priceValue = priceValue.replace (",", ".");
BigDecimal bigDecimalPrice = new BigDecimal (priceValue);
vehicle.setPrice (bigDecimalPrice);
} catch (NumberFormatException e) {
vehicle.getValidationErrors (). add ("price has a formatting error");
}

break;
Case Status:
To attempt {
vehicle.setStatus (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("Status has a formatting error");
}
break;
Case COMMITTEE:
To attempt {
vehicle.setCommittee (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("scrap has a formatting error");
}
break;
case COMMITTEE_DATE:
To attempt {
Object committeeDate = getValueForDateColumn (currentCell);
vehicle.setCommitteeDate ((java.sql.Date) committeeDate);
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("scrap date has a formatting error");
}
break;
case SYNCHRO_POINT:
To attempt {
vehicle.setSynchroPoint (currentCell.getStringCellValue ());
} catch (ClassCastException e) {
vehicle.getValidationErrors (). add ("Syncro Point has a formatting error");
}
break;

}
}

}
Return vehicle;
`` `

Calculate the average time between failures (SRE metrics) in the Java stack

We are currently trying to capture / calculate the mean time between failures for all of our services in production.
We use K8s and Prometheus to monitor the same thing.
MBTR = total operating time / number of errors
How can you achieve full uptime with prometheus? Is it possible to use JVM metrics? Is it a good idea to use ps -eo?
How can one determine the number of failures?

java – decomposes the JSON array into its components

Hello everyone, I'm talking to you to see if they can help me.
I have a JSON file (data.json) with the structure:

[
{
“cli_nombre”: “Miguel”,
“cli_tel1”: “”,
“cli_tel2”: “723223319805”,
“cli_apellidos”: “lopez”,
“prov_id”: “1”,
“descripcion”: “antonia_NAVARRO_72231_0_0_1_1_1”,
“ssid”: “”,
“clavewifi”: “”
},
{
“cli_nombre”: “Francisca”,
“cli_tel1”: “952236146458”,
“cli_tel2”: “663338821642”,
“cli_apellidos”: “gomez”,
“prov_id”: “2”,
“descripcion”: “joseA_NAVARRO_LE_0_0_1_1_1”,
“ssid”: “”,
“clavewifi”: “”
},
….
]

and I want to have fields one after another to handle them … I work in Java and have tried it in different ways, but I can not get it …
The idea is to individually retrieve the keys and values ​​that exist in the file for later use in other applications …

I thank all of you

Java – Is there a way to reference a Unity UI object in native code?

Thanks for responding to Game Development Stack Exchange!

  • Please be sure too answer the question, Provide details and share your research!

But avoid

  • Ask for help, clarification or answering other questions.
  • Make statements based on opinions; Cover them with references or personal experience.

Use MathJax to format equations. Mathjax reference.

For more information, see our tips for writing great answers.

java – Changes the value of the superclass by using the subclassing method

My sacar () does not work, it does not change the amount of the credit.
I pay directly with the superclass method (CuentaBancaria), sacar () belongs to the class ContaPoupanca, which extends the superclass, but I say super.getSaldo (), and yet the value of the service is not discounted.

When I use this.getSoldo () or super.getSaldo (), Eclipse shows that the reference is in the AccountBank class, but the subtraction does not occur when I run it.

public class AccountBancaria {

private double balance;

public double getSo () {
Repay the balance;
}
public void setSaldo (Double Balance) {
this.saldo = balance;
}

public void deposit (double value) {
this.saldo + = value;
}

@Override
public String toString () {
return "Balance:" + balance;
}
}
public class ContaPoupanca extends AccountBancaria {

private int dayDay;

public int getDelivery () {
return diaRendimento;
}
public void setDayRender (int dayRender) {
this.diaRendimento = diaRendimento;
}

public nullity (double value) {
if (value < super.getSaldo()) {
            super.setSaldo(super.getSaldo() - valor);
            System.out.println("Saque realizado com sucesso!nSaldo: " + super.getSaldo());
        } else {
            System.out.println("Saldo insuficiente.nSaldo: " + super.getSaldo());
        }
    }

    public void calcularNovoSaldo(int dia) {
        if (dia >= 15) {
System.out.println ("Yield:" + (this.getSoldo () + 100));
} else {
System.out.println ("No Revenue Account Balance:" + this.getSo ());
}
}
}
public class Ex01 {

public static void main (String[] Arguments) {

Scanner scan = new scanner (System.in);

AccountBancaria account = new AccountBancaria ();
ContaPoupanca savings = new ContaPoupanca ();

Boolean exit = false;

while (!) go {
System.out.println ("1st deposit");
System.out.println ("2. Remove");
System.out.println ("Account Balance");
System.out.print ("0. Exit  nType the option:");
int option = scan.nextInt ();
System.out.println ();
if (option == 1) {
System.out.print ("Enter deposit amount:");
account.setSaldo (scan.nextDouble ());
} else if (option == 2) {
System.out.print ("Enter the value of the service:");
double value = scan.nextDouble ();
Save (value);
} else if (option == 3) {
System.out.println (account);
} else if (option == 0) {
System.out.println ("Exiting.");
exit = true;
}
System.out.println ();

}


scan.close ();
}

Develop Android apps for you for $ 20

Develop Android apps for you

If you need someone to develop an Android app then you are in the right place. I'm creating native Android apps for you.

I am an expert in the following areas:

  • Music apps
  • Calculator Apps
  • Image App
  • Database App
  • Quiz App
  • Web App

My goal:

  • Best running app
  • Attractive layout design
  • Best work functions
  • good quality
  • App provided with full request of the user

You can see that my demo of images works

Many Thanks

,

java – Creates a node tree from a list of paths

I have this list of paths:

private static final list path = Arrays.asList (
"assets / css / custom.css",
"assets / css / default.css",
"assets / js / main.js",
"assets / js / old / main-old.js",
"fonts / poppins.woff",
"Favicon.ico"
"Index.html"
);

That I need to create a searchable tree as follows:

Enter image description here

and here is what I have now:

public void testCreateTree () {
Node root = new node ("ROOT", null, Node.NODE_TYPE.ROOT);
paths.forEach (path -> {
last node[] currentNode = {root};
if (! path.contains ("/")) {// root files
currentNode[0].addChild (new node (path, current node[0], Node.NODE_TYPE.FILE));
} else {
String folders = DirectoryRegex.matchFolders (path); // e.g. Matches / Returns "root /"
String fileName = DirectoryRegex.matchFile (path); // e.g. matches / returns index.html
string[] folderArrays = folders.split ("/");
Arrays.asList (folderArrays) .forEach (Folder -> {
Node node = new Node ("ROOT", null, Node.NODE_TYPE.ROOT);
node.setNodeName (folder);
node.setNodeType (Node.NODE_TYPE.FOLDER);
node.setParent (currentNode[0]);
// check if child exists
Node existingNode = currentNode[0].getChild (folder, Node.NODE_TYPE.FOLDER);
if (existingNode == null) {
existingNode = node;
currentNode[0].addChild (node);
}
currentNode[0] = existingNode;
});
currentNode[0].addChild (new node (filename, current node[0], Node.NODE_TYPE.FILE));
}

});
String print = root.printNodeJSON (). ToString ();
Console.log (print);
}

The Node.java Class is this:

public class node {
public NODE_TYPE getNodeType () {
return nodeType;
}

public void setNodeType (NODE_TYPE nodeType) {
this.nodeType = nodeType;
}

public Node getParent () {
Return parent;
}

public void setParent (Node parent) {
this.parent = parent;
}

public list getChildren () {
if (children == null) {
children = new LinkedList <> ();
}
Return children;
}

public void setChildren (List Children) {
this.children = children;
}

public void addChild (Node child) {
getChildren (). add (child);
}

public Node getChild (String nodeName, NODE_TYPE nodeType) {
last node[] child = {null};
getChildren (). forEach (node ​​-> {
if (node.getNodeName (). matches (nodeName) && node.getNodeType (). matches (nodeType)) {
child[0] = Node;
}
});
Return child[0];
}

public String getNodeName () {
return nodeName;
}

public void setNodeName (String nodeName) {
this.nodeName = nodeName;
}

private node () {}

public node (string node-name, parent-node, NODE_TYPE node-type) {
setNodeName (nodeName);
setNodeType (nodeType);
setParent (parent);
}

public enumeration NODE_TYPE {FILE, FOLDER, ROOT}
private NODE_TYPE nodeType;
Parent of the private node;
private list Children;
private string nodeName;

public String printNode () {
last string[] s = {"[ "};

s[0] = s[0] + "Node name:" + node name + ",";
if (nodeType! = null) {
s[0] = s[0] + "Node type:" + nodeType.toString () + ",";
}
if (getParent ()! = null) {
s[0] = s[0] + "Node Parent: [ name = " + getParent().getNodeName() + ", type = " + getParent().getNodeType() + " ]";
}
s[0] = s[0] + "Nodal children:[ ";
getChildren (). forEach (child -> {
s[0] = "["+S["+S["+s["+s[0] + child.printNode () + "]";
});
s[0] = s[0] + "]";

s[0] = s[0] + "]";
returns[0];
}

public JSONObject printNodeJSON () {
JSONObject jsonObject = new JSONObject ();
jsonObject.put ("node name", node name);
jsonObject.put ("nodeType", nodeType! = null? nodeType.toString (): null);
jsonObject.put ("parent", getParent ()! = null? getParent (). printNodeJSONWithoutChildren (): null);
JSONArray children = new JSONArray ();
getChildren (). forEach (child -> {
children.put (child.printNodeJSON ());
});
jsonObject.put ("children", children);
return jsonObject;
}

public JSONObject printNodeJSONWithoutChildren () {
JSONObject jsonObject = new JSONObject ();
jsonObject.put ("node name", node name);
jsonObject.put ("nodeType", nodeType! = null? nodeType.toString (): null);
jsonObject.put ("parent", getParent ()! = null? getParent (). printNodeJSONWithoutChildren (): null);
// JSONArray children = new JSONArray ();
// getChildren (). forEach (child -> {
// children.put (child.printNodeJSON ());
//});
// jsonObject.put ("children", children);
return jsonObject;
}

}

The code works fine, but I want to know how it works most efficiently.

java scanner does not recognize entries

I'm doing an exercise in Java. I can not recognize my income. Where is the mistake?

public static void main (String[] Arguments) {
Scanner sc = new scanner (System.in);
Point p = new point ();
String address = "";
int steps = 0;
String exit = "";

System.out.println ("Where do you want to move the point  n");
do
System.out.println ("Right " D  ":  n" +
Left  "I ":  n "+
"Up " A  ":  n" +
Downwards "B" :);
Address = sc.next ();

System.out.println ("Enter the number of steps:");
steps = sc.nextInt ();

if (address == "D") {
p.SetX (steps);
} else if (address == "I") {
p.SetX (-steps);
} else if (address == "A") {
p.SetY (steps);
} else if (address == "B") {
p.SetY (steps);
}
int CoordX = p.GetX ();
int CoordY = p.GetY ();
System.out.println ("Current Position: (" + CoordX + "," + CoordY + ")");
System.out.println ("Press to exit " S  ");
exit = sc.next ();
} while (exit! = "S");
}

I declare that I have transferred the appropriate amount to the scanner. I do not show the class point, because Netbean does not show me a bug there.
When I execute it, I enter a value, eg: D and 7, so I should show the position (7.0), but it shows (0,0). I also do not recognize the letter S to get out.