Scanner keyboard = new Scanner(System.in);
System.out.println("Enter number of bars(min 1 / max 6): ");
int barNumbers = keyboard.nextInt();
while (barNumbers <= 0 || barNumbers >= 7) {
System.out.println("Enter number of bars(min 1 / max 6): ");
barNumbers = keyboard.nextInt();
}
int barHeights[] = new int[barNumbers];
int countForBars = 1;
for (int i = 0; i <= barNumbers - 1; i++) {
System.out.println(
"Enter height of bar " + countForBars + " of " + barNumbers + "(min 1 / max 7): ");
barHeights[i] = keyboard.nextInt();
while (barHeights[i] <= 0 || barHeights[i] >= 8) {
System.out.println(
"Enter height of bar " + countForBars + " of " + barNumbers + "(min 1 / max 7): ");
barHeights[i] = keyboard.nextInt();
}
countForBars += 1;
}
大家好,我需要一些帮助,这对你来说很容易,因为我是Java的初学者。 无论如何,我现在试图控制一个机器人手臂通过Java传达东西。 问题是,正如你在那里看到的那样,我设置了一些条件,只能获得1-6之间的整数。因此必须限制其余的输入,尤其是字符串。那么如何限制字符串输入而不是使用try catch东西呢?如果有任何有用的解决方案,我会很感激。干杯!抱歉代码指示。我不知道如何让它像代码一样:(
答案 0 :(得分:0)
可能您可以尝试以下代码:
public static boolean isInteger(String str) { //pass your "keyboard" string here.
if (str == null) { // if there is nothing entered in the String
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
}
for (i = 1; i < length; i++) {
char c = str.charAt(i);
if (c < '0' || c > '6') {
return false;
}
}
return true;
}