扫描仪输入数据类型

时间:2013-08-04 17:30:47

标签: java java.util.scanner

我需要编写一个测试类来执行以下操作:

  • 一个。让用户输入一个整数并显示它。
  • 湾让用户输入一个浮点值并显示它。
  • ℃。让用户输入他/她的名字(没有空格)并显示 名称为:“Hello <name>, welcome to Scanner!”
  • d。让用户输入一个字符并显示它。
  • 即让用户输入任何字符串(带有空格)并显示它。

我的问题是,如何只扫描一个Character并显示它?在数字2中,如何输入带有空格的String并显示它? (字母“d”和“e”)

我一直在寻找,但我找不到最简单的解决方案(因为我是Java和编程的新手)。

到目前为止,这是我的代码:

package aw;

import java.io.PrintStream;
import java.util.Scanner;

public class NewClass1
{
  public static void main(String[] args)
  {
      int num;
      double num2;
      String name;
      char c;
          Scanner sc = new Scanner(System.in);
          PrintStream ps = new PrintStream(System.out);

      //for integer
      System.out.println("Enter a number: ");
      num = sc.nextInt();
      ps.printf("%d\n", num);

      //for float
      System.out.println("Enter a float value: ");
      num2 = sc.nextDouble();
      ps.printf("%.2f\n", num2);

      //for name w/o white space
      System.out.print("Enter your first name: ");
      name = sc.next();
      ps.printf("Hello %s, welcome to Scanner\n", name);


      //for character
      System.out.print("Enter a character: ");
      c = sc.findWithinHorizon(".", 0).charAt(0);
      System.out.print(“%c”, c);

      //for name w/ white space
      System.out.print("Enter your full name: ");
      name = sc.nextLine();
      System.out.print(“%s”, name);
  }
}

我希望你能帮助我。谢谢!

3 个答案:

答案 0 :(得分:2)

首先,没有必要在System.out中包含PrintStream,因为out已经支持使用format()printf()方法进行格式化。

接下来,您需要了解当您输入一行数据时,您还会使用新行 \n来终止它。 next<Type>()方法仅使用<Type>而不使用其他内容。因此,如果next<Type>()来电可能与\n匹配,则您需要在之前使用其他\n跳过任何额外的新行 nextLine()

以下是修补程序的代码:

  int num;
  double num2;
  String name;
  char c;

  Scanner sc = new Scanner(System.in);

  //for integer
  System.out.print("Enter a number: ");
  num = sc.nextInt();
  System.out.printf("%d\n", num);

  //for float
  System.out.print("Enter a float value: ");
  num2 = sc.nextDouble();
  System.out.printf("%.2f\n", num2);

  //for name w/o white space
  System.out.print("Enter your first name: ");
  name = sc.next();
  System.out.printf("Hello %s, welcome to Scanner\n", name);

  //for character
  System.out.print("Enter a character: ");
  c = sc.findWithinHorizon(".", 0).charAt(0);
  System.out.printf("%c\n", c);

  sc.nextLine(); // skip

  //for name w/ white space
  System.out.print("Enter your full name: ");
  name = sc.nextLine();
  System.out.printf("%s", name);

答案 1 :(得分:0)

使用此:

  //for a single char
  char Character = sc.findWithinHorizon(".", 0).charAt(0);

  //for a name with white space
  System.out.print("Enter your full name: ");
      String name2 = sc.next();
      String surname = sc.next();
      System.out.println(name2 + " " + surname);

答案 2 :(得分:0)

使用Scanner.next(Pattern)并传递Pattern.compile("[A-Za-z0-9]")让扫描程序只接受定义的1个字符。
您可以将任何正则表达式作为参数传递并检查next()
{{{ 1}}用于包含空格的下一行

相关问题