printf方法和Scanner类

时间:2015-02-17 22:58:32

标签: java

我最近编写了一个程序,我必须使用对话框来捕获输入和输出信息。以下是其中一个陈述:

packageType = 
   JOptionPane.showInputDialog(Enter the customer's package (A,B, or C): ");

我现在必须再次编写它,但使用printf方法。我试着这样写:

System.out.printf("Enter the customer's package (A, B, or C): %-10s",
packageType = input.nextLine());

我无法让它工作,我不确定这是否是正确的做法。我是Java新手,我很感激帮助。

2 个答案:

答案 0 :(得分:1)

我自己对Java很陌生,但它看起来很简单:

Scanner input = new Scanner (System.in);

System.out.println ("Enter the customer's package type: A, B, or C:");
packageType = input.nextLine();
System.out.printf ("The customer's package type is %s.", packageType);

System.out.printf仅用于输出文本。它允许您以不同的方式对其进行格式化,但它不用于捕获输入。这个例子并没有真正做很多格式化(它只是一个字母)。

我希望这会有所帮助。

吉姆

答案 1 :(得分:0)

如果你不包含第二个参数,printf可以像print和println一样工作:System.out.printf("String", notInclude);所以用这种方式编码来传递输入:

Scanner input = new Scanner(System.in);

System.out.printf("Enter the customer's package type: A, B, or C:");
String packageLetter = input.nextLine();