Part 3

Using strings

Let's first revise what we already know about Strings and see how to split them. Below we create a String variable magicWord, that contains value "abracadabra".

String magicWord = "abracadabra";

Passing a String as a parameter to a print command (or, for that matter, any method that takes a String parameter) happens in the familiar way:

String magicWord = "abracadabra";
System.out.println(magicWord);
Sample output

abracadabra

Reading and Printing Strings

You can read a string using the nextLine-method offered by Scanner. The program below reads the name of the user and prints it:

Scanner reader = new Scanner(System.in);

System.out.print("What's your name? ");
// reading a line from the user and assigning it to the name variable
String name = reader.nextLine();

System.out.println(name);
Sample output

What's your name? Vicky Vicky

Strings can also be concatenated. If you place a +-operator between two strings, you get a new string that's a combination of those two strings. Be mindful of any white spaces in your variables!

String greeting = "Hi ";
String name = "Lily";
String goodbye = " and see you later!";

String phrase = greeting + name + goodbye;

System.out.println(phrase);
Sample output

Hi Lily and see you later!

Loading

String Comparisons And "Equals"

Strings can't be compared with with the equals operator - ==. For strings, there exists a separate equals-command, which is always appended to the end of the string that we want to compare.

String text = "course";

if (text.equals("marzipan")) {
    System.out.println("The text variable contains the text marzipan.");
} else {
    System.out.println("The text variable does not contain the text marzipan.");
}
The `equals` command is always appended to the end of the string that we want to compare, "string variable dot equals some text". You can also compare a string variable to another string variable.
String text = "course";
String anotherText = "horse";

if (text.equals(anotherText)) {
    System.out.println("The two texts are equal!");
} else {
    System.out.println("The two texts are not equal!");
}

When comparing strings, you should make sure the string variable has some value assigned to ti. If it doesn't have a value, the program will produce a NullPointerException error, which means that no value has been assigned to the variable, or that it is empty (null).

As we've come to know, a boolean value can be inverted through negation - !.

System.out.println("Make sure the text is not 'cake'");
String text = "pie";

if (!(text.equals("cake"))) {  // true if the condition text.equals("cake") is false
    System.out.println("it wasn't!");
} else {
    System.out.println("it was!");
}
Sample output

it wasn't!

Loading
Loading

Splitting a String

You can split a string to multiple pieces with the split-method of the String class. The method takes as a parameter a string denoting the place around which the string should be split. The split method returns an array of the resulting sub-parts. In the example below, the string has been split around a space.

String text = "first second third fourth";
String[] pieces = text.split(" ");
System.out.println(pieces[0]);
System.out.println(pieces[1]);
System.out.println(pieces[2]);
System.out.println(pieces[3]);

System.out.println();

for (int i = 0; i < pieces.length; i++) {
    System.out.println(pieces[i]);
}
Sample output

first second third fourth

first second third fourth

Loading
Loading

Data of Fixed Format

Splitting strings is used particularly when the data is of a fixed format. This refers to data that adheres to some predefined format. An example of this of this is the comma-separated values (csv) format, where commas are used to separate values. Belowm you'll find an example of data in csv form containing names and ages. The first column contains names and the second one ages. The columns are separed by a comma.

Sample data

sebastian,2 lucas,2 lily,1

Let's assume the user enters the data above row by row, ending with an empty line.

A program to print the names and ages looks like the following:

Scanner reader = new Scanner(System.in);

while (true) {
    String input = reader.nextLine();
    if (input.equals("")) {
        break;
    }

    String[] pieces = input.split(",");
    System.out.println("Name: " + pieces[0] + ", age: " + pieces[1]);
}
Sample output

sebastian,2 Name: sebastian, age: 2 lucas,2 Name: lucas, age: 2 lily,1 Name: lily, age: 1

Loading
Loading

Using Diverse Text

We've printed strings in the examples above. Some of the data contained in a fixed-format string can be numerical. In the previous data we used that contained names and ages, the ages were integers.

Sample data

sebastian,2 lucas,2 lily,1

Splitting a string always produces an array of strings. If the text is of fixed format, we can assume the data in a specific index to always be of the a specific type — e.g., in the example above, age at index 1 is an integer.

The program below computes the sum of ages in this fixed format data. In order to compute the sum, the age must first be converted to a number (the familiar command Integer.valueOf())

Scanner reader = new Scanner(System.in);
int sum = 0;

while (true) {
    String input = reader.nextLine();
    if (input.equals("")) {
        break;
    }

    String[] parts = input.split(",");
    sum = sum + Integer.valueOf(parts[1]);
}

System.out.println("Sum of the ages is " + sum);
Sample output

sebastian,2 lucas,2 lily,1

Sum of the ages is 5

We can write a program to compute the average of the ages in the same way:

Scanner reader = new Scanner(System.in);
int sum = 0;
int count = 0;

while (true) {
    String input = reader.nextLine();
    if (input.equals("")) {
        break;
    }

    String[] parts = input.split(",");
    sum = sum + Integer.valueOf(parts[1]);
    count = count + 1;
}

if (count > 0) {
    System.out.println("Age average: " + (1.0 * sum / count));
} else {
    System.out.println("No input.");
}
Sample output

sebastian,2 lucas,2 lily,1

Age average: 1.666

Loading
Loading
Loading
You have reached the end of this section! Continue to the next section:

Remember to check your points from the ball on the bottom-right corner of the material!