Reading and Writing Strings in Java - dummies

By Barry A. Burd

A String is a bunch of characters in Java. It’s like having several char values in a row. To read a String value from the keyboard, you can call either next or nextLine:

  • The methodnextreads up to the next blank space.

For example, with the input Barry A. Burd, the statements

String firstName = keyboard.next();

String middleInit = keyboard.next();

String lastName = keyboard.next();

assign Barry to firstName, A. to middleInit, and Burd to lastName.

  • The method<code>nextLinereads up to the end of the current line.

For example, with input Barry A. Burd, the statement

String fullName = keyboard.nextLine();

assigns Barry A. Burd to the variable fullName.

To display a String value, you can call one of your old friends, System.out.print or System.out.println. A statement like

out.print("Customer&apos;s full name: ");

displays the String value "Customer's full name: ".

You can use print and println to write String values to a disk file.

In a Java program, you surround the letters in a String literal with double quote marks.

Adding strings to things

In Java, you can put a plus sign between a String value and a numeric value. When you do, Java turns everything into one big String value. To see how this works, consider the following code.

import java.util.Scanner;

import static java.lang.System.out;

class ProcessMoreData {

public static void main(String args[]) {

Scanner keyboard = new Scanner(System.in);

String fullName;

double amount;

boolean taxable;

double total;

out.print("Customer's full name: ");

fullName = keyboard.nextLine();

out.print("Amount: ");

amount = keyboard.nextDouble();

out.print("Taxable? (true/false) ");

taxable = keyboard.nextBoolean();

if (taxble) {

total = amount * 1.05;

} else {

total = amount;

}

out.println();

out.print("The total for ");

out.print(fullName);

out.print(" is ");

out.print(total);

out.println(".");

keyboard.close();

}

}

Replace the last several lines in of the code below with the following single line:

out.println("The total for " + fullName + " is " + total + ".");

Fun with word order

Write a program that inputs six words from the keyboard. The program outputs six sentences, each with the first word in a different position. For example, the output of one run might look like this:

only I have eyes for you.

I only have eyes for you.

I have only eyes for you.

I have eyes only for you.

I have eyes for only you.

I have eyes for you only.