我想获取用户输入并将最后一个值的默认值设置为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
答案 0 :(得分:1)
我将如何解决它:
int x = 0;
和int y = 0;
没有任何效果,但我们这样做是为了让编译器不会抱怨打印尚未初始化的值。然后初始化z = 1;
String inputString = scan.nextLine();
split()
方法将该行转换为字符串数组。 (用空格分隔作为我们的分隔符)输出(输入第一行,从程序输出第二行): 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);
}
}