How to Put String Variables to Good Use in Java

By Barry A. Burd

The Java program below takes the user’s input and echoes it back on the screen. This is a wonderful program, but (like many college administrators) it doesn’t seem to be particularly useful.

Take a look at a more useful application of Java’s String type.

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();

}

}

A run of the code in is shown below. The code stores Barry A. Burd in a variable called fullName and displays the fullName variable’s content as part of the output. To make this program work, you have to store Barry A. Burd somewhere. After all, the program follows a certain outline:

Get a name.

Get some other stuff.

Compute the total.

Display the name (along with some other stuff).

making a purchase in java
Making a purchase.

If you don’t have the program store the name somewhere, by the time it’s done getting other stuff and computing the total, it forgets the name (so the program can’t display the name).