1. Trang chủ
  2. » Công Nghệ Thông Tin

Java Programming for absolute beginner- P4 ppt

20 427 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 20
Dung lượng 528,85 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Getting Simple User Input Thus far, the programs you have written have been one-sided in that they per-form specific tasks and do not accept any user input.. Any-time the user runs the a

Trang 1

//The value of b will be 1

//The addition happens first because of the parentheses //Next the division and then the subtraction.

int b = 10 - (4 + 14) / 2;

System.out.println(“10 - (4 + 14) / 2 = “ + b);

//The value of c will be -1 int c = 10 - (4 + 14 / 2);

System.out.println(“10 - (4 + 14 / 2) = “ + c);

}

}

38

J a

s o

l ut

n e

FIGURE 2.5

This demonstrates how parentheses affect operator precedence.

Getting Simple User Input

Thus far, the programs you have written have been one-sided in that they per-form specific tasks and do not accept any user input Every time you run these programs the output is exactly the same, making them all but useless in the eyes

of a user after the first few times they are run How can you make procedures more dynamic? By adding the functionality to accept and use user input Any-time the user runs the application, he or she can enter different input, causing the program to have the capability to have different output each time it is run Because programmers write programs in the real world to be useful to users, this almost always means that the programs provide some interface that accepts user input The program then processes that input and spits out the result Accepting command-line input is a simple way to allow users to interact with your pro-grams In this section, you will learn how to accept and incorporate user input into your Java programs What follows is a listing of the HelloUserapplication:

Trang 2

* HelloUser

* Demonstrates simple I/O

*/

import java.io.*;

public class HelloUser { public static void main(String args[]) { String name;

BufferedReader reader;

reader = new BufferedReader(new InputStreamReader(System.in));

System.out.print(“\nWhat is your name? “);

try { name = reader.readLine();

System.out.println(“Hello, “ + name + “!”);

} catch (IOException ioe) { System.out.println(“I/O Exception Occurred”);

} }

}

As you can see in Figure 2.6, the program prints a message asking for the user’s name After that the cursor blinks awaiting user input In Figure 2.7 you see that the user entered her name, “Roseanne” and the application read it in and then printed “Hello, Roseanne!”

39

i a

l e

FIGURE 2.6

The user is prompted for his or her name, which is accepted through standard input.

Trang 3

Using the BufferedReader Class

Unfortunately, getting simple user input is not very straightforward One might think it would make sense that the syntax for reading a line would be as simple

as writing a line of output However, this is not the case As you know, writing standard output can be done like this:

System.out.println(“Shampoo is better!”);

So, it would be natural to think reading input could be done like this:

System.in.readln();

But it is not that simple First you must import the java.iopackage, which pro-vides functionality for system input and output:

import java.io.*;

A package is a group of complimentary classes that work together to provide a

larger scale of functionality This is the second Java program you’ve written that uses the import statement In the HelloWebapplet from Chapter 1, you imported

differ-ence here is that you use an asterisk to signify that you might be interested in all the classes that the java.iopackage groups together Basically, you are import-ing the java.iopackage here to give your program the capability to call upon the I/O functionality Specifically, it allows you to use the BufferedReaderand

under-stand anything about these classes except that InputStreamReader reads the user’s input and BufferedReaderbuffers the input to make it work more effi-ciently

You can think of a buffer as sort of a middle man I hear the Corleone family had

a lot of buffers When reading data in, a program has to make a system call, which can take a relatively long time (in computer-processing terms) To make up for this, the buffering trick is used Instead of making a system call each time you

40

J a

s o

l ut

n e

FIGURE 2.7

The program says hello to the user after she enters her name.

Trang 4

need a piece of data, the buffer temporarily stores a chunk of data before you ask for it using only one system call The buffer is then used to get data for subse-quent requests because accessing memory is much faster than using a bunch of system calls

Inside the main()method, you declared two variables:

String name;

BufferedReader reader;

Neither of them is a primitive data type They are both instances of classes The namevariable is declared to be a String, giving it the capability to hold strings, which are covered in the next section, and readeris declared to be a

speci-fies readerto be a standard input buffer:

reader = new BufferedReader(new InputStreamReader(System.in));

In this program you used a slightly different approach to printing a line of output.

You used the System.out.print() method instead of the System.out.print-ln() method What’s the difference? The System.out.println() method prints

a message to the screen and then adds a carriage return to the end of it The System.out.print() method does not add a carriage return to the end of the output line As you see in Figures 2.6 and 2.7, the computer prompts the user for his or her name and the user types the name on the same line as the prompt It is also important to note that you used a newline character escape code \n within the string passed to System.out.print() method This moves the cursor down one line before printing the message.

After you have instantiated the BufferedReader object, which you have stored in

prompts the user

name = reader.readLine();

Confused? That’s okay if you are The important thing here is that you learn the syntax for accepting user input Bear with me, this concept, as well as others, become clearer later on You’ll use this method of obtaining simple user input in these early chapters to create command prompt-based games until you learn graphic user interface (GUI) programming later

Handling the Exceptions

Although exception handling is covered in more detail later in this book, I feel that I should explain the basics of it here because you are required to handle

exceptions in this application Exceptions are encountered when code does not

H I N T

41

i a

l e

Trang 5

work as it is expected to Exception handling is used to plan a course of action in the event your code does not work as you expect it to Here is an analogy to help you digest this concept You have to go to work or school every normal weekday, right? Well, what if there is a blizzard or a tornado and you cannot go to work?

In this analogy, the blizzard or tornado is the exception because it is an abnor-mality The way this exception is handled is that you end up staying home from work

Java requires that exceptions be handled in certain situations In the HelloUser application, you are required to handle an IOException(input/output exception) What if you never actually get the user’s input here? This would be an exception and you would not be able to incorporate the user’s name in the program’s out-put In the case of this application, you issue an error message, indicating that

an exception was encountered You do not say “Hello” to the user—you can’t because you were not able to retrieve the user’s name

You handled exceptions in the HelloUser application by using the try…catch structure Any code, such as reading user input that might cause an exception, is placed within the tryblock, or “clause” Remember that a block is one or more statements enclosed within a set of curly braces:

try { name = reader.readLine();

System.out.println(“Hello, “ + name + “!”);

} Here, you are trying to read user input and use it in a standard output line What

if it doesn’t work? That’s what the catchclause is for:

catch (IOException ioe) { System.out.println(“I/O Exception Occurred”);

}

If the code within the tryclause does not work as it is expected to—there is an

message “I/O Exception Occurred”is printed to standard output to let the users know that a problem was encountered In the real world, you try to handle exceptions as gracefully as you can When detecting exceptions, you should try

to handle them in a way so that your program uses default values instead of halt-ing abruptly, but in some instances, your program just can’t continue due to some error that you can’t provide a work-around for In these cases, you should

at the very least, try to generate meaningful error messages so that users can use them to resolve any possible problems on their end

42

J a

s o

l ut

n e

Trang 6

The Math Game

In this section you incorporate much of what you’ve learned so far into a single application After you write and compile this application, you can actually use it

as a tool to remind yourself how arithmetic operators work in Java Here is a list-ing of the source code for MathGame.java:

/*

* MathGame

* Demonstrates integer math using arithmetic operators

*/

import java.io.*;

public class MathGame { public static void main(String args[]) { int num1, num2;

BufferedReader reader;

reader = new BufferedReader(new InputStreamReader(System.in));

try { System.out.print(“\nFirst Number: “);

num1 = Integer.parseInt(reader.readLine());

System.out.print(“Second Number: “);

num2 = Integer.parseInt(reader.readLine());

reader.close();

} // Simple Exception Handling catch (IOException ioe) { System.out.println(“I/O Error Occurred, using 1 ”);

num1 = num2 = 1;

} catch (NumberFormatException nfe) { System.out.println(“Number format incorrect, using 1 ”);

num1 = num2 = 1;

} //Avoid this pitfall e.g 1 + 1 = 11:

//System.out.println(num1 + “ + “ + num2 + “ = “ + num1 + num2);

System.out.println(num1 + “ + “ + num2 + “ = “ + (num1 + num2));

System.out.println(num1 + “ - “ + num2 + “ = “ + (num1 - num2));

System.out.println(num1 + “ * “ + num2 + “ = “ + (num1 * num2));

System.out.println(num1 + “ / “ + num2 + “ = “ + (num1 / num2));

System.out.println(num1 + “ % “ + num2 + “ = “ + (num1 % num2));

} }

43

i a

l e

Trang 7

Parsing Strings to Numbers

Most of the code in the MathGameapplication should already be familiar to you The code that is new to you is the code that parses a string value into an integer value:

Integer.parseInt(reader.readLine());

Parsing, just like casting, is changing the data type of the value of a variable or

lit-eral The BufferedReader.readLine()method accepts the users input in string form You cannot assign strings to intvariables or perform mathematical opera-tions on them, so you must first convert them to numbers For instance, you can’t do this:

int myNumber = “8”;

An int variable can only store a valid int value, but in the line above “8” is expressed as a Stringliteral, not an int Because you need to accept user input here in string form, you need a way to parse the Stringinput to an int

accepts a Stringargument and returns the intvalue of that string For example

if the Stringliteral “8”is passed to this method, it returns the int 8 Here are some useful methods for converting strings to numbers:

As shown in Figure 2.8, this program prompts the user for two integers and then performs arithmetic operations on them It displays the results of these opera-tions to the user It’s not exactly a game, unless math is fun for you, but you get the point

44

J a

s o

l ut

n e

FIGURE 2.8

The MathGame

application demonstrates mathematical operations applied

to integers.

Trang 8

i a

l e

Float.parseFloat(String s) Converts a string to a float

Double.parseDouble(String s) Converts a string to a double

The string passed to a method that parses it to another data type must be a valid representation of that data type For example, if you tried to parse the String

“one” to an integer using Integer.parseInt() , it would cause a NumberFormatException , however, it is not required that you handle this excep-tion, although you do in the MathGame application by simply using the int 1 if user input isn’t obtained If you don’t handle the NumberFormatException , your program will crash if the user types a value that cannot be parsed to an int

The TipCalculator Application

Here is another program for you to take a look at It uses concepts of the Math-Gameand TipAdderapplications It prompts the user for the price of the meal, converts the Stringvalue of the user’s input into a double and then calculates the tip and displays the information to the user Take a look at the source code:

/*

* TipCalculator

* Parses user input and does floating point math

*/

import java.io.*;

public class TipCalculator { public static void main(String args[]) { String costResponse;

double meal, tip, total;

BufferedReader reader;

reader = new BufferedReader(new InputStreamReader(System.in));

System.out.print(“\nHow much was the meal? “);

try { costResponse = reader.readLine();

// Note: we are not handling NumberFormatException meal = Double.parseDouble(costResponse);

tip = meal * 0.15;

total = meal + tip;

System.out.println(“The meal costs $” + meal);

System.out.println(“The 15% tip is $” + tip);

System.out.println(“The total is $” + total);

reader.close();

}

T R A P

Trang 9

catch (IOException ioe) { System.out.println(“I/O Exception Occurred”);

} }

} Figure 2.9 shows the output of this program Notice that this calculation is more precise than in the TipAdderprogram That’s because you used doublesinstead

2.10 shows what happens when you don’t get the doublevalue you expect

46

J a

s o

l ut

n e

FIGURE 2.9

The output of the

TipCalculator

application.

FIGURE 2.10

Oops, my program crashed! I didn’t type a valid double

value.

Accepting Command-Line Arguments

As mentioned in Chapter 1, it is possible to pass command-line arguments to

your application Command-line arguments are parameters that are passed to the

program when it is initially started up This is done, as you’d imagine, from the

Trang 10

command prompt You pass parameters to an application by using the following syntax when running the application:

java ApplicationName command_line_arguments When using a Macintosh, you will be prompted for any command-line arguments when you run your application Command-line arguments are passed to the

para-meters, so you can handle it like any other array You learn about arrays in the next chapter For now, you can just write the following application to give your-self a basic idea of how Java can accept and use command-line arguments

/*

* HelloArg

* Uses command-line arguments

*/

public class HelloArg { public static void main(String args[]) { System.out.println(“Hello, “ + args[0] + “!”);

}

}

As you can see in Figure 2.11, I ran this procedure three times using different command-line arguments causing the application to issue different output By the way, I wouldn’t make the last guy angry, you wouldn’t like him very much if

he gets angry

47

i a

l e

I N THE R EAL W ORLD

Command-line arguments are used for a number of different purposes in the real world They are used as parameters that affect the way the program runs.

Command-line arguments can exist to allow the user certain options while run-ning your program One other major use of command-line arguments from a programmer’s standpoint is to aid in debugging or testing your code You can use a command-line argument to set some sort of debug-mode parameter With this debug mode set, you can debug your code by giving yourself special options that would not normally be available For example, say you are a video game programmer You need to test a particular game level, but it is a particu-larly difficult level for you to get through or would be time consuming You can use a command-line argument that gives you access to any position in any level

of the game you’re programming, so you can just test the parts you need to.

Ngày đăng: 03/07/2014, 05:20

TỪ KHÓA LIÊN QUAN