Home

How to Put String Variables to Good Use in Java

|
|  Updated:  
2017-10-13 11:38:14
Java Essentials For Dummies
Explore Book
Buy On Amazon
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);

<strong>String fullName;</strong>

double amount;

boolean taxable;

double total;

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

<strong>fullName = keyboard.nextLine();</strong>

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

<strong>out.print(fullName);</strong>

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:

<strong><em>Get a name.</em></strong>

<em>Get some other stuff.</em>

<em>Compute the total.</em>

<strong><em>Display the name</em></strong><em> (along with some other stuff).</em>

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).

About This Article

This article is from the book: 

About the book author: