Java Arena
Step 6 of 8

Data in a fixed format

Programs often read data in which every line has the same shape: a name and a score, or a city and a temperature. The values are separated by a character that doesn't appear in the values themselves, often a comma or a semicolon:

Mira,87
Otto,92

Each line is split at the separator, and the parts are picked out by their index. The parts are Strings, so a number has to be turned into an int with Integer.valueOf (or into a double with Double.valueOf) before you can calculate with it:

String line = "Mira,87";
String[] parts = line.split(",");
String name = parts[0];
int score = Integer.valueOf(parts[1]);
System.out.println(name + " scored " + score);
System.out.println("With the bonus: " + (score + 5));
Output
Mira scored 87
With the bonus: 92

Without Integer.valueOf, parts[1] + 5 would join the two as text and give 875.

Decimal numbers separated by semicolons work the same way:

String line = "Oulu;-4.5";
String[] parts = line.split(";");
double temperature = Double.valueOf(parts[1]);
if (temperature < 0) {
    System.out.println(parts[0] + " is below freezing");
}
Output
Oulu is below freezing

A space too many

Data typed by people isn't always tidy. If a line has a space after the comma, the second part starts with that space, and Integer.valueOf refuses it:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String line = scanner.nextLine();
        String[] parts = line.split(",");
        int score = Integer.valueOf(parts[1]);
        System.out.println(parts[0] + ": " + score);
    }
}
Input
Mira, 87
The program crashes with
Exception in thread "main" java.lang.NumberFormatException: For input string: " 87"
	at Main.main(Main.java:8)

The quotes in the message show the culprit: the text was " 87", with a space in front. trim() removes it, so Integer.valueOf(parts[1].trim()) works whether the space is there or not.

A line with no comma at all splits into just one part, and parts[1] then crashes with an ArrayIndexOutOfBoundsException. When the input might have lines like that, check parts.length before you use the parts.

Your task

Challenge 1 of 3

A training app saves lines such as running,35: an activity and how many minutes it took. Fill in the blanks, so the program reads one such line and prints the activity and its length in minutes and in seconds. For the input running,35 it prints:

running for 35 minutes
That's 2100 seconds

Challenge 2

Write a method toMinutes(String time) that turns a length of time written as hours and minutes, such as 2:45, into minutes. There may be spaces around the numbers, as in 1 : 15. The check runs System.out.println(toMinutes("2:45")); and expects:

165

Challenge 3

What does this program print? Watch when the parts are text and when they're numbers.