【发布时间】:2017-03-09 00:22:07
【问题描述】:
我能够让程序运行并使用错误检查来确保用户输入实际上是一个 int。我遇到的问题是我只希望它是一个 3 位数的整数。我无法将它放到正确的位置:
import java.util.*;
public class listMnemonics
{
public static void main(String[] args)
{
//Defines the "keypad" similar to that of a phone
char[][] letters =
{{'0'},{'1'},{'A','B','C'},{'D','E','F'},{'G','H','I'},{'J','K','L'},
{'M','N','O'},{'P','Q','R','S'},{'T','U','V'},{'W','X','Y','Z'}};
//Creates the Scanner
Scanner scan = new Scanner(System.in);
这就是我需要实现它的地方,我遇到了这个问题。我敢肯定,这可能只是我需要的一条线不合适或缺少,我只是不知道是什么或在哪里。当它坐着时,它会不断地要求我输入一个 3 位数的数字,无论长度如何。对输入的字符串进行错误检查目前有效:
//Gives instructions to the user to enter 3-digit number
//Any amount of numbers will work, but instructions help
//System.out.println("Please enter a 3-digit number: ");
int j;
do
{
System.out.println("Please enter a 3-digit number: ");
while (!scan.hasNextInt()) {
System.out.println("That's not a 3-digit number! Try again!");
scan.next(); // this is important!
}
j = scan.nextInt();
}
//while (j <= 0); This works while not checking digit length
while (j != 3);
int w = (int) Math.log10(j) +1; //Found this, but not sure if it helps or not
String n = Integer.toString(w);
剩下的就是做我需要做的事情了:
//Determines char length based on user input
char[][] sel = new char[n.length()][];
for (int i = 0; i < n.length(); i++)
{
//Grabs the characters at their given position
int digit = Integer.parseInt("" +n.charAt(i));
sel[i] = letters[digit];
}
mnemonics(sel, 0, "");
}
public static void mnemonics(char[][] symbols, int n, String s)
{
if (n == symbols.length)
{
System.out.println(s);
return;
}
for (int i = 0; i < symbols[n].length; i ++)
{
mnemonics(symbols, n+1, s + symbols[n][i]);
}
}
}
这是输出:
----jGRASP exec: java listMnemonics
请输入 3 位数字:
2345
请输入 3 位数字:
12
请输入 3 位数字:
123
请输入 3 位数字:
motu
这不是一个三位数的数字!再试一次!
【问题讨论】:
-
前导零有可能吗?
nbr > 99 && nbr < 1000怎么了? -
是的,前导或结尾的零是可接受的输入。如果是这样的话,我应该把那条线放在哪里?那是我的麻烦。
-
如果是这种情况,您无法将其解析为
int。您必须将其作为字符串读入并自己解析。 -
所以你说的是:
int j;我应该改成String j = scan.nextLine();或类似的东西,然后从那里开始? -
无论如何我都不是 java 专家,大多数时候我只是很幸运,但这听起来我可能需要进行比预期更多的更改,因为在输入之后我目前正在解析
int到String,然后继续前进。我不希望String成为可接受的输入。
标签: java math input int java.util.scanner