-1

I'm working through the infamous TDD Bowling Game Example. I have a string as follows. How can I add the first 2 values together to show 3?

 String score = "12|--|--|--|--|--|--|--|--|--|";

I think I convert this to an array of integers, but I'm then unsure how to add the first 2 elements together.

Coder
  • 197
  • 1
  • 17
  • Why would you store points (i.e. whole numbers) in a `String`? – Turing85 Jan 24 '20 at 17:06
  • This should help https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java – Grant Murphy Jan 24 '20 at 17:17
  • 1
    I know this doesn't answer your question, but this looks like a situation where you really shouldn't be storing those numbers in the string in the first place. There's a lot of room for ambiguity here. For instance, can you be sure that the string will always contain exactly two numbers, and that those numbers will always be exactly one digit? Will it never start with "118...", which might be 11 + 8, or 1 + 18? My suggestion would be to examine why those numbers are there in the first place, and find an alternate method to accomplish the same goal that uses multiple int variables. – Jordan Jan 24 '20 at 17:24

1 Answers1

1

You can put value in a int array

and after write a method like that

public void toString(int[] intArray){
String res="";
for (int i=0; i<intArray.length; i++){
    res+=intArray[I];
    res+="|"
}

}

or no parameter is you define your tab in constructor

Xbattlax
  • 109
  • 8
  • Hey thanks for the comment, I made this, just need it to replace the - with a 0 now. public int totalForOneFrame(String score) { String[] items = score.split("\\|"); score.replace("\\--", "0"); int[] results = new int[items.length]; int total = 0; for (int i = 0; i < items.length; i++) { results[i] = Integer.parseInt(items[i]); total += results[i]; } return total; } – Coder Jan 28 '20 at 16:22