Ask User if They Want to Run Program Again Java
Chapter iii Input and output
The programs nosotros've looked at so far but brandish messages, which doesn't involve a lot of real computation. This chapter will evidence you lot how to read input from the keyboard, use that input to calculate a result, and then format that result for output.
3.ane The System class
We have been using Organization.out.println
for a while, just you might not take idea most what information technology means. System
is a class that provides methods related to the "system" or environment where programs run. Information technology also provides Organisation.out
, which is a special value that provides methods for displaying output, including println
.
In fact, we can employ Organisation.out.println
to brandish the value of Organization.out
:
System.out.println(System.out);
The event is:
java.io.PrintStream@685d72cd
This output indicates that System.out
is a PrintStream
, which is defined in a package chosen java.io
. A package is a drove of related classes; java.io
contains classes for "I/O" which stands for input and output.
The numbers and letters after the @ sign are the address of System.out
, represented equally a hexadecimal (base sixteen) number. The address of a value is its location in the computer's memory, which might exist different on unlike computers. In this example the accost is 685d72cd
, simply if you run the same lawmaking you might go something different.
As shown in Figure 3.1, System
is defined in a file called System.java, and PrintStream
is divers in PrintStream.java. These files are part of the Java library, which is an extensive collection of classes you lot tin can use in your programs.
![]()
Effigy iii.ane:
System.out.println
refers to theout
variable of theArrangement
course, which is aPrintStream
that provides a method calledprintln
.
iii.two The Scanner class
The Arrangement
form too provides the special value System.in
, which is an InputStream
that provides methods for reading input from the keyboard. These methods are non easy to employ; fortunately, Java provides other classes that make it easier to handle common input tasks.
For example, Scanner
is a class that provides methods for inputting words, numbers, and other data. Scanner
is provided past java.util
, which is a packet that contains classes so useful they are called "utility classes". Before you can employ Scanner
, you take to import it like this:
import java.util.Scanner;
This import argument tells the compiler that when y'all say Scanner
, you hateful the 1 defined in coffee.util
. It's necessary because at that place might exist some other class named Scanner
in some other bundle. Using an import statement makes your code unambiguous.
Import statements can't exist inside a grade definition. By convention, they are commonly at the first of the file.
Next 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 Arrangement.in
.
Scanner
provides a method chosen nextLine
that reads a line of input from the keyboard and returns a String
. The following example reads two lines and repeats them back to the user:
If you omit the import statement and later refer to Scanner
, y'all will become a compiler error like "cannot observe symbol". That means the compiler doesn't know what y'all mean by Scanner
.
Y'all might wonder why we tin use the Organisation
class without importing it. System
belongs to the coffee.lang
package, which is imported automatically. According to the documentation, java.lang
"provides classes that are fundamental to the design of the Java programming language." The Cord
grade is also part of the coffee.lang
package.
3.iii Program structure
At this point, we have seen all of the elements that make upwardly Java programs. Figure 3.2 shows these organizational units.
![]()
Figure iii.two: Elements of the Java language, from largest to smallest.
To review, a parcel is a drove of classes, which define methods. Methods contain statements, some of which contain expressions. Expressions are fabricated up of tokens, which are the basic elements of a program, including numbers, variable names, operators, keywords, and punctuation like parentheses, braces and semicolons.
The standard edition of Coffee comes with several thousand classes you can import
, which tin be both exciting and intimidating. You tin browse this library at http://docs.oracle.com/javase/8/docs/api/. Most of the Java library itself is written in Java.
Note there is a major difference between the Java linguistic communication, which defines the syntax and pregnant of the elements in Figure 3.two, and the Java library, which provides the congenital-in classes.
3.4 Inches to centimeters
Now let's come across an example that'southward a little more useful. Although near of the world has adopted the metric organization for weights and measures, some countries are stuck with English units. For example, when talking with friends in Europe near the weather, people in the United States might have to convert from Celsius to Fahrenheit and dorsum. Or they might want to convert height in inches to centimeters.
We can write a program to help. Nosotros'll use a Scanner
to input a measurement in inches, catechumen to centimeters, and and so display the results. The post-obit lines declare the variables and create the Scanner
:
int inch; double cm; Scanner in = new Scanner(Organization.in);
The next step is to prompt the user for the input. We'll use print
instead of println
so they tin can enter the input on the same line every bit the prompt. And we'll use the Scanner
method nextInt
, which reads input from the keyboard and converts it to an integer:
Organization.out.impress("How many inches? "); inch = in.nextInt();
Next we multiply the number of inches by 2.54, since that'south how many centimeters there are per inch, and display the results:
cm = inch * two.54; Arrangement.out.print(inch + " in = "); Organisation.out.println(cm + " cm");
This code works correctly, but it has a pocket-size problem. If another programmer reads this code, they might wonder where ii.54 comes from. For the benefit of others (and yourself in the future), it would be improve to assign this value to a variable with a meaningful proper name. We'll demonstrate in the next section.
iii.5 Literals and constants
A value that appears in a plan, like 2.54 (or " in ="
), is called a literal. In general, there's nothing wrong with literals. But when numbers like two.54 appear in an expression with no explanation, they make code difficult to read. And if the same value appears many times, and might have to change in the future, information technology makes code hard to maintain.
Values like that are sometimes called magic numbers (with the implication that being "magic" is not a skilful thing). A proficient practice is to assign magic numbers to variables with meaningful names, like this:
double cmPerInch = 2.54; cm = inch * cmPerInch;
This version is easier to read and less error-prone, but information technology still has a problem. Variables can vary, simply the number of centimeters in an inch does not. Once we assign a value to cmPerInch
, it should never modify. Java provides a language characteristic that enforces that rule, the keyword final
.
terminal double CM_PER_INCH = ii.54;
Declaring that a variable is final
means that it cannot exist reassigned once information technology has been initialized. If you try, the compiler reports an fault. Variables declared as final
are called constants. By convention, names for constants are all uppercase, with the underscore character (_
) between words.
iii.6 Formatting output
When you output a double
using print
or println
, information technology displays upward to 16 decimal places:
Arrangement.out.print(four.0 / 3.0);
The result is:
That might exist more than you lot desire. Organization.out
provides another method, called printf
, that gives you lot more control of the format. The "f" in printf
stands for "formatted". Here'due south an example:
Organization.out.printf("Four thirds = %.3f", 4.0 / 3.0);
The offset 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 percent sign. The format specifier \%.3f
indicates that the following value should exist displayed as floating-indicate, rounded to 3 decimal places. The result is:
The format string can contain any number of format specifiers; here's an example with two:
int inch = 100; double cm = inch * CM_PER_INCH; Organization.out.printf("%d in = %f cm\n", inch, cm);
The result is:
Similar print
, printf
does not append a newline. So format strings often end 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 order, so inch
is displayed using \%d
, and cm
is displayed using \%f
.
Learning virtually format strings is like learning a sub-language inside Coffee. There are many options, and the details tin can exist overwhelming. Table iii.1 lists a few mutual uses, to give y'all an idea of how things work. For more details, refer to the documentation of java.util.Formatter
. The easiest fashion 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 to the lowest degree viii digits wide 00012345 \%f
floating-signal 6.789000 \%.2f
rounded to 2 decimal places vi.79 Table 3.1: Example format specifiers
iii.seven Centimeters to inches
At present suppose nosotros have a measurement in centimeters, and we want to round it off to the nearest inch. Information technology is tempting to write:
inch = cm / CM_PER_INCH; // syntax fault
But the consequence is an error – you go something like, "Bad types in assignment: from double to int." The problem is that the value on the correct is floating-indicate, and the variable on the left is an integer.
The simplest manner to convert a floating-point value to an integer is to utilise a type cast, so called considering it molds or "casts" a value from 1 type to some other. The syntax for type casting is to put the name of the type in parentheses and utilize it as an operator.
double pi = iii.14159; int x = (int) pi;
The (int)
operator has the effect of converting what follows into an integer. In this instance, x
gets the value 3
. Like integer division, converting to an integer always rounds toward zippo, even if the fraction office is 0.999999
(or -0.999999
). In other words, information technology merely throws away the fractional part.
Blazon casting takes precedence over arithmetic operations. In this example, the value of pi
gets converted to an integer before the multiplication. So the result is lx.0, not 62.0.
double pi = 3.14159; double x = (int) pi * 20.0;
Keeping that in mind, here's how we 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 require the sectionalization to happen before the type bandage. And the result is rounded toward nada; we will meet in the side by side chapter how to round floating-indicate numbers to the closest integer.
iii.eight Modulus operator
Allow'southward take the example ane step farther: suppose you accept a measurement in inches and you want to catechumen to feet and inches. The goal is divide past 12 (the number of inches in a foot) and keep the residue.
Nosotros have already seen the partitioning operator (/
), which computes the quotient of two numbers. If the numbers are integers, it performs integer division. Coffee as well provides the modulus operator (\%
), which divides ii numbers and computes the rest.
Using division and modulus, we can convert to feet and inches like this:
quotient = 76 / 12; // division residual = 76 % 12; // modulus
The kickoff line yields 6. The second line, which is pronounced "76 mod 12", yields 4. So 76 inches is 6 feet, 4 inches.
The modulus operator looks like a per centum sign, but you might find it helpful to think of it every bit a division sign (÷) rotated to the left.
The modulus operator turns out to be surprisingly useful. For case, you can check whether ane number is divisible by another: if ten \% y
is zero, so x
is divisible past y
. You can use modulus to "extract" digits from a number: x \% 10
yields the rightmost digit of x
, and x \% 100
yields the final two digits. Likewise, many encryption algorithms apply the modulus operator extensively.
3.9 Putting it all together
At this betoken, you have seen enough Java to write useful programs that solve everyday issues. Yous tin (1) import Java library classes, (2) create a Scanner
, (3) get input from the keyboard, (4) format output with printf
, and (5) divide and modern integers. Now we will put everything together in a complete program:
Although not required, all variables and constants are declared at the top of primary
. This exercise makes information technology easier to discover their types afterward, and it 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 annotate. It likewise includes a documentation annotate ( /**
), which we'll larn more than about in the next chapter.
Many algorithms, including the Convert
plan, perform division and modulus together. In both steps, y'all separate by the same number (IN_PER_FOOT
).
When statements get long (mostly wider than fourscore characters), a common fashion convention is to pause them across multiple lines. The reader should never take to scroll horizontally.
3.x The Scanner bug
Now that you've had some feel with Scanner
, at that place is an unexpected behavior nosotros want to warn yous most. The following code fragment asks users for their name and age:
System.out.impress("What is your name? "); name = in.nextLine(); System.out.print("What is your age? "); age = in.nextInt(); System.out.printf("Howdy %s, age %d\north", name, age);
The output might look something like this:
Hello Grace Hopper, age 45
When y'all read a String
followed by an int
, everything works just fine. But when you read an int
followed past a String
, something strange happens.
Organization.out.print("What is your age? "); age = in.nextInt(); System.out.print("What is your name? "); proper name = in.nextLine(); System.out.printf("Hello %s, historic period %d\n", proper noun, age);
Endeavor running this case lawmaking. It doesn't permit you input your proper noun, and it immediately displays the output:
What is your proper noun? Howdy , historic period 45
To empathize what is happening, you have to sympathise that the Scanner
doesn't see input as multiple lines, like we practise. Instead, it gets a "stream of characters" as shown in Figure 3.3.
![]()
Figure three.3: A stream of characters equally seen by a
Scanner
.
The pointer indicates the next character to be read past Scanner
. When you phone call nextInt
, it reads characters until it gets to a non-digit. Figure 3.4 shows the state of the stream later on nextInt
is invoked.
![]()
Figure 3.4: A stream of characters later
nextInt
is invoked.
At this point, nextInt
returns 45
. The program then displays the prompt "What is your proper noun? "
and calls nextLine
, which reads characters until it gets to a newline. But since the next graphic symbol is already a newline, nextLine
returns the empty cord ""
.
To solve this problem, you lot need an extra nextLine
afterwards nextInt
.
System.out.print("What is your age? "); age = in.nextInt(); in.nextLine(); // read the newline Arrangement.out.print("What is your name? "); proper noun = in.nextLine(); System.out.printf("Hello %s, age %d\n", proper name, age);
This technique is common when reading int
or double
values that appear on their own line. First you read the number, so yous read the remainder of the line, which is simply a newline character.
iii.11 Vocabulary
- packet:
- A grouping of classes that are related to each other.
- accost:
- The location of a value in computer memory, oft represented as a hexadecimal integer.
- library:
- A collection of packages and classes that are available for apply in other programs.
- import argument:
- A statement that allows programs to use classes defined in other packages.
- token:
- A bones chemical element of a programme, such as a word, space, symbol, or number.
- literal:
- A value that appears in source code. For case,
"Hello"
is a string literal and74
is an integer literal. - magic number:
- A number that appears without explanation as part of an expression. It should by and large be replaced with a constant.
- constant:
- A variable, alleged
final
, whose value cannot be changed. - 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 information blazon and format of the corresponding value.
- type bandage:
- An operation that explicitly converts one data blazon into some other. In Java information technology appears as a type name in parentheses, similar
(int)
. - modulus:
- An operator that yields the remainder when one integer is divided by some other. In Java, it is denoted with a percentage sign; for example,
5 \% 2
isane
.
3.12 Exercises
The lawmaking for this chapter is in the ch03 directory of ThinkJavaCode. Run into folio ?? for instructions on how to download the repository. Before you kickoff the exercises, nosotros recommend that you compile and run the examples.
If you lot have non already read Appendix A.3, now might be a good time. Information technology describes the control-line interface, which is a powerful and efficient way to collaborate with your computer.
Exercise ane When you use printf
, the Java compiler does not check your format string. See what happens if you try to display a value with type int
using \%f
. And what happens if you lot display a double
using \%d
? What if you apply two format specifiers, but then merely provide 1 value?
Exercise 2 Write a program that converts a temperature from Celsius to Fahrenheit. Information technology should (one) prompt the user for input, (2) read a double
value from the keyboard, (3) calculate the result, and (4) format the output to i decimal place. For example, it should display "24.0 C = 75.2 F".
Hither is the formula. Be careful not to employ integer division!
Exercise 3 Write a programme that converts a total number of seconds to hours, minutes, and seconds. It should (1) 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: Use the modulus operator.
Practise 4 The goal of this practice is to program a "Gauge My Number" game. When it's finished, it will work like this:
I'grand thinking of a number between 1 and 100 (including both). Can yous judge what information technology is? Type a number: 45 Your guess is: 45 The number I was thinking of is: 14 You lot were off by: 31
To choose a random number, you can employ the Random
class in coffee.util
. Here's how information technology works:
Like the Scanner
course nosotros saw in this chapter, Random
has to exist imported before nosotros tin use it. And equally we saw with Scanner
, we have to employ the new
operator to create a Random
(number generator).
Then we can utilise the method nextInt
to generate a random number. In this case, the result of nextInt(100)
will exist between 0 and 99, including both. Adding one yields a number between 1 and 100, including both.
- The definition of
GuessStarter
is in a file called GuessStarter.java, in the directory called ch03, in the repository for this book. - Compile and run this program.
- Modify the program to prompt the user, and then use a
Scanner
to read a line of user input. Compile and test the program. - Read the user input as an integer and display the result. Once again, compile and test.
- Compute and display the deviation betwixt the user's guess and the number that was generated.
brizendineaber1997.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