Java Reference
In-Depth Information
double price = sc.nextDouble();
System.out.format("Price of %s is: %.2f%n", item, price);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
How It Works
Here's how it works:
1.
The Scanner class wraps around a BufferedReader in this example, but can also be directly
applied to a string if so desired.
2.
Next, we set the delimiter pattern of the Scanner . A delimiter is a piece of string by which we want
to split up text fragments. By default, the delimiter of a Scanner equals all white-space characters
(newline, a space, a tab), but in our case, we change it to match either a comma followed by a
space (“, “) or a newline ( \r\n ).
3.
We also set the Locale of the Scanner to English to make sure the decimal prices are read in and
interpreted correctly. Locale is a Java provided class to represent geographical regions. Instead of
instantiating a new object, the class provides a series of static members (themselves Locale objects)
that can be accessed and used directly, such as Locale.ENGLISH or Locale.KOREA . Your computer
might already use English as a default locale, in which case this line can also be removed.
4.
Next, a while loop is iterated over so long as the Scanner is able to feed text fragments. If this is
the case, we know we can immediately read in two pieces of fragments at once—the item and the
price—using the nextDouble method.
5.
Note that we use the Pattern class here to supply a regular expression, a relatively advanced format
that specifies text patterns. Normally, you could also supply the delimiter as a single string, in which
case you might be tempted to try “, “, but this will not work, as the Scanner will then continue to
read text even after the end of a line is encountered, which we do not want in this case. Therefore,
as a general recommendation, it is best to either stick to newline delimiters only, or use a delimiter
that can be easily expressed as a single string, for instance “, “ and put all the data on the same line.
input and output from the command-line
You've seen how to use streams to perform input and output operations, e.g., to read and write data
to files. In the following section, we'll explore file I/O a bit deeper, but we first take a slight detour
in order to show off input and output with the command-line.
Although most programs you run on your computer nowadays offer some sort of Graphical User
Interface (GUI), this has not always been the case. In the old days of computing, programs often-
times only offered text-like communication possibilities, showing their output and taking input from
a so-called “console,” or command-line. Even in modern operating systems, this command-line
 
Search WWH ::




Custom Search