获取默认用户输入java

时间:2017-12-10 08:37:45

标签: java

我想获取用户输入并将最后一个值的默认值设置为1.我该怎么做?

private static void addone() {
Scanner scan = new Scanner(System.in)
    int x = scan.nextInt();
    int y = scan.nextInt();
    int z = scan.next();
    System.out.println(x + " " + y + " " + z)

因此,如果用户输入1 1 2,则该方法将打印1 1 2。 或者用户输入1 1并且方法打印1 1 1

1 个答案:

答案 0 :(得分:1)

我将如何解决它:

  • 设置x,y和z的默认值。默认情况下,Java中的int值的默认值为零。因此初始化int x = 0;int y = 0;没有任何效果,但我们这样做是为了让编译器不会抱怨打印尚未初始化的值。然后初始化z = 1;
  • 通过String inputString = scan.nextLine();
  • 阅读一行
  • 通过split()方法将该行转换为字符串数组。 (用空格分隔作为我们的分隔符)
  • 分别将数组的前三个值读入x,y和z。
  • 通过将上述语句包装在Try-Catch块
  • 中来捕获任何异常

输出(输入第一行,从程序输出第二行):     1     1 0 1

1 1
1 1 1

1 4
1 4 1

1 2 3
1 2 3

代码:

import java.util.Scanner;

class F {
  public static void main(String[] args) {

    addone();
  }

  private static void addone() {
    Scanner scan = new Scanner(System.in);
    String inputString = scan.nextLine();   // Read in a line

    int x = 0;  // Default value 0
    int y = 0;  // Default value 0
    int z = 1;  // Default value 1

    try {
      // Split the String by spaces
      String[] input = inputString.split(" ");

      // Get the first three integers from the list
      // If the list is longer, the rest will be
      // simply ignored. If the list is too short
      // an indexOutOfBoundsException will be thrown
      // but we will also catch it, and proceed with
      // the program
      x = Integer.parseInt(input[0]);
      y = Integer.parseInt(input[1]);
      z = Integer.parseInt(input[2]);

      // Catch a thrown Exception
    } catch (Exception e) {

      // Don't do anything.

    } 

    // Display the result:
    // If the Exception was thrown, the original
    // values will be printed, if there was no Exception
    // then the values will have been properly overriden
    System.out.println(x + " " + y + " " + z);

  }
}