我正在开发这个项目,允许用户在输出窗口中输入名称,但是他们不能输入数字。我无法弄清楚正确的代码行,使其无法输入数字(如果他们这样做会给他们一个错误信息)。
import java.util.*;
public class UserInput
{
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do
{
Collections.sort(list);
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y"))
{
System.out.println("Enter: ");
list.add(stdin.next());
}
else
{
break;
}
}
while (true);
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
public void add(String string) {
try {
double d = Double.parseDouble(string);
} catch(NumberFormatException e) {
// throw a exception or something.
return;
}
super.add(string);
return;
}
这是我的代码!
非常感谢您的帮助!
答案 0 :(得分:1)
对输入进行正则表达式测试
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Enter: ");
String strin = stdin.next();
if (isNumeric(strin)) {
System.out.println("Please enter a non numeric value");
} else {
list.add(strin);
}
Collections.sort(list);
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
} while (stdin.next().startsWith("y"));
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?");
}
}
答案 1 :(得分:0)
您可以创建一个扩展ArrayList
并覆盖add()
方法的类,检查给定的String
是否为数字。
import java.util.*;
public class UserInput
{
public static void main(String[] args)
{
List<String> list = new MyArrayList<String>();
Scanner stdin = new Scanner(System.in);
do
{
Collections.sort(list);
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y"))
{
System.out.println("Enter: ");
try {
list.add(stdin.next());
} catch (Exception e) {
// given string was a number.
}
}
else
{
break;
}
}
while (true);
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
class MyArrayList extends ArrayList<String> {
public void add(String string) {
try {
double d = Double.parseDouble(string);
} catch(NumberFormatException e) {
super.add(string);
return;
}
throw new Exception();
}
但您也需要覆盖其他“add
”方法。