How to Ask User to Enter Choice Again Java

Chapter 3  Input and output

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

3.one  The System class

We take been using System.out.println for a while, but you might not have thought most what it means. Organization is a course that provides methods related to the "system" or environment where programs run. It likewise provides System.out, which is a special value that provides methods for displaying output, including println.

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

System.out.println(Organization.out);

The result is:

coffee.io.PrintStream@685d72cd

This output indicates that System.out is a PrintStream, which is divers in a package called java.io. A parcel is a collection of related classes; coffee.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 equally a hexadecimal (base 16) number. The address of a value is its location in the computer's retentiveness, which might be different on different computers. In this example the accost is 685d72cd, just if you run the same code you might get something dissimilar.

As shown in Figure 3.ane, System is divers in a file called System.coffee, and PrintStream is defined in PrintStream.java. These files are role of the Java library, which is an extensive collection of classes you lot tin can utilize in your programs.

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

three.2  The Scanner form

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

For case, Scanner is a form that provides methods for inputting words, numbers, and other information. Scanner is provided by java.util, which is a package that contains classes then useful they are chosen "utility classes". Before you can use Scanner, you take to import it like this:

import java.util.Scanner;

This import argument tells the compiler that when you say Scanner, you mean the one divers in java.util. It's necessary because there might be another class named Scanner in some other packet. Using an import statement makes your code unambiguous.

Import statements tin't exist within a class definition. By convention, they are normally at the offset of the file.

Side by side 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 System.in.

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

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

You might wonder why we can use the Organisation form without importing it. System belongs to the java.lang package, which is imported automatically. According to the documentation, java.lang "provides classes that are fundamental to the pattern of the Coffee programming linguistic communication." The String grade is as well part of the java.lang package.

iii.3  Programme structure

At this point, we have seen all of the elements that brand up Java programs. Figure iii.two shows these organizational units.

Figure 3.ii: 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 contain expressions. Expressions are made up 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 Coffee comes with several yard classes you can import , which tin can exist both heady and intimidating. You can browse this library at http://docs.oracle.com/javase/8/docs/api/. About of the Java library itself is written in Java.

Notation there is a major difference between the Java 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'due south see an case that's a petty 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 nearly the weather, people in the United States might have to convert from Celsius to Fahrenheit and back. Or they might want to convert meridian in inches to centimeters.

We can write a plan to help. Nosotros'll utilize a Scanner to input a measurement in inches, convert to centimeters, and and then display the results. The post-obit lines declare the variables and create the Scanner:

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

The side by side step is to prompt the user for the input. We'll utilise print instead of println and then they tin enter the input on the aforementioned line as the prompt. And we'll employ 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 past two.54, since that's how many centimeters there are per inch, and display the results:

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

This code works correctly, but it 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), it would exist ameliorate to assign this value to a variable with a meaningful proper name. We'll demonstrate in the next department.

3.five  Literals and constants

A value that appears in a programme, like two.54 (or " in =" ), is called a literal. In general, there's zero wrong with literals. But when numbers like ii.54 appear in an expression with no caption, they make code hard to read. And if the aforementioned value appears many times, and might take to change in the hereafter, it makes lawmaking hard to maintain.

Values like that are sometimes called magic numbers (with the implication that being "magic" is not a skillful thing). 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 mistake-decumbent, just information technology still has a problem. Variables can vary, just the number of centimeters in an inch does not. Once we assign a value to cmPerInch, information technology should never change. Java provides a linguistic communication feature that enforces that rule, the keyword last .

final double CM_PER_INCH = 2.54;

Declaring that a variable is final means that information technology cannot be reassigned in one case it has been initialized. If you try, the compiler reports an mistake. Variables alleged equally final are chosen constants. By convention, names for constants are all uppercase, with the underscore character (_) between words.

iii.six  Formatting output

When you output a double using print or println, it displays upwardly to 16 decimal places:

System.out.print(iv.0 / 3.0);

The consequence is:

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

Organisation.out.printf("Four thirds = %.3f", 4.0 / three.0);

The first 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 post-obit value should be displayed as floating-signal, rounded to 3 decimal places. The result is:

The format string can contain any number of format specifiers; here'southward an example with two:

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

The result is:

Like print, printf does not append 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 social club, and then inch is displayed using \%d, and cm is displayed using \%f.

Learning about format strings is like learning a sub-language within Java. There are many options, and the details tin can be overwhelming. Table 3.1 lists a few common uses, to give you an idea of how things work. For more details, refer to the documentation of java.util.Formatter. The easiest way to observe documentation for Coffee classes is to practice a spider web search for "Java" and the name of the class.

\%d decimal integer 12345
\%08d padded with zeros, at least 8 digits wide 00012345
\%f floating-point half dozen.789000
\%.2f rounded to 2 decimal places 6.79

Table iii.i: Example format specifiers

3.7  Centimeters to inches

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

inch = cm / CM_PER_INCH; // syntax error

But the result is an error – yous get something like, "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 way to convert a floating-bespeak value to an integer is to use a type bandage, and then called because it molds or "casts" a value from one blazon to some other. The syntax for blazon casting is to put the proper name of the type in parentheses and utilise it every bit an operator.

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

The (int) operator has the event of converting what follows into an integer. In this example, 10 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.

Type casting takes precedence over arithmetics operations. In this example, the value of pi gets converted to an integer before the multiplication. Then the result is lx.0, not 62.0.

double pi = iii.14159; double ten = (int) pi * 20.0;

Keeping that in heed, hither's how nosotros tin 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 earlier the type cast. And the result is rounded toward zero; we will meet in the side by side affiliate how to round floating-bespeak numbers to the closest integer.

3.8  Modulus operator

Let's take the example one footstep further: suppose you take a measurement in inches and you want to convert to feet and inches. The goal is dissever past 12 (the number of inches in a foot) and keep the remainder.

We have already seen the segmentation operator (/), which computes the caliber of ii numbers. If the numbers are integers, it performs integer partition. Java also provides the modulus operator (\%), which divides ii numbers and computes the rest.

Using division and modulus, we can convert to anxiety and inches similar this:

quotient = 76 / 12; // sectionalisation residue = 76 % 12; // modulus

The get-go line yields 6. The 2d line, which is pronounced "76 mod 12", yields 4. So 76 inches is half dozen feet, 4 inches.

The modulus operator looks like a per centum sign, but you might detect information technology helpful to recall of information technology as a division sign (÷) rotated to the left.

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

three.9  Putting it all together

At this indicate, yous have seen enough Coffee to write useful programs that solve everyday problems. You can (1) import Coffee library classes, (two) create a Scanner, (3) become input from the keyboard, (4) format output with printf, and (v) split and mod integers. Now we will put everything together in a consummate program:

Although not required, all variables and constants are declared at the top of chief. This exercise makes it easier to find their types later on, and it helps the reader know what data is involved in the algorithm.

For readability, each major step of the algorithm is separated past a blank line and begins with a comment. It also includes a documentation comment ( /** ), which nosotros'll learn more about in the next chapter.

Many algorithms, including the Convert programme, perform division and modulus together. In both steps, you dissever by the same number (IN_PER_FOOT).

When statements get long (generally wider than 80 characters), a common manner convention is to suspension them across multiple lines. The reader should never accept to scroll horizontally.

3.10  The Scanner bug

At present that you've had some experience with Scanner, there is an unexpected behavior we want to warn you about. The following code fragment asks users for their proper noun and age:

Organisation.out.print("What is your name? "); name = in.nextLine(); System.out.print("What is your age? "); age = in.nextInt(); Arrangement.out.printf("Hello %southward, age %d\n", name, age);

The output might look something like this:

Hello Grace Hopper, age 45

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

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

Endeavor running this example 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 have to empathise that the Scanner doesn't come across input as multiple lines, like we do. Instead, information technology gets a "stream of characters" every bit shown in Figure 3.iii.

Effigy three.iii: A stream of characters as seen by a Scanner.

The arrow indicates the next character to be read by Scanner. When you call nextInt, information technology reads characters until it gets to a non-digit. Figure 3.4 shows the state of the stream later nextInt is invoked.

Figure three.four: A stream of characters afterward nextInt is invoked.

At this bespeak, nextInt returns 45. The programme then displays the prompt "What is your name? " and calls nextLine, which reads characters until it gets to a newline. But since the side by side graphic symbol is already a newline, nextLine returns the empty string "" .

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

System.out.print("What is your age? "); age = in.nextInt(); in.nextLine(); // read the newline Organisation.out.print("What is your proper name? "); name = in.nextLine(); System.out.printf("How-do-you-do %s, age %d\n", name, age);

This technique is mutual when reading int or double values that appear on their own line. First you lot read the number, and so you read the rest of the line, which is only a newline character.

iii.11  Vocabulary

package:
A group of classes that are related to each other.
address:
The location of a value in computer retentivity, oftentimes represented as a hexadecimal integer.
library:
A drove of packages and classes that are bachelor for use in other programs.
import statement:
A statement that allows programs to use classes defined in other packages.
token:
A bones element of a program, such as a word, space, symbol, or number.
literal:
A value that appears in source lawmaking. For example, "Hi" is a string literal and 74 is an integer literal.
magic number:
A number that appears without explanation every bit role of an expression. It should generally be replaced with a constant.
constant:
A variable, declared final , whose value cannot be changed.
format string:
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 respective value.
blazon cast:
An performance that explicitly converts one information blazon into another. In Java it appears as a type name in parentheses, like (int).
modulus:
An operator that yields the remainder when one integer is divided past another. In Coffee, it is denoted with a percent sign; for example, 5 \% two is 1.

three.12  Exercises

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

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

Practice 1 When y'all use printf, the Coffee compiler does not check your format cord. See what happens if you try to brandish a value with blazon int using \%f. And what happens if you display a double using \%d? What if you utilise two format specifiers, but then only provide one value?

Exercise two Write a programme that converts a temperature from Celsius to Fahrenheit. It should (1) prompt the user for input, (2) read a double value from the keyboard, (iii) calculate the result, and (iv) format the output to one decimal place. For case, it should brandish "24.0 C = 75.2 F".

Here is the formula. Exist careful not to apply 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, (3) calculate the effect, and (4) employ printf to display the output. For example, "5000 seconds = 1 hours, 23 minutes, and 20 seconds".

Hint: Employ the modulus operator.

Exercise 4 The goal of this exercise is to program a "Guess My Number" game. When it'south finished, it will work similar this:

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

To choose a random number, you can apply the Random class in java.util. Here's how it works:

Like the Scanner class we saw in this chapter, Random has to be imported earlier we tin can use it. And every bit nosotros saw with Scanner, we have to apply the new operator to create a Random (number generator).

Then nosotros tin use the method nextInt to generate a random number. In this example, the result of nextInt(100) will exist betwixt 0 and 99, including both. Adding ane yields a number between 1 and 100, including both.

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

smithswence.blogspot.com

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

0 Response to "How to Ask User to Enter Choice Again Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel