How to Make Use Put Input Again Java
Chapter iii Input and output
The programs we've looked at so far but display letters, which doesn't involve a lot of real computation. This chapter volition show you 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 take been using System.out.println
for a while, but you might not have idea about what it ways. System
is a form that provides methods related to the "system" or environment where programs run. It also provides Organisation.out
, which is a special value that provides methods for displaying output, including println
.
In fact, we tin can employ System.out.println
to brandish the value of System.out
:
Arrangement.out.println(System.out);
The result is:
java.io.PrintStream@685d72cd
This output indicates that System.out
is a PrintStream
, which is defined in a bundle 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 Organization.out
, represented as a hexadecimal (base 16) number. The address of a value is its location in the figurer's retention, which might be different on different computers. In this example the address is 685d72cd
, but if you run the same code y'all might go something dissimilar.
Equally shown in Figure iii.1, System
is defined in a file chosen Arrangement.coffee, and PrintStream
is defined in PrintStream.java. These files are part of the Java library, which is an extensive collection of classes y'all tin can use in your programs.
three.2 The Scanner form
The System
grade also provides the special value Organization.in
, which is an InputStream
that provides methods for reading input from the keyboard. These methods are not easy to utilize; fortunately, Coffee provides other classes that get in easier to handle common input tasks.
For case, Scanner
is a form that provides methods for inputting words, numbers, and other data. Scanner
is provided by java.util
, which is a package that contains classes so useful they are called "utility classes". Before you can use Scanner
, you have to import it like this:
import coffee.util.Scanner;
This import statement tells the compiler that when yous say Scanner
, yous mean the one divers in java.util
. It'southward necessary because there might be some other class named Scanner
in another package. Using an import argument makes your lawmaking unambiguous.
Import statements can't be inside a grade definition. By convention, they are usually at the beginning of the file.
Side by side you have to create a Scanner
:
Scanner in = new Scanner(Organization.in);
This line declares a Scanner
variable named in
and creates a new Scanner
that takes input from System.in
.
Scanner
provides a method called nextLine
that reads a line of input from the keyboard and returns a String
. The following instance reads two lines and repeats them back to the user:
If you omit the import statement and later refer to Scanner
, yous volition get a compiler error similar "cannot discover symbol". That means the compiler doesn't know what you lot mean by Scanner
.
You might wonder why we tin use the System
grade without importing it. Organisation
belongs to the java.lang
parcel, which is imported automatically. According to the documentation, coffee.lang
"provides classes that are key to the design of the Java programming linguistic communication." The String
form is besides role of the java.lang
package.
3.3 Program structure
At this point, we have seen all of the elements that make up Java programs. Figure iii.2 shows these organizational units.
To review, a package is a collection of classes, which define methods. Methods contain statements, some of which comprise expressions. Expressions are made 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 Java comes with several thousand classes y'all can import
, which tin exist both exciting and intimidating. You tin can browse this library at http://docs.oracle.com/javase/8/docs/api/. Near of the Java library itself is written in Coffee.
Annotation there is a major difference between the Java linguistic communication, which defines the syntax and pregnant of the elements in Figure 3.2, and the Java library, which provides the built-in classes.
3.4 Inches to centimeters
At present let's see an instance that'due south a petty more useful. Although about of the world has adopted the metric system for weights and measures, some countries are stuck with English units. For example, when talking with friends in Europe about the weather, people in the United States might have to convert from Celsius to Fahrenheit and back. Or they might want to convert superlative in inches to centimeters.
We can write a program to assistance. Nosotros'll employ a Scanner
to input a measurement in inches, convert to centimeters, then display the results. The following lines declare the variables and create the Scanner
:
int inch; double cm; Scanner in = new Scanner(System.in);
The adjacent step is to prompt the user for the input. Nosotros'll apply impress
instead of println
so they can enter the input on the same line as the prompt. And we'll use the Scanner
method nextInt
, which reads input from the keyboard and converts it to an integer:
System.out.print("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 brandish the results:
cm = inch * ii.54; System.out.impress(inch + " in = "); Arrangement.out.println(cm + " cm");
This lawmaking works correctly, but information technology has a minor problem. If some other programmer reads this code, they might wonder where two.54 comes from. For the benefit of others (and yourself in the future), it would exist better to assign this value to a variable with a meaningful proper noun. We'll demonstrate in the adjacent section.
3.5 Literals and constants
A value that appears in a program, like two.54 (or " in ="
), is chosen a literal. In general, there'south nil wrong with literals. Just when numbers like 2.54 appear in an expression with no caption, they make code hard to read. And if the aforementioned value appears many times, and might have to change in the future, information technology makes lawmaking hard to maintain.
Values like that are sometimes called magic numbers (with the implication that beingness "magic" is not a good matter). A good practice is to assign magic numbers to variables with meaningful names, similar this:
double cmPerInch = ii.54; cm = inch * cmPerInch;
This version is easier to read and less error-prone, merely it even so has a problem. Variables can vary, only the number of centimeters in an inch does not. One time we assign a value to cmPerInch
, information technology should never change. Java provides a linguistic communication characteristic that enforces that rule, the keyword final
.
concluding double CM_PER_INCH = ii.54;
Declaring that a variable is final
means that it cannot exist reassigned one time it has been initialized. If you effort, the compiler reports an error. Variables declared as last
are called constants. Past convention, names for constants are all upper-case letter, with the underscore grapheme (_
) between words.
3.6 Formatting output
When you output a double
using print
or println
, information technology displays upwardly to 16 decimal places:
System.out.impress(4.0 / 3.0);
The result is:
That might be more than you want. Organisation.out
provides another method, chosen printf
, that gives you more control of the format. The "f" in printf
stands for "formatted". Here'south an example:
System.out.printf("Four thirds = %.3f", 4.0 / 3.0);
The outset value in the parentheses is a format string that specifies how the output should be displayed. This format cord contains ordinary text followed by a format specifier, which is a special sequence that starts with a percentage sign. The format specifier \%.3f
indicates that the following value should exist displayed as floating-indicate, rounded to three decimal places. The result is:
The format string can incorporate any number of format specifiers; here'south 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 suspend a newline. So format strings frequently 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 well-nigh format strings is like learning a sub-language within Coffee. There are many options, and the details can exist overwhelming. Tabular array 3.1 lists a few common uses, to give you an thought of how things work. For more details, refer to the documentation of coffee.util.Formatter
. The easiest style to observe documentation for Java classes is to do a web search for "Java" and the proper noun of the class.
\%d
decimal integer 12345 \%08d
padded with zeros, at least 8 digits broad 00012345 \%f
floating-point six.789000 \%.2f
rounded to 2 decimal places vi.79
3.7 Centimeters to inches
At present suppose we have a measurement in centimeters, and nosotros desire to round it off to the nearest inch. It is tempting to write:
inch = cm / CM_PER_INCH; // syntax fault
But the result is an fault – you get something like, "Bad types in assignment: from double to int." The trouble is that the value on the correct is floating-signal, 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 type cast, so called because it molds or "casts" a value from one type to another. The syntax for type casting is to put the name of the type in parentheses and utilise information technology as an operator.
double pi = 3.14159; int x = (int) pi;
The (int)
operator has the effect of converting what follows into an integer. In this example, x
gets the value 3
. Like integer sectionalization, converting to an integer always rounds toward zero, even if the fraction part is 0.999999
(or -0.999999
). In other words, it just throws away the fractional office.
Type casting takes precedence over arithmetic operations. In this example, the value of pi
gets converted to an integer before the multiplication. So the upshot is sixty.0, not 62.0.
double pi = 3.14159; double x = (int) pi * 20.0;
Keeping that in mind, here'due south how we tin catechumen a measurement in centimeters to inches:
inch = (int) (cm / CM_PER_INCH); System.out.printf("%f cm = %d in\n", cent, inch);
The parentheses afterward the cast operator require the division to happen earlier the blazon cast. And the result is rounded toward zip; we will see in the next affiliate how to circular floating-indicate numbers to the closest integer.
3.8 Modulus operator
Let'southward have the example one step further: suppose y'all accept a measurement in inches and you want to convert to feet and inches. The goal is divide past 12 (the number of inches in a foot) and keep the remainder.
We have already seen the division operator (/
), which computes the quotient of two numbers. If the numbers are integers, it performs integer division. Java also provides the modulus operator (\%
), which divides two numbers and computes the residual.
Using division and modulus, we tin convert to feet and inches like this:
quotient = 76 / 12; // sectionalization residue = 76 % 12; // modulus
The commencement line yields 6. The 2d line, which is pronounced "76 modern 12", yields 4. So 76 inches is half-dozen feet, 4 inches.
The modulus operator looks similar a percent sign, just y'all might find it helpful to call up of it as a sectionalization sign (÷) rotated to the left.
The modulus operator turns out to be surprisingly useful. For instance, you can check whether one number is divisible by another: if 10 \% y
is aught, then 10
is divisible past y
. You tin utilize modulus to "excerpt" digits from a number: 10 \% 10
yields the rightmost digit of 10
, and x \% 100
yields the last ii digits. Besides, many encryption algorithms use the modulus operator extensively.
3.9 Putting it all together
At this point, y'all have seen enough Coffee to write useful programs that solve everyday problems. Y'all tin can (one) import Java library classes, (2) create a Scanner
, (3) get input from the keyboard, (4) format output with printf
, and (v) divide and modern integers. Now nosotros will put everything together in a complete program:
Although not required, all variables and constants are declared at the summit of master
. This practice makes it easier to detect their types later on on, and it helps the reader know what information 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 besides includes a documentation annotate ( /**
), which we'll acquire more almost in the next chapter.
Many algorithms, including the Convert
programme, perform division and modulus together. In both steps, y'all divide past the aforementioned number (IN_PER_FOOT
).
When statements get long (generally wider than 80 characters), a common mode convention is to break them across multiple lines. The reader should never have to scroll horizontally.
3.10 The Scanner issues
At present that you've had some experience with Scanner
, there is an unexpected beliefs we want to warn you about. The following lawmaking fragment asks users for their name and historic period:
Organisation.out.print("What is your proper name? "); name = in.nextLine(); System.out.print("What is your age? "); historic period = in.nextInt(); Arrangement.out.printf("Hello %s, age %d\n", name, age);
The output might expect something similar this:
Hello Grace Hopper, age 45
When you read a Cord
followed past an int
, everything works just fine. Merely when yous read an int
followed by a String
, something strange happens.
Organization.out.impress("What is your historic period? "); age = in.nextInt(); Arrangement.out.print("What is your name? "); proper noun = in.nextLine(); Organisation.out.printf("Hello %s, historic period %d\n", name, historic period);
Endeavor running this instance code. It doesn't let you input your name, and it immediately displays the output:
What is your name? Hello , age 45
To sympathise what is happening, you take to sympathize that the Scanner
doesn't see input equally multiple lines, like nosotros do. Instead, information technology gets a "stream of characters" as shown in Effigy iii.3.
The pointer indicates the adjacent character to be read past Scanner
. When you call nextInt
, it reads characters until it gets to a non-digit. Figure 3.4 shows the state of the stream after nextInt
is invoked.
At this point, nextInt
returns 45
. The program and then displays the prompt "What is your name? "
and calls nextLine
, which reads characters until it gets to a newline. Simply since the next character is already a newline, nextLine
returns the empty cord ""
.
To solve this problem, you need an extra nextLine
later nextInt
.
Organization.out.print("What is your age? "); age = in.nextInt(); in.nextLine(); // read the newline System.out.print("What is your name? "); proper name = in.nextLine(); System.out.printf("Hello %s, age %d\n", proper name, historic period);
This technique is common when reading int
or double
values that appear on their own line. Get-go you read the number, so you read the rest of the line, which is but a newline character.
iii.11 Vocabulary
- package:
- A grouping of classes that are related to each other.
- address:
- The location of a value in computer memory, often represented as a hexadecimal integer.
- library:
- A collection of packages and classes that are available for apply in other programs.
- import statement:
- A statement that allows programs to utilise classes defined in other packages.
- token:
- A basic element of a program, such as a word, infinite, symbol, or number.
- literal:
- A value that appears in source lawmaking. For example,
"Hi"
is a string literal and74
is an integer literal. - magic number:
- A number that appears without caption as part of an expression. It should generally be replaced with a constant.
- constant:
- A variable, declared
final
, whose value cannot exist inverse. - format string:
- A string passed to
printf
to specify the format of the output. - format specifier:
- A special code that begins with a percentage sign and specifies the data type and format of the corresponding value.
- type cast:
- An operation that explicitly converts one data blazon into another. In Java it appears as a blazon name in parentheses, like
(int)
. - modulus:
- An operator that yields the remainder when ane integer is divided by another. In Java, it is denoted with a percent sign; for example,
5 \% ii
is1
.
3.12 Exercises
The code for this chapter is in the ch03 directory of ThinkJavaCode. Encounter page ?? for instructions on how to download the repository. Before you start the exercises, we recommend that you lot compile and run the examples.
If you lot have not already read Appendix A.3, now might be a proficient time. Information technology describes the command-line interface, which is a powerful and efficient manner to interact with your computer.
Practice ane When you employ printf
, the Coffee compiler does non check your format string. See what happens if you try to brandish a value with type int
using \%f
. And what happens if you display a double
using \%d
? What if yous apply 2 format specifiers, but so only provide one value?
Practise 2 Write a program that converts a temperature from Celsius to Fahrenheit. It should (1) prompt the user for input, (2) read a double
value from the keyboard, (3) calculate the result, and (4) format the output to one decimal place. For example, it should display "24.0 C = 75.2 F".
Here is the formula. Be careful not to use integer segmentation!
Exercise 3 Write a plan that converts a total number of seconds to hours, minutes, and seconds. It should (1) prompt the user for input, (ii) read an integer from the keyboard, (3) summate the result, and (4) use printf
to display the output. For example, "5000 seconds = 1 hours, 23 minutes, and xx seconds".
Hint: Use the modulus operator.
Exercise 4 The goal of this exercise is to program a "Guess My Number" game. When it's finished, it will work like this:
I'm thinking of a number between one and 100 (including both). Can yous guess what it is? Type a number: 45 Your gauge is: 45 The number I was thinking of is: 14 You were off by: 31
To choose a random number, you lot can utilize the Random
class in java.util
. Here's how it works:
Similar the Scanner
class nosotros saw in this affiliate, Random
has to be imported before we can use it. And as nosotros saw with Scanner
, we have to apply the new
operator to create a Random
(number generator).
Then we tin can apply the method nextInt
to generate a random number. In this example, the result of nextInt(100)
will exist betwixt 0 and 99, including both. Calculation 1 yields a number betwixt 1 and 100, including both.
- The definition of
GuessStarter
is in a file chosen GuessStarter.java, in the directory chosen ch03, in the repository for this book. - Compile and run this program.
- Alter the program to prompt the user, then use a
Scanner
to read a line of user input. Compile and test the plan. - Read the user input equally an integer and display the event. Over again, compile and test.
- Compute and brandish the difference betwixt the user's guess and the number that was generated.
Source: https://books.trinket.io/thinkjava/chapter3.html
0 Response to "How to Make Use Put Input Again Java"
Post a Comment