Ask User if They Want to Run Program Again Java

Chapter 3  Input and output

The programs nosotros've looked at so far but display messages, which doesn't involve a lot of real computation. This chapter will show yous how to read input from the keyboard, use that input to summate a result, then format that result for output.

3.i  The System class

We accept been using Organization.out.println for a while, only yous might non have idea about what it means. Organisation is a class that provides methods related to the "organization" or environment where programs run. It as well provides System.out, which is a special value that provides methods for displaying output, including println.

In fact, nosotros tin use Arrangement.out.println to display the value of System.out:

System.out.println(System.out);

The outcome is:

java.io.PrintStream@685d72cd

This output indicates that Organization.out is a PrintStream, which is defined in a package chosen java.io. A package is a drove of related classes; coffee.io contains classes for "I/O" which stands for input and output.

The numbers and messages after the @ sign are the address of System.out, represented as a hexadecimal (base of operations 16) number. The address of a value is its location in the calculator'due south memory, which might be different on unlike computers. In this example the accost is 685d72cd, but if you run the same code you might get something different.

Equally shown in Effigy 3.1, System is defined in a file called System.coffee, and PrintStream is defined in PrintStream.java. These files are function of the Java library, which is an extensive drove of classes y'all tin apply in your programs.

Effigy 3.1: System.out.println refers to the out variable of the System class, which is a PrintStream that provides a method called println.

three.2  The Scanner class

The Organization class too provides the special value System.in, which is an InputStream that provides methods for reading input from the keyboard. These methods are not easy to utilise; fortunately, Coffee provides other classes that make it easier to handle common input tasks.

For instance, Scanner is a grade that provides methods for inputting words, numbers, and other information. Scanner is provided by coffee.util, which is a package that contains classes so useful they are called "utility classes". Before yous can use Scanner, y'all have to import it like this:

import java.util.Scanner;

This import argument tells the compiler that when you say Scanner, yous mean the i defined in java.util. Information technology'southward necessary because in that location might be another class named Scanner in another packet. Using an import statement makes your code unambiguous.

Import statements can't be inside a course definition. By convention, they are unremarkably at the starting time of the file.

Adjacent you have to create a Scanner:

Scanner in = new Scanner(System.in);

This line declares a Scanner variable named in and creates a new Scanner that takes input from Organisation.in.

Scanner provides a method chosen nextLine that reads a line of input from the keyboard and returns a String. The following case reads two lines and repeats them dorsum to the user:

If you lot omit the import statement and later refer to Scanner, you will get a compiler error like "cannot find symbol". That ways the compiler doesn't know what you lot mean by Scanner.

Yous might wonder why we can employ the System form without importing it. Organization belongs to the coffee.lang parcel, which is imported automatically. Co-ordinate to the documentation, java.lang "provides classes that are central to the pattern of the Java programming linguistic communication." The String class is also part of the java.lang package.

iii.three  Programme structure

At this point, we accept seen all of the elements that make upwardly Java programs. Figure 3.2 shows these organizational units.

Figure three.2: Elements of the Java language, from largest to smallest.

To review, a package is a collection of classes, which define methods. Methods contain statements, some of which incorporate expressions. Expressions are fabricated upwards of tokens, which are the basic elements of a programme, including numbers, variable names, operators, keywords, and punctuation like parentheses, braces and semicolons.

The standard edition of Java comes with several k classes yous tin import , which can exist both exciting and intimidating. Yous can browse this library at http://docs.oracle.com/javase/8/docs/api/. Most of the Java library itself is written in Coffee.

Note there is a major departure between the Java language, which defines the syntax and pregnant of the elements in Figure iii.ii, and the Java library, which provides the built-in classes.

three.4  Inches to centimeters

Now let'due south see an example that's a little more than useful. Although nigh of the world has adopted the metric organisation for weights and measures, some countries are stuck with English language units. For example, when talking with friends in Europe about the weather, people in the U.s.a. might have to convert from Celsius to Fahrenheit and back. Or they might want to catechumen height in inches to centimeters.

We can write a program to assist. We'll use a Scanner to input a measurement in inches, convert to centimeters, and and so display the results. The following lines declare the variables and create the Scanner:

int inch; double cm; Scanner in = new Scanner(System.in);

The next step is to prompt the user for the input. We'll use print instead of println so they can enter the input on the same line as the prompt. And we'll utilize the Scanner method nextInt, which reads input from the keyboard and converts it to an integer:

Organization.out.print("How many inches? "); inch = in.nextInt();

Adjacent we multiply the number of inches by 2.54, since that's how many centimeters there are per inch, and display the results:

cm = inch * 2.54; System.out.print(inch + " in = "); System.out.println(cm + " cm");

This code works correctly, just information technology has a minor problem. If another programmer reads this code, they might wonder where ii.54 comes from. For the do good of others (and yourself in the future), information technology would exist ameliorate to assign this value to a variable with a meaningful proper name. Nosotros'll demonstrate in the next section.

3.five  Literals and constants

A value that appears in a program, like ii.54 (or " in =" ), is chosen a literal. In general, there's zip wrong with literals. But when numbers like 2.54 appear in an expression with no explanation, they brand code hard to read. And if the aforementioned value appears many times, and might have to modify in the future, it makes code hard to maintain.

Values like that are sometimes called magic numbers (with the implication that existence "magic" is not a good matter). A adept practice is to assign magic numbers to variables with meaningful names, similar this:

double cmPerInch = 2.54; cm = inch * cmPerInch;

This version is easier to read and less mistake-decumbent, merely it still has a problem. Variables can vary, just the number of centimeters in an inch does non. Once we assign a value to cmPerInch, information technology should never change. Java provides a language feature that enforces that rule, the keyword final .

final double CM_PER_INCH = 2.54;

Declaring that a variable is final means that information technology cannot be reassigned once it has been initialized. If y'all try, the compiler reports an mistake. Variables alleged every bit final are called constants. Past convention, names for constants are all capital letter, with the underscore graphic symbol (_) between words.

three.vi  Formatting output

When y'all output a double using print or println, it displays upwards to 16 decimal places:

System.out.impress(4.0 / three.0);

The result is:

That might be more you want. System.out provides another method, called printf, that gives you lot more control of the format. The "f" in printf stands for "formatted". Here'south an example:

Organization.out.printf("4 thirds = %.3f", four.0 / 3.0);

The first value in the parentheses is a format string that specifies how the output should be displayed. This format string contains ordinary text followed by a format specifier, which is a special sequence that starts with a per centum sign. The format specifier \%.3f indicates that the following value should exist displayed every bit floating-point, rounded to three decimal places. The issue is:

The format string tin can comprise any number of format specifiers; here'southward an instance with two:

int inch = 100; double cm = inch * CM_PER_INCH; System.out.printf("%d in = %f cm\n", inch, cm);

The outcome is:

Like print, printf does not append a newline. So format strings often terminate with a newline character.

The format specifier \%d displays integer values ("d" stands for "decimal"). The values are matched up with the format specifiers in social club, and so inch is displayed using \%d, and cm is displayed using \%f.

Learning virtually format strings is like learning a sub-linguistic communication inside Java. In that location are many options, and the details can be overwhelming. Table three.1 lists a few common uses, to requite you an idea of how things work. For more details, refer to the documentation of java.util.Formatter. The easiest style to find documentation for Java classes is to do a web search for "Java" and the name of the class.

\%d decimal integer 12345
\%08d padded with zeros, at least eight digits wide 00012345
\%f floating-point 6.789000
\%.2f rounded to ii decimal places 6.79

Table 3.i: Example format specifiers

3.vii  Centimeters to inches

At present suppose we have a measurement in centimeters, and we want to round information technology off to the nearest inch. It is tempting to write:

inch = cm / CM_PER_INCH; // syntax mistake

But the outcome is an error – you get something similar, "Bad types in assignment: from double to int." The problem is that the value on the right is floating-point, and the variable on the left is an integer.

The simplest way to catechumen a floating-point value to an integer is to use a blazon cast, so called considering information technology molds or "casts" a value from ane type to another. The syntax for type casting is to put the name of the type in parentheses and use it as an operator.

double pi = iii.14159; int x = (int) pi;

The (int) operator has the event of converting what follows into an integer. In this instance, 10 gets the value 3. Like integer division, converting to an integer always rounds toward zero, even if the fraction role is 0.999999 (or -0.999999). In other words, it simply throws away the fractional role.

Type casting takes precedence over arithmetic operations. In this instance, the value of pi gets converted to an integer before the multiplication. And so the result is 60.0, not 62.0.

double pi = 3.14159; double x = (int) pi * twenty.0;

Keeping that in heed, here's how nosotros can convert a measurement in centimeters to inches:

inch = (int) (cm / CM_PER_INCH); System.out.printf("%f cm = %d in\n", cent, inch);

The parentheses after the cast operator crave the partition to happen before the type cast. And the upshot is rounded toward zero; we will see in the next chapter how to round floating-point numbers to the closest integer.

3.8  Modulus operator

Allow's take the instance one footstep further: suppose y'all take a measurement in inches and y'all want to convert to anxiety and inches. The goal is divide by 12 (the number of inches in a foot) and keep the remainder.

We have already seen the sectionalization operator (/), which computes the quotient of 2 numbers. If the numbers are integers, information technology performs integer partitioning. Coffee also provides the modulus operator (\%), which divides two numbers and computes the remainder.

Using division and modulus, we can catechumen to feet and inches like this:

caliber = 76 / 12; // division remainder = 76 % 12; // modulus

The first line yields 6. The second line, which is pronounced "76 modern 12", yields 4. Then 76 inches is 6 anxiety, 4 inches.

The modulus operator looks like a percentage sign, simply you lot might discover information technology helpful to think of it as a division sign (÷) rotated to the left.

The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another: if x \% y is zero, then x is divisible by y. You lot can apply modulus to "excerpt" digits from a number: x \% ten yields the rightmost digit of x, and x \% 100 yields the terminal two digits. Too, many encryption algorithms use the modulus operator extensively.

3.9  Putting it all together

At this point, you have seen enough Java to write useful programs that solve everyday problems. You lot can (1) import Java library classes, (two) create a Scanner, (3) get input from the keyboard, (4) format output with printf, and (5) divide and mod integers. Now nosotros volition put everything together in a complete program:

Although not required, all variables and constants are alleged at the top of main. This practice makes it easier to find their types afterwards on, and information technology helps the reader know what data is involved in the algorithm.

For readability, each major footstep of the algorithm is separated by a blank line and begins with a comment. It also includes a documentation comment ( /** ), which we'll larn more near in the next chapter.

Many algorithms, including the Convert program, perform sectionalization and modulus together. In both steps, you divide by the aforementioned number (IN_PER_FOOT).

When statements get long (generally wider than lxxx characters), a mutual style convention is to break them across multiple lines. The reader should never have to scroll horizontally.

3.10  The Scanner issues

Now that you've had some feel with Scanner, in that location is an unexpected behavior nosotros want to warn you lot about. The following code fragment asks users for their proper name and age:

System.out.print("What is your name? "); name = in.nextLine(); System.out.print("What is your historic period? "); age = in.nextInt(); System.out.printf("Hi %s, age %d\n", name, age);

The output might wait something similar this:

Hi Grace Hopper, age 45

When yous read a String followed by an int , everything works just fine. But when you read an int followed by a Cord, something strange happens.

System.out.impress("What is your age? "); age = in.nextInt(); System.out.print("What is your name? "); proper noun = in.nextLine(); System.out.printf("Hullo %s, age %d\n", name, age);

Try running this example code. It doesn't let you input your name, and information technology immediately displays the output:

What is your proper noun? Hello , age 45

To empathize what is happening, you have to understand that the Scanner doesn't see input equally multiple lines, like we practise. Instead, it gets a "stream of characters" as shown in Effigy 3.3.

Figure 3.3: A stream of characters as seen past a Scanner.

The arrow indicates the next character to exist read by Scanner. When y'all call nextInt, it reads characters until information technology gets to a not-digit. Effigy 3.4 shows the state of the stream subsequently nextInt is invoked.

Figure 3.4: A stream of characters afterwards nextInt is invoked.

At this indicate, nextInt returns 45. The plan then displays the prompt "What is your name? " and calls nextLine, which reads characters until it gets to a newline. Just since the side by side character is already a newline, nextLine returns the empty cord "" .

To solve this problem, you need an extra nextLine later on nextInt.

System.out.impress("What is your age? "); age = in.nextInt(); in.nextLine(); // read the newline System.out.print("What is your name? "); name = in.nextLine(); System.out.printf("Hello %south, historic period %d\n", name, age);

This technique is common when reading int or double values that appear on their own line. Showtime you read the number, and then you read the residuum of the line, which is just a newline character.

three.11  Vocabulary

package:
A grouping of classes that are related to each other.
address:
The location of a value in calculator memory, frequently represented as a hexadecimal integer.
library:
A collection of packages and classes that are available for utilize in other programs.
import statement:
A argument that allows programs to use classes defined in other packages.
token:
A basic element of a program, such equally a give-and-take, space, symbol, or number.
literal:
A value that appears in source code. For example, "Hello" is a string literal and 74 is an integer literal.
magic number:
A number that appears without explanation equally part of an expression. It should generally be replaced with a abiding.
constant:
A variable, declared final , whose value cannot be inverse.
format cord:
A string passed to printf to specify the format of the output.
format specifier:
A special code that begins with a percent sign and specifies the data type and format of the corresponding value.
blazon bandage:
An operation that explicitly converts one data type into another. In Java it appears as a blazon name in parentheses, like (int).
modulus:
An operator that yields the remainder when one integer is divided by some other. In Java, it is denoted with a percent sign; for example, 5 \% 2 is 1.

3.12  Exercises

The code for this affiliate is in the ch03 directory of ThinkJavaCode. See folio ?? for instructions on how to download the repository. Before y'all offset the exercises, nosotros recommend that you compile and run the examples.

If you have not already read Appendix A.3, now might exist a adept fourth dimension. It describes the command-line interface, which is a powerful and efficient manner to interact with your reckoner.

Exercise 1 When you lot use printf, the Java compiler does not cheque your format cord. Run across what happens if yous try to display a value with type int using \%f. And what happens if you lot display a double using \%d? What if yous utilize two format specifiers, but then but provide ane value?

Exercise 2 Write a program that converts a temperature from Celsius to Fahrenheit. It should (1) prompt the user for input, (two) read a double value from the keyboard, (3) summate the result, and (iv) format the output to one decimal identify. For example, it should display "24.0 C = 75.2 F".

Here is the formula. Be careful not to utilize integer partition!

Practise 3 Write a program that converts a total number of seconds to hours, minutes, and seconds. It should (ane) prompt the user for input, (2) read an integer from the keyboard, (3) calculate the result, and (4) use printf to display the output. For example, "5000 seconds = 1 hours, 23 minutes, and 20 seconds".

Hint: Utilise the modulus operator.

Exercise 4 The goal of this exercise is to program a "Approximate My Number" game. When information technology's finished, it will piece of work similar this:

I'm thinking of a number between 1 and 100 (including both). Can you guess what information technology is? Type a number: 45 Your guess is: 45 The number I was thinking of is: 14 You were off past: 31

To choose a random number, you can use the Random class in java.util. Here'south how information technology works:

Like the Scanner course we saw in this chapter, Random has to exist imported before we tin can utilize it. And every bit we saw with Scanner, we have to employ the new operator to create a Random (number generator).

And then we can use the method nextInt to generate a random number. In this case, the upshot of nextInt(100) will exist between 0 and 99, including both. Adding one yields a number betwixt i and 100, including both.

  1. The definition of GuessStarter is in a file called GuessStarter.coffee, in the directory called ch03, in the repository for this volume.
  2. Compile and run this program.
  3. Change the program to prompt the user, then employ a Scanner to read a line of user input. Compile and test the plan.
  4. Read the user input as an integer and brandish the effect. Once more, compile and test.
  5. Compute and display the difference between the user's guess and the number that was generated.

smithlowee1994.blogspot.com

Source: https://books.trinket.io/thinkjava/chapter3.html

0 Response to "Ask User if They Want to Run Program Again Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel