-1

I am making a code that stores sport scores and matches through user input however I have used a string array to store both string and int value - while this did not seem to be a problem at first I have realized that validation becomes tedious as you can equally store a string in the "score" section even though it is incorrect.

I wish to additionally record the amount of points scored from each team but I cannot add together two strings to get a int value, that's my problem.

The user input looks like this;

Home_Team : Away_Team : Home_ Score : Away Score

I want to be able to add all the Away/Home scores to produce an output like so;

Total Home score: x

Total Away Score: x

Here is my for loop so far,

for (int i = 0; i < counter; i++) { // A loop to control the Array
    String[] words = football_list[i].split(":"); // Splits the input
    if (words.length == 4) {
    System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " ["+ words[3].trim() + "]"); 
    }else{
    System.out.println("Your input was not valid.");
    matches--;
    invalid++;

The logic for my new code will be "If Element[] does not contain an int value print "Invalid input"

Tino Uchiha
  • 53
  • 1
  • 10

2 Answers2

3

"I wish to additionally record the amount of points scored from each team but I cannot add together two strings to get a int value, that's my problem."

To make an integer from a String, use this :

    int x = Integer.parseInt( some_string );
wotyas
  • 91
  • 3
0

Java Split String Into Array Of Integers Example


public class Test {
       public static void main(String[] args) {
                   String sampleString = "101,203,405";
                    String[] stringArray = sampleString.split(",");
                     int[] intArray = new int[stringArray.length];
                     for (int i = 0; i < stringArray.length; i++) {
                       String numberAsString = stringArray[i];
                        intArray[i] = Integer.parseInt(numberAsString);
                      }
                     System.out.println("Number of integers: " + intArray.length);
                     System.out.println("The integers are:");
                     for (int number : intArray) {
                        System.out.println(number);
                     }
                  }
               }

Here is the output of the code:

Number of integers: 3
The integers are:
101
203
405
B Karthik Kumar
  • 230
  • 1
  • 8