
在java中,当我们需要用户输入一个固定长度的标识符(如8位id)时,一个常见的错误是将该标识符声明为基本数据类型int,然后尝试调用其length()方法来检查长度。例如,原始代码中存在以下逻辑:
int id; // ID被声明为int类型
// ...
while(id.length() != 8) // 错误发生在这里:int类型没有length()方法
{
System.out.print("Enter salesperson ID >> ");
id = input.nextInt();
}这里的问题在于,int是Java中的一个基本数据类型(primitive type),它不是一个对象,因此不具备任何方法,包括length()。只有像String这样的对象类型才拥有length()方法来获取其包含字符的数量。尝试对int类型的变量调用length()方法会导致编译错误:“int cannot be dereferenced”(int不能解引用),意味着你试图将一个基本类型当作对象来引用其方法。
解决这个问题的关键在于,无论ID是纯数字还是字母数字混合,都应该首先将其作为String类型读取。这样我们就可以利用String类提供的丰富方法进行长度检查、格式验证等操作。
如果您的ID允许包含字母和数字(即字母数字ID),那么最直接的方法是使用Scanner.nextLine()来读取完整的行作为字符串,然后检查其长度。
import java.util.Scanner;
public class InputValidationExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String id = "";
// 循环直到用户输入一个非空且长度为8的ID
while (id.isEmpty() || id.length() != 8) {
System.out.print("请输入8位销售员ID (字母数字): ");
id = input.nextLine().trim(); // 读取一行并去除首尾空白
if (id.isEmpty()) {
System.out.println("ID不能为空!请重新输入。");
} else if (id.length() != 8) {
System.out.println("无效的ID (" + id + ")!ID必须是8个字符长。请重新输入。");
id = ""; // 重置id,以便继续循环
}
}
System.out.println("销售员ID已成功录入: " + id);
input.close();
}
}代码解析:
立即学习“Java免费学习笔记(深入)”;
如果您的ID必须是纯数字且长度固定(例如8位数字),您仍然应该先将其作为String读取。在验证长度之后,还需要额外验证其内容是否全部为数字。如果验证通过,再将其转换为int或long类型(取决于数字大小)。
import java.util.Scanner;
public class NumericInputValidationExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String idString = "";
int salesmanID = 0; // 用于存储转换后的int类型ID
// 循环直到用户输入一个非空、长度为8且全部为数字的ID
while (idString.isEmpty() || idString.length() != 8 || !idString.matches("\d+")) {
System.out.print("请输入8位销售员ID (纯数字): ");
idString = input.nextLine().trim();
if (idString.isEmpty()) {
System.out.println("ID不能为空!请重新输入。");
} else if (idString.length() != 8) {
System.out.println("无效的ID (" + idString + ")!ID必须是8位数字。请重新输入。");
idString = ""; // 重置以便继续循环
} else if (!idString.matches("\d+")) { // 使用正则表达式检查是否全部为数字
System.out.println("无效的ID (" + idString + ")!ID必须全部由数字组成。请重新输入。");
idString = ""; // 重置以便继续循环
}
}
// 如果到达这里,说明输入是有效的8位数字字符串
try {
salesmanID = Integer.parseInt(idString); // 将字符串转换为int
System.out.println("销售员ID已成功录入: " + salesmanID);
} catch (NumberFormatException e) {
// 理论上,经过前面的正则验证,这里不会发生NumberFormatException
System.err.println("内部错误:无法将ID转换为数字。");
}
input.close();
}
}代码解析:
立即学习“Java免费学习笔记(深入)”;
现在,我们将上述解决方案集成到原始的CreateSalesperson程序中。假设Salesperson类的id字段和getId()方法期望一个int类型。
import java.util.*;
public class CreateSalesperson {
public static void main(String[] args) {
Salesperson[] salespeople = new Salesperson[20];
int count = 0;
char option;
Scanner input = new Scanner(System.in); // 最佳实践:在main方法中创建一次Scanner
System.out.print("Do you want to (A)dd, or (C)hange a record or (Q)uit >> ");
option = input.nextLine().charAt(0);
while (option != 'Q') {
if (option == 'A')
count = addOption(salespeople, count, input); // 传递Scanner实例
else if (option == 'C')
changeOption(salespeople, count, input); // 传递Scanner实例
else
System.out.println("Invalid entry");
System.out.print("Do you want to (A)dd, or (C)hange a record or (Q)uit >> ");
option = input.nextLine().charAt(0);
}
input.close(); // 在程序结束时关闭Scanner
}
public static int addOption(Salesperson[] array, int count, Scanner input) { // 接收Scanner实例
String name;
double sales;
boolean alreadyEntered;
int id = 0; // 声明为int,最终存储转换后的ID
if (count == array.length) {
System.out.println("Sorry - array is full -- cannot add a record");
} else {
System.out.print("Enter name of salesperson >> ");
name = input.nextLine();
String idString = ""; // 用于接收字符串形式的ID
while (idString.isEmpty() || idString.length() != 8 || !idString.matches("\d+")) {
System.out.print("Enter salesperson ID (8 digits) >> ");
idString = input.nextLine().trim();
if (idString.isEmpty()) {
System.out.println("ID不能为空!请重新输入。");
} else if (idString.length() != 8) {
System.out.println("无效的ID (" + idString + ")!ID必须是8位数字。请重新输入。");
idString = "";
} else if (!idString.matches("\d+")) {
System.out.println("无效的ID (" + idString + ")!ID必须全部由数字组成。请重新输入。");
idString = "";
}
}
id = Integer.parseInt(idString); // 转换为int
alreadyEntered = false;
for (int x = 0; x < count; ++x) {
if (array[x].getId() == id) {
System.out.println("Sorry -- ID number already exists");
alreadyEntered = true;
break; // 找到重复ID后即可退出循环
}
}
if (!alreadyEntered) {
System.out.print("Enter sales amount >> ");
// 注意:由于前面使用了nextLine(),这里可以直接用nextDouble(),但如果前面是nextInt(),则需要额外的nextLine()
sales = input.nextDouble();
input.nextLine(); // 消耗nextDouble()留下的换行符
array[count] = new Salesperson(id, sales, name);
++count;
}
}
display(array, count);
return count;
}
public static void changeOption(Salesperson[] array, int count, Scanner input) { // 接收Scanner实例
int position = 0;
int idToChange = 0; // 用于存储转换后的ID
double sales;
if (count == 0) {
System.out.println("Database is empty -- cannot change record");
} else {
String idString = ""; // 用于接收字符串形式的ID
while (idString.isEmpty() || idString.length() != 8 || !idString.matches("\d+")) {
System.out.print("Enter ID to change (8 digits) >> ");
idString = input.nextLine().trim();
if (idString.isEmpty()) {
System.out.println("ID不能为空!请重新输入。");
} else if (idString.length() != 8) {
System.out.println("无效的ID (" + idString + ")!ID必须是8位数字。请重新输入。");
idString = "";
} else if (!idString.matches("\d+")) {
System.out.println("无效的ID (" + idString + ")!ID必须全部由数字组成。请重新输入。");
idString = "";
}
}
idToChange = Integer.parseInt(idString); // 转换为int
boolean exists = false;
for (int x = 0; x < count; ++x) {
if (array[x].getId() == idToChange) {
exists = true;
position = x;
break; // 找到ID后即可退出循环
}
}
if (!exists) {
System.out.println("Sorry - ID number #" + idToChange + " does not exists in the database");
} else {
System.out.print("Enter new sales amount >> ");
sales = input.nextDouble();
input.nextLine(); // 消耗nextDouble()留下的换行符
array[position].setSales(sales);
}
display(array, count);
}
}
// Salesperson class (假设存在,并包含id, sales, name字段及相应的getter/setter)
static class Salesperson {
private int id;
private double sales;
private String name;
public Salesperson(int id, double sales, String name) {
this.id = id;
this.sales = sales;
this.name = name;
}
public int getId() {
return id;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
public String getName() {
return name;
}
}
public static void display(Salesperson[] array, int count) {
// ... (display方法保持不变,或根据需要进行优化)
// 原始代码中的排序逻辑有误,应比较array[b].getId() 和 array[b+1].getId(),并根据需要交换整个Salesperson对象
// 并且,如果目标是按ID排序,条件应该是 if (array[b].getId() > array[b + 1].getId())
// 这里仅修正为正确的比较和交换,以避免运行时错误,但排序逻辑可能需要进一步检查。
int a, b;
Salesperson temp;
int highSubscript = count - 1;
for (a = 0; a < highSubscript; ++a) {
for (b = 0; b < highSubscript - a; ++b) { // 改进冒泡排序的内层循环范围
if (array[b].getId() > array[b + 1].getId()) { // 假设按ID升序排序
temp = array[b];
array[b] = array[b + 1];
array[b + 1] = temp;
}
}
}
System.out.println("
Current database:");
for (a = 0; a < count; ++a) {
System.out.println("NAME: " + array[a].getName() + " ID: #" + array[a].getId() + " Sales Amount: $" + array[a].getSales());
}
System.out.println();
}
}集成要点:
以上就是Java用户输入固定长度字符:避免“int不能解引用”错误与输入验证实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号