what do i have to enter two inputs before my java output shows
Chapter three Input and output
The programs we've looked at so far simply display letters, which doesn't involve a lot of real ciphering. This chapter volition show y'all how to read input from the keyboard, use that input to summate a effect, and then format that effect for output.
3.one The System grade
We have been using Organisation.out.println for a while, but you might not have thought about what it ways. System is a grade that provides methods related to the "system" or environment where programs run. It also provides System.out, which is a special value that provides methods for displaying output, including println.
In fact, we can use System.out.println to display the value of System.out:
Organisation.out.println(Organization.out);
The result is:
java.io.PrintStream@685d72cd
This output indicates that System.out is a PrintStream, which is defined in a bundle called 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 Arrangement.out, represented every bit a hexadecimal (base 16) number. The address of a value is its location in the computer's retention, which might be different on different computers. In this example the address is 685d72cd, but if you lot run the aforementioned code y'all might get something different.
As shown in Effigy 3.1, System is defined in a file called System.coffee, and PrintStream is defined in PrintStream.java. These files are part of the Coffee library, which is an extensive collection of classes you lot can utilize in your programs.
![]()
Figure 3.1:
System.out.printlnrefers to theoutvariable of theSystemclass, which is aPrintStreamthat provides a method calledprintln.
3.2 The Scanner grade
The System class besides provides the special value Organization.in, which is an InputStream that provides methods for reading input from the keyboard. These methods are non easy to use; fortunately, Java provides other classes that go far easier to handle common input tasks.
For instance, Scanner is a class that provides methods for inputting words, numbers, and other data. Scanner is provided past java.util, which is a parcel that contains classes so useful they are chosen "utility classes". Before you tin employ Scanner, you have to import it similar this:
import java.util.Scanner;
This import statement tells the compiler that when you say Scanner, you mean the one defined in coffee.util. It's necessary considering there might be another class named Scanner in another package. Using an import argument makes your code unambiguous.
Import statements can't be within a class definition. By convention, they are usually at the showtime of the file.
Adjacent you have to create a Scanner:
Scanner in = new Scanner(Organisation.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 case reads two lines and repeats them dorsum to the user:
If you lot omit the import statement and after refer to Scanner, you will become a compiler fault like "cannot find symbol". That means the compiler doesn't know what you mean past Scanner.
You might wonder why we can utilise the Arrangement course without importing it. System belongs to the java.lang package, which is imported automatically. Co-ordinate to the documentation, java.lang "provides classes that are fundamental to the design of the Coffee programming linguistic communication." The String class is also part of the coffee.lang bundle.
3.iii Plan construction
At this indicate, we have seen all of the elements that make up Java programs. Figure 3.2 shows these organizational units.
![]()
Figure 3.ii: 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 bones elements of a program, including numbers, variable names, operators, keywords, and punctuation similar parentheses, braces and semicolons.
The standard edition of Java comes with several m classes you can import , which can exist both exciting and intimidating. Yous 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 significant of the elements in Figure three.ii, and the Coffee library, which provides the congenital-in classes.
3.four Inches to centimeters
Now let's come across an example that's a little more than useful. Although nigh 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 take to convert from Celsius to Fahrenheit and back. Or they might want to convert superlative in inches to centimeters.
We tin write a programme to assist. We'll utilize a Scanner to input a measurement in inches, convert to centimeters, and then display the results. The following lines declare the variables and create the Scanner:
int inch; double cm; Scanner in = new Scanner(Organisation.in);
The next pace is to prompt the user for the input. We'll utilise print instead of println then they 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:
System.out.print("How many inches? "); inch = in.nextInt();
Next we multiply the number of inches by two.54, since that's how many centimeters at that place are per inch, and brandish the results:
cm = inch * two.54; System.out.print(inch + " in = "); Arrangement.out.println(cm + " cm");
This code works correctly, but it has a small-scale problem. If another developer reads this lawmaking, they might wonder where 2.54 comes from. For the do good of others (and yourself in the future), it would be better to assign this value to a variable with a meaningful proper name. We'll demonstrate in the side by side department.
3.5 Literals and constants
A value that appears in a program, like 2.54 (or " in =" ), is called a literal. In general, at that place's nothing wrong with literals. But when numbers like 2.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 alter in the future, it makes lawmaking difficult to maintain.
Values similar that are sometimes called magic numbers (with the implication that being "magic" is non a practiced thing). A skilful practice is to assign magic numbers to variables with meaningful names, like this:
double cmPerInch = ii.54; cm = inch * cmPerInch;
This version is easier to read and less error-prone, but it still has a problem. Variables can vary, simply the number of centimeters in an inch does not. Once we assign a value to cmPerInch, information technology should never modify. Java provides a language characteristic that enforces that rule, the keyword final .
final double CM_PER_INCH = 2.54;
Declaring that a variable is final means that it cannot be reassigned once it has been initialized. If you effort, the compiler reports an fault. Variables declared equally final are called constants. Past convention, names for constants are all majuscule, with the underscore character (_) between words.
three.half-dozen Formatting output
When yous output a double using impress or println, it displays up to 16 decimal places:
System.out.print(4.0 / three.0);
The result is:
That might be more than than you want. System.out provides some other method, called printf, that gives you more control of the format. The "f" in printf stands for "formatted". Here's an case:
System.out.printf("Four thirds = %.3f", iv.0 / 3.0);
The first value in the parentheses is a format string that specifies how the output should exist displayed. This format cord 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 be displayed as floating-point, rounded to iii decimal places. The result is:
The format string tin contain whatever number of format specifiers; here's an example with 2:
int inch = 100; double cm = inch * CM_PER_INCH; Arrangement.out.printf("%d in = %f cm\due north", inch, cm);
The result is:
Similar impress, printf does not suspend a newline. And then 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 about format strings is like learning a sub-language inside Java. In that location are many options, and the details tin can be overwhelming. Table 3.1 lists a few mutual uses, to give yous an idea of how things work. For more than details, refer to the documentation of java.util.Formatter. The easiest way to find documentation for Java classes is to practice a web search for "Java" and the proper noun of the form.
\%ddecimal integer 12345 \%08dpadded with zeros, at least 8 digits wide 00012345 \%ffloating-point half-dozen.789000 \%.2frounded to 2 decimal places 6.79 Table 3.1: Instance format specifiers
3.seven Centimeters to inches
Now suppose we have a measurement in centimeters, and nosotros want to round it off to the nearest inch. Information technology is tempting to write:
inch = cm / CM_PER_INCH; // syntax mistake
But the issue is an error – you get something similar, "Bad types in consignment: 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 manner to convert a floating-betoken value to an integer is to use a type cast, and so called because it molds or "casts" a value from one type to some other. The syntax for type casting is to put the name of the blazon in parentheses and utilise it as an operator.
double pi = 3.14159; int 10 = (int) pi;
The (int) operator has the consequence of converting what follows into an integer. In this example, x gets the value iii. Similar integer partitioning, converting to an integer ever rounds toward zero, even if the fraction part is 0.999999 (or -0.999999). In other words, it simply throws away the partial part.
Type casting takes precedence over arithmetic operations. In this example, the value of pi gets converted to an integer earlier the multiplication. So the result is threescore.0, not 62.0.
double pi = iii.14159; double x = (int) pi * twenty.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 division to happen before the type cast. And the result is rounded toward zippo; we volition run into in the side by side chapter how to round floating-bespeak numbers to the closest integer.
iii.8 Modulus operator
Let'due south accept the instance one stride farther: suppose you have a measurement in inches and you want to convert to feet and inches. The goal is divide by 12 (the number of inches in a human foot) and go along the remainder.
We have already seen the division operator (/), which computes the caliber of 2 numbers. If the numbers are integers, it performs integer division. Java as well provides the modulus operator (\%), which divides two numbers and computes the remainder.
Using division and modulus, we tin can convert to anxiety and inches like this:
quotient = 76 / 12; // division rest = 76 % 12; // modulus
The beginning line yields half-dozen. The 2d line, which is pronounced "76 modernistic 12", yields four. So 76 inches is half dozen anxiety, 4 inches.
The modulus operator looks like a percent sign, but you might detect it helpful to retrieve of information technology equally a division sign (÷) rotated to the left.
The modulus operator turns out to be surprisingly useful. For example, you can check whether 1 number is divisible by another: if 10 \% y is goose egg, then x is divisible by y. You can apply modulus to "extract" digits from a number: 10 \% 10 yields the rightmost digit of 10, and x \% 100 yields the terminal ii digits. As well, many encryption algorithms use the modulus operator extensively.
iii.ix Putting it all together
At this betoken, you have seen enough Java to write useful programs that solve everyday issues. You can (1) import Java library classes, (2) create a Scanner, (three) go input from the keyboard, (4) format output with printf, and (5) split up and mod integers. At present we will put everything together in a consummate program:
Although not required, all variables and constants are alleged at the height of main. This practise makes it easier to find their types afterward, and it helps the reader know what information is involved in the algorithm.
For readability, each major step 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 than almost in the next chapter.
Many algorithms, including the Catechumen programme, perform sectionalization and modulus together. In both steps, yous split up by the same number (IN_PER_FOOT).
When statements become long (by and large wider than lxxx characters), a common style convention is to break them across multiple lines. The reader should never have to gyre horizontally.
3.ten The Scanner bug
Now that you've had some experience with Scanner, there is an unexpected behavior we want to warn yous about. The following code fragment asks users for their proper name and historic period:
Organization.out.print("What is your name? "); name = in.nextLine(); System.out.print("What is your historic period? "); age = in.nextInt(); Organisation.out.printf("How-do-you-do %south, historic period %d\northward", proper name, historic period);
The output might look something like this:
Hello Grace Hopper, age 45
When you read a String followed by an int , everything works just fine. But when y'all read an int followed past a Cord, something strange happens.
System.out.print("What is your historic period? "); age = in.nextInt(); System.out.print("What is your proper name? "); name = in.nextLine(); System.out.printf("Hello %south, age %d\north", name, age);
Endeavor running this example lawmaking. It doesn't allow you lot input your name, and it immediately displays the output:
What is your name? Hello , historic period 45
To understand what is happening, you lot have to empathise that the Scanner doesn't run across input as multiple lines, similar nosotros practice. Instead, it gets a "stream of characters" as shown in Figure 3.3.
![]()
Figure 3.iii: A stream of characters every bit seen by a
Scanner.
The arrow indicates the side by side character to be read by Scanner. When you telephone call nextInt, information technology reads characters until information technology gets to a non-digit. Figure 3.4 shows the state of the stream after nextInt is invoked.
![]()
Figure 3.4: A stream of characters later
nextIntis invoked.
At this point, nextInt returns 45. The program then displays the prompt "What is your proper name? " and calls nextLine, which reads characters until it gets to a newline. Simply since the side by side graphic symbol is already a newline, nextLine returns the empty string "" .
To solve this problem, you need an extra nextLine after nextInt.
System.out.print("What is your age? "); historic period = in.nextInt(); in.nextLine(); // read the newline System.out.impress("What is your proper name? "); name = in.nextLine(); System.out.printf("Howdy %due south, age %d\northward", name, historic period);
This technique is common when reading int or double values that appear on their own line. Kickoff you read the number, and then you read the residuum of the line, which is merely a newline graphic symbol.
3.eleven Vocabulary
- packet:
- A group of classes that are related to each other.
- address:
- The location of a value in reckoner retentiveness, frequently represented equally a hexadecimal integer.
- library:
- A drove of packages and classes that are available for use in other programs.
- import statement:
- A statement that allows programs to use classes defined in other packages.
- token:
- A bones chemical element of a program, such as a word, space, symbol, or number.
- literal:
- A value that appears in source code. For case,
"Hello"is a string literal and74is an integer literal. - magic number:
- A number that appears without caption every bit part of an expression. It should generally be replaced with a constant.
- constant:
- A variable, alleged
final, whose value cannot be inverse. - format cord:
- A string passed to
printfto specify the format of the output. - format specifier:
- A special code that begins with a per centum sign and specifies the data type and format of the corresponding value.
- blazon cast:
- An operation that explicitly converts ane information type into another. In Java it appears as a blazon proper noun in parentheses, like
(int). - modulus:
- An operator that yields the remainder when one integer is divided by another. In Java, information technology is denoted with a pct sign; for example,
5 \% 2is1.
3.12 Exercises
The lawmaking for this chapter is in the ch03 directory of ThinkJavaCode. See folio ?? for instructions on how to download the repository. Before yous first the exercises, we recommend that you compile and run the examples.
If you have not already read Appendix A.three, now might exist a expert time. It describes the command-line interface, which is a powerful and efficient mode to interact with your computer.
Do one When yous use printf, the Java compiler does non check your format string. See what happens if y'all effort to display a value with type int using \%f. And what happens if you display a double using \%d? What if you use two format specifiers, but then just provide i value?
Practise ii Write a plan that converts a temperature from Celsius to Fahrenheit. It should (ane) 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".
Hither is the formula. Exist careful not to utilize integer sectionalisation!
Practice 3 Write a program that converts a total number of seconds to hours, minutes, and seconds. It should (one) prompt the user for input, (two) read an integer from the keyboard, (iii) calculate the issue, and (4) use printf to display the output. For example, "5000 seconds = one hours, 23 minutes, and twenty seconds".
Hint: Use the modulus operator.
Practice 4 The goal of this practice is to program a "Guess My Number" game. When information technology's finished, it will work like this:
I'm thinking of a number between i and 100 (including both). Tin can you guess what information technology is? Type a number: 45 Your guess is: 45 The number I was thinking of is: 14 You lot were off past: 31
To cull a random number, you can utilize the Random class in coffee.util. Hither's how it works:
Like the Scanner course we saw in this affiliate, Random has to be imported earlier we tin can use it. And as we saw with Scanner, we have to utilize the new operator to create a Random (number generator).
Then we can use the method nextInt to generate a random number. In this instance, the result of nextInt(100) will be between 0 and 99, including both. Adding 1 yields a number between one and 100, including both.
- The definition of
GuessStarteris in a file called GuessStarter.java, in the directory called ch03, in the repository for this book. - Compile and run this program.
- Modify the programme to prompt the user, then utilise a
Scannerto read a line of user input. Compile and examination the program. - Read the user input every bit an integer and display the result. Again, compile and test.
- Compute and display the difference between the user's guess and the number that was generated.
Source: https://books.trinket.io/thinkjava/chapter3.html
Post a Comment for "what do i have to enter two inputs before my java output shows"