Input and Output(easy to use)

本文介绍如何使用Java的Scanner类从控制台读取用户输入,并展示如何格式化输出。此外,还提供了在JDK 5.0之前版本中读取输入的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Input and Output
To make our example programs more interesting, we want to accept input and properly format the program output. Of course, modern programs use a GUI for collecting user input. However, programming such an interface requires more tools and techniques than we have at our disposal at this time. Because the first order of business is to become more familiar with the Java programming language, we make do with the humble console for input and output for now. GUI programming is covered in Chapters 7 through 9.
Reading Input
You saw that it is easy to print output to the "standard output stream" (that is, the console window) just by calling System.out.println. Oddly enough, before JDK 5.0, there was no convenient way to read input from the console window. Fortunately, that situation has finally been rectified.
To read console input, you first construct a Scanner that is attached to the "standard input stream" System.in.
Scanner in = new Scanner(System.in);
Now you use the various methods of the Scanner class to read input. For example, the nextLine method reads a line of input.
System.out.print("What is your name? ");
String name = in.nextLine();
Here, we use the nextLine method because the input might contain spaces. To read a single word (delimited by whitespace), call
String firstName = in.next();
To read an integer, use the nextInt method.
System.out.print("How old are you? ");
int age = in.nextInt();
Similarly, the nextdouble method reads the next floating-point number.
The program in Example 3-2 asks for the user's name and age and then prints a message like
Hello, Cay. Next year, you'll be 46
Finally, add the line
import java.util.*;
at the beginning of the program. The Scanner class is defined in the java.util package. Whenever you use a class that is not defined in the basic java.lang package, you need to use an import directive. We look at packages and import directives in more detail in Chapter 4.
Example 3-2. InputTest.java
 1. import java.util.*;
 2.
 3. public class InputTest
 4. {
 5.    public static void main(String[] args)
 6.    {
 7.       Scanner in = new Scanner(System.in);
 8.
 9.       // get first input
10.       System.out.print("What is your name? ");
11.       String name = in.nextLine();
12.
13.       // get second input
14.       System.out.print("How old are you? ");
15.       int age = in.nextInt();
16.
17.       // display output on console
18.       System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));
19.    }
20. }
NOTE

 If you do not have JDK 5.0 or above, you have to work harder to read user input. The simplest method is to use an input dialog (see Figure 3-6).

String input = JOptionPane.showInputDialog(promptString)
The return value is the string that the user typed.
For example, here is how you can query the name of the user of your program:
String name = JOptionPane.showInputDialog("What is your name?");
Reading numbers requires an additional step. The JOptionPane.showInputDialog method returns a string, not a number. You use the Integer.parseInt or Double.parseDouble method to convert the string to its numeric value. For example,
String input = JOptionPane.showInputDialog("How old are you?");
int age = Integer.parseInt(input);
If the user types 45, then the string variable input is set to the string "45". The Integer.parseInt method converts the string to its numeric value, the number 45.
The JOptionPane class is defined in the javax.swing package, so you need to add the statement
import javax.swing.*;
Finally, whenever your program calls JOptionPane.showInputDialog, you need to end it with a call to System.exit(0). The reason is a bit technical. Showing a dialog box starts a new thread of control. When the main method exits, the new thread does not automatically terminate. To end all threads, you call the System.exit method. (For more information on threads, see Chapter 1 of Volume 2.) The following program is the equivalent to Example 3-2 prior to JDK 5.0.
import javax.swing.*;
public class InputTest
{
   public static void main(String[] args)
   {
      String name = JOptionPane.showInputDialog("What is your name?");
      String input = JOptionPane.showInputDialog("How old are you?");
      int age = Integer.parseInt(input);
      System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));
      System.exit(0);
   }

Objectives of this Assignment 1. Declare arrays of different types dynamically. 2. Iterate through arrays, processing all of the elements. 3. Write methods with arrays as parameters and return values。 In this assignment you will create your own class and write the methods in it. The class you write is called Main and it has four methods that build arrays and four methods that process arrays. All methods should be public and static. Create a project called P7_4 and a class named Main in a file called Main.java, then follow the instructions below exactly: 1. Write a method named createChars that extracts the characters from a string and builds an array with them. The method takes a parameter of type String and returns an array of characters. Hint: the size of this array is very easy to determine. 2.Write a method called translateChars that takes an array of characters and returns an array of integers with the values that correspond to each element of the character array. For example, the character 'A' will be translated to 65, the character '0' will be translated to 48, and the character '%' will be translated to 37. The integer array returned should be of the same size as the array of characters passed in. 3.Add a main method with the usual signature that instantiates the Main class and tests its methods as follow: public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); // Create arrays char[] charArray = createChars(str); // Test processing System.out.println(Arrays.toString(translateChars(charArray))); in.close(); } Input Specification: There are one line in the input . Output Specification: For each case, output the array that is translated. NOTE: You must use methods to sovle this problem. Sample Input: Java1234!& Sample Output: [74, 97, 118, 97, 49, 50, 51, 52, 33, 38] 代码长度限制 16 KB 时间限制 400 ms 内存限制 64 MB 栈限制
最新发布
03-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值