Read in a Number From a User Java

Chapter 3  Input and output

The programs we've looked at so far just display messages, which doesn't involve a lot of real computation. This chapter will prove you how to read input from the keyboard, use that input to calculate a outcome, so format that outcome for output.

iii.1  The System course

We take been using Arrangement.out.println for a while, but y'all might not have thought nigh what information technology ways. System is a class that provides methods related to the "system" or environment where programs run. It likewise provides Arrangement.out, which is a special value that provides methods for displaying output, including println.

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

System.out.println(System.out);

The result is:

coffee.io.PrintStream@685d72cd

This output indicates that Organisation.out is a PrintStream, which is divers in a packet called java.io. A package is a collection 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 accost of System.out, represented every bit a hexadecimal (base 16) number. The address of a value is its location in the calculator's retention, which might exist different on different computers. In this example the accost is 685d72cd, but if yous run the same code y'all might get something different.

As shown in Figure 3.i, System is defined in a file chosen System.coffee, and PrintStream is defined in PrintStream.coffee. These files are part of the Java library, which is an all-encompassing drove of classes you can employ in your programs.

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

3.two  The Scanner class

The System course also 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 apply; fortunately, Java provides other classes that make information technology easier to handle common input tasks.

For case, Scanner is a course that provides methods for inputting words, numbers, and other information. Scanner is provided by java.util, which is a package that contains classes so useful they are chosen "utility classes". Before y'all tin apply Scanner, you lot have to import it like this:

import java.util.Scanner;

This import statement tells the compiler that when yous say Scanner, yous mean the one defined in java.util. It's necessary considering in that location might exist another form named Scanner in another bundle. Using an import statement makes your lawmaking unambiguous.

Import statements tin't be inside a course definition. By convention, they are usually at the beginning of the file.

Next you have to create a Scanner:

Scanner in = new Scanner(Arrangement.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 post-obit example reads ii lines and repeats them back to the user:

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

You might wonder why nosotros can apply the System 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 primal to the blueprint of the Coffee programming language." The Cord form is also part of the coffee.lang packet.

3.three  Program structure

At this indicate, we take seen all of the elements that make up Java programs. Figure iii.2 shows these organizational units.

Effigy 3.ii: Elements of the Java linguistic communication, from largest to smallest.

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

The standard edition of Java comes with several thousand classes you tin import , which can be both exciting and intimidating. You can scan this library at http://docs.oracle.com/javase/viii/docs/api/. Nigh of the Coffee library itself is written in Java.

Note there is a major difference betwixt the Coffee language, which defines the syntax and meaning of the elements in Figure 3.two, and the Java library, which provides the congenital-in classes.

3.4  Inches to centimeters

Now let'south see an example that's a little more useful. Although near of the earth has adopted the metric system for weights and measures, some countries are stuck with English units. For example, when talking with friends in Europe virtually the weather condition, people in the Us might have to convert from Celsius to Fahrenheit and back. Or they might desire to convert height in inches to centimeters.

We can write a program to assistance. We'll use 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(Arrangement.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 use the Scanner method nextInt, which reads input from the keyboard and converts it to an integer:

System.out.impress("How many inches? "); inch = in.nextInt();

Next nosotros multiply the number of inches past ii.54, since that's how many centimeters at that place are per inch, and brandish the results:

cm = inch * two.54; Arrangement.out.impress(inch + " in = "); System.out.println(cm + " cm");

This lawmaking works correctly, but it has a pocket-size trouble. If another programmer reads this code, they might wonder where 2.54 comes from. For the benefit of others (and yourself in the future), it would be meliorate to assign this value to a variable with a meaningful name. Nosotros'll demonstrate in the adjacent section.

three.five  Literals and constants

A value that appears in a programme, like two.54 (or " in =" ), is called a literal. In full general, at that place's nada wrong with literals. But when numbers similar 2.54 appear in an expression with no caption, they brand lawmaking hard to read. And if the aforementioned value appears many times, and might have to alter in the future, it makes code difficult to maintain.

Values like that are sometimes called magic numbers (with the implication that beingness "magic" is non a good thing). A good practise 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 error-prone, simply it still has a problem. Variables can vary, but the number of centimeters in an inch does not. Once we assign a value to cmPerInch, it should never change. Java provides a language feature that enforces that rule, the keyword concluding .

last double CM_PER_INCH = 2.54;

Declaring that a variable is final means that it cannot be reassigned one time information technology has been initialized. If you lot try, the compiler reports an error. Variables declared as final are chosen constants. By convention, names for constants are all upper-case letter, with the underscore character (_) betwixt words.

three.vi  Formatting output

When y'all output a double using print or println, information technology displays up to 16 decimal places:

System.out.print(4.0 / 3.0);

The result is:

That might exist more than than you lot desire. System.out provides another method, called printf, that gives yous more command of the format. The "f" in printf stands for "formatted". Here's an example:

Arrangement.out.printf("Four thirds = %.3f", 4.0 / 3.0);

The first value in the parentheses is a format string that specifies how the output should exist displayed. This format string 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 be displayed as floating-point, rounded to 3 decimal places. The event is:

The format cord tin can contain any number of format specifiers; here's an example with two:

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

The result is:

Like print, printf does not append a newline. Then format strings frequently end with a newline graphic symbol.

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

Learning almost format strings is like learning a sub-language within Java. There are many options, and the details can be overwhelming. Table 3.one lists a few common uses, to give y'all an idea of how things work. For more details, refer to the documentation of java.util.Formatter. The easiest way to find documentation for Java classes is to do a web search for "Coffee" and the name of the class.

\%d decimal integer 12345
\%08d padded with zeros, at least 8 digits broad 00012345
\%f floating-point 6.789000
\%.2f rounded to 2 decimal places vi.79

Table 3.1: Instance format specifiers

3.7  Centimeters to inches

At present suppose nosotros accept a measurement in centimeters, and we desire to round it off to the nearest inch. It is tempting to write:

inch = cm / CM_PER_INCH; // syntax error

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

The simplest way to convert a floating-betoken value to an integer is to use a blazon cast, so chosen 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 use information technology as an operator.

double pi = 3.14159; int x = (int) pi;

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

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

double pi = three.14159; double 10 = (int) pi * twenty.0;

Keeping that in mind, here's how we can catechumen a measurement in centimeters to inches:

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

The parentheses after the cast operator require the division to happen earlier the type cast. And the result is rounded toward cypher; we will run across in the next chapter how to circular floating-point numbers to the closest integer.

3.8  Modulus operator

Allow's take the example 1 step further: suppose y'all have a measurement in inches and you want to convert to feet and inches. The goal is split up by 12 (the number of inches in a pes) and go along the remainder.

Nosotros have already seen the partition operator (/), which computes the quotient of 2 numbers. If the numbers are integers, it performs integer sectionalization. Java as well provides the modulus operator (\%), which divides two numbers and computes the remainder.

Using partitioning and modulus, nosotros can convert to feet and inches like this:

quotient = 76 / 12; // division rest = 76 % 12; // modulus

The start line yields half-dozen. The second line, which is pronounced "76 mod 12", yields iv. So 76 inches is 6 feet, four inches.

The modulus operator looks like a percent sign, merely you might discover it helpful to retrieve of it as a segmentation sign (÷) rotated to the left.

The modulus operator turns out to exist surprisingly useful. For example, y'all tin check whether ane number is divisible by another: if 10 \% y is zero, and so x is divisible past y. You tin use modulus to "extract" digits from a number: x \% 10 yields the rightmost digit of 10, and ten \% 100 yields the last two digits. Also, many encryption algorithms use the modulus operator extensively.

3.9  Putting it all together

At this point, you have seen enough Coffee to write useful programs that solve everyday problems. You lot can (i) import Java library classes, (2) create a Scanner, (iii) get input from the keyboard, (iv) format output with printf, and (5) divide and modernistic integers. Now nosotros will put everything together in a consummate program:

Although not required, all variables and constants are alleged at the tiptop of main. This practise makes information technology easier to detect their types later on, and information technology helps the reader know what data is involved in the algorithm.

For readability, each major pace of the algorithm is separated by a blank line and begins with a comment. It also includes a documentation comment ( /** ), which we'll learn more almost in the side by side affiliate.

Many algorithms, including the Catechumen plan, perform partition and modulus together. In both steps, y'all dissever by the same number (IN_PER_FOOT).

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

iii.x  The Scanner bug

Now that you've had some feel with Scanner, at that place is an unexpected behavior nosotros want to warn you lot nigh. The post-obit code fragment asks users for their name and historic period:

System.out.print("What is your name? "); proper noun = in.nextLine(); Organisation.out.impress("What is your historic period? "); age = in.nextInt(); Arrangement.out.printf("Hello %due south, age %d\north", name, age);

The output might look something like this:

How-do-you-do Grace Hopper, age 45

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

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

Endeavour running this case lawmaking. It doesn't permit you input your name, and information technology immediately displays the output:

What is your name? How-do-you-do , age 45

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

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

The arrow indicates the adjacent character to be read past Scanner. When you telephone call nextInt, it reads characters until it gets to a not-digit. Effigy iii.4 shows the country of the stream later on nextInt is invoked.

Figure iii.iv: A stream of characters afterwards nextInt is invoked.

At this point, nextInt returns 45. The plan then displays the prompt "What is your proper name? " and calls nextLine, which reads characters until it gets to a newline. But since the next grapheme is already a newline, nextLine returns the empty cord "" .

To solve this problem, y'all need an actress nextLine after nextInt.

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

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

3.11  Vocabulary

packet:
A group of classes that are related to each other.
address:
The location of a value in computer retentivity, oft represented equally a hexadecimal integer.
library:
A drove of packages and classes that are available for apply in other programs.
import statement:
A statement that allows programs to use classes divers in other packages.
token:
A basic chemical element of a program, such as a give-and-take, space, symbol, or number.
literal:
A value that appears in source code. For case, "Hello" is a cord literal and 74 is an integer literal.
magic number:
A number that appears without explanation as part of an expression. It should more often than not be replaced with a abiding.
constant:
A variable, declared concluding , whose value cannot be inverse.
format string:
A string passed to printf to specify the format of the output.
format specifier:
A special code that begins with a pct sign and specifies the data blazon and format of the corresponding value.
blazon cast:
An functioning that explicitly converts 1 data type into another. In Java it appears as a blazon name in parentheses, similar (int).
modulus:
An operator that yields the rest when one integer is divided by another. In Java, it is denoted with a percent sign; for case, v \% two is 1.

3.12  Exercises

The code for this chapter is in the ch03 directory of ThinkJavaCode. See folio ?? for instructions on how to download the repository. Before you lot start the exercises, we recommend that you compile and run the examples.

If you accept non already read Appendix A.3, now might exist a skillful time. It describes the command-line interface, which is a powerful and efficient way to interact with your reckoner.

Exercise ane When you use printf, the Java compiler does not cheque your format string. Run into what happens if you try to display a value with type int using \%f. And what happens if you display a double using \%d? What if you apply ii format specifiers, just then merely provide one value?

Exercise ii Write a programme that converts a temperature from Celsius to Fahrenheit. It should (ane) prompt the user for input, (ii) read a double value from the keyboard, (3) calculate the result, and (4) format the output to 1 decimal place. For example, it should display "24.0 C = 75.2 F".

Here is the formula. Exist careful non to use integer division!

Exercise 3 Write a program 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, (three) calculate the outcome, and (4) utilise printf to display the output. For example, "5000 seconds = one hours, 23 minutes, and xx seconds".

Hint: Use the modulus operator.

Exercise 4 The goal of this practise is to plan a "Guess My Number" game. When it'due south finished, information technology will work like this:

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

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

Like the Scanner class nosotros saw in this chapter, Random has to be imported before nosotros tin use information technology. And as we saw with Scanner, we accept to use the new operator to create a Random (number generator).

Then nosotros can utilize the method nextInt to generate a random number. In this case, the result of nextInt(100) volition be between 0 and 99, including both. Adding 1 yields a number between one and 100, including both.

  1. The definition of GuessStarter is in a file called GuessStarter.java, in the directory called ch03, in the repository for this book.
  2. Compile and run this plan.
  3. Change the plan to prompt the user, then apply a Scanner to read a line of user input. Compile and test the programme.
  4. Read the user input as an integer and brandish the result. Again, compile and test.
  5. Compute and brandish the difference between the user's guess and the number that was generated.

kendrickareacking.blogspot.com

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

Related Posts

0 Response to "Read in a Number From a User Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel