我尝试按以下顺序接受4个整数值,4个浮点值和3个字符。无论我尝试键入什么内容,我都难以接受字符并不断出现错误。我同时尝试了char_value1 = charval.next();
和此char_value1 = charval.nextChar();
我在做什么错,我该如何更改才能正常工作?
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
// Four integer values
int int_value1;
int int_value2;
int int_value3;
int int_value4;
// Four double values
double dbl_value1;
double dbl_value2;
double dbl_value3;
double dbl_value4;
// Three character values
char char_value1;
char char_value2;
char char_value3;
// Number value scanner here
Scanner numval = new Scanner(System.in);
// Prompt user to enter 4 integer values
System.out.println("Enter 4 integer values below with a space in between");
// 4 integer values set in order as they were entered
int_value1 = numval.nextInt();
int_value2 = numval.nextInt();
int_value3 = numval.nextInt();
int_value4 = numval.nextInt();
// Prompt user to enter 4 float values
System.out.println("\nEnter 4 floating values below with a space in between");
// 4 float values set in order as they were entered
dbl_value1 = numval.nextDouble();
dbl_value2 = numval.nextDouble();
dbl_value3 = numval.nextDouble();
dbl_value4 = numval.nextDouble();
numval.close();
// Character value scanner here
Scanner charval = new Scanner(System.in);
System.out.println("\nEnter any 3 characters below with a space in between");
char_value1 = charval.nextChar();
char_value2 = charval.nextChar();
char_value3 = charval.nextChar();
charval.close();
最佳答案
不需要多台扫描仪,您可以使用一个扫描仪进行所有输入,然后使用next()。chatAt(0)
获取角色输入
这是您的工作代码
import java.util.Scanner;
public class code {
public static void main(String[] args) {
// Four integer values
int int_value1;
int int_value2;
int int_value3;
int int_value4;
// Four double values
double dbl_value1;
double dbl_value2;
double dbl_value3;
double dbl_value4;
// Three character values
char char_value1;
char char_value2;
char char_value3;
// Number value scanner here
Scanner numval = new Scanner(System.in);
// Prompt user to enter 4 integer values
System.out.println("Enter 4 integer values below with a space in between");
// 4 integer values set in order as they were entered
int_value1 = numval.nextInt();
int_value2 = numval.nextInt();
int_value3 = numval.nextInt();
int_value4 = numval.nextInt();
// Prompt user to enter 4 float values
System.out.println("\nEnter 4 floating values below with a space in between");
// 4 float values set in order as they were entered
dbl_value1 = numval.nextDouble();
dbl_value2 = numval.nextDouble();
dbl_value3 = numval.nextDouble();
dbl_value4 = numval.nextDouble();
System.out.println("\nEnter any 3 characters below with a space in between");
char_value1 = numval.next().charAt(0);
char_value2 = numval.next().charAt(0);
char_value3 = numval.next().charAt(0);
}
}