这个程序是由 3 个数字和 7 个字母组成的字符串,使用方法将其转换为等效的数字。用户输入是一个字符串,它从字母变为数字,然后再变成由破折号分隔的数字字符串。所以这只是学习的第 3 周,我被方法绊倒了。我收到的错误代码告诉我字符串索引超出范围。所以,我怀疑错误出在我的转换中,或者我在第 89 行附近连接了最后的字符串。我花了 20 分钟与 TA 交流,希望得到任何指导。我仍然与该程序有更多的关系,所以我省略了一些,因为我只需要在我遇到卡住超过 45 分钟的地方时获得帮助。主要问题 - 错误发生在哪里,为什么?我试图将打印语句放在任何地方,看看发生了什么......
import java.util.Scanner;
public class ConvPhoneNumTwo{
public static void main(String[] args){
String s = getInput();
printPhone(convertToDigit(s));
}
public static String getInput() {
Scanner scan = new Scanner(System.in);
String s1 = "";
boolean length = false;
while (length==false){
System.out.println(" Please enter a telephone number in this format ###-AAA-AAAA") ;
s1 = scan.nextLine();
if(s1.length() != 12 ){
System.out.println( "this is an invalid choice try again Plz...");
length = false;
}
else{
length = true;
}
}
return s1;
}
public static String convertToDigit(String s010){
s010 = s010.toLowerCase();
String s001= s010.substring(0,3);
String s002 = s010.substring(4,6);
String s003 = s010.substring(8,12);
String s1 = (s001+s002+s003);
String s2 = "";
// Exceptions to our problem to stop invalid inputs
if (s1 == null) {
System.out.print (" invalid input null thing");
}
if (s1.length() != 10){
System.out.print (" invalid input");
}
String s6 = "";
for (int i=0; i < s1.length(); i++) {
if (Character.isDigit(s1.charAt(i))){
s2 += s1.charAt(i);
}
//sorting of the letter inputs
char ch = s1.charAt(i);
if (ch == 'a'||ch=='b'||ch== 'c'){
s2 += "2";
}
if (ch == 'd'||ch=='e'||ch=='f'){
s2 += "3";
}
if (ch == 'g'||ch=='h'||ch=='i'){
s2 += "4";
}
if (ch == 'j'||ch=='k'||ch=='l'){
s2 += "5";
}
if (ch == 'm'||ch=='n'||ch=='o'){
s2 += "6";
}
if (ch == 'p'||ch=='q'||ch=='r'|| ch=='s'){
s2 += "7";
}
if (ch == 't'||ch=='u'||ch=='v'){
s2 += "8";
}
if (ch == 'w'||ch=='x'||ch=='y'|| ch=='z')
{
s2 += "9";
}
else{
}
String s3 = s2.substring(0,3);
String s4 = s2.substring(3,6);
String s5 = s2.substring(6);
s6 = ( s3 +"-"+ s4 + "-"+ s5);
}
return s6;
}
public static void printPhone(String message) { //print out whatever string it is given, basically System.out.println(), but through a method instead
System.out.println(message);
}
}
不确定我可以在其中添加多少细节。