-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"

2
  • have a look at Integer.parseInt() Commented Jan 8, 2017 at 14:37
  • Wrap the Integer.parseInt() in try-catch block to take care of the Invalid input. It will throw number format exception and you can print "Invalid Input" in catch block. Commented Jan 8, 2017 at 14:40

2 Answers 2

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 );
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.