我正在尝试停止输入缓冲区的输入。我认为scan.hasNext()方法会在缓冲区为空时结束,但它会继续运行并给我两个额外的输出。预期输出位于顶部,我的输出位于底部。我没有输入的副本。
222-3334
555-6667
7-778-889-9991
1-800-555-1234
222-3334
555-6667
7-778-889-9991
1-800-555-1234
1-800-555-1234
582-4817
以下是代码:
import java.util.Scanner;
public class TelephoneMapping {
public static void main(String[] args){
String input; // IN,CALC - reads from input
// Inputs information
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
input = scan.next();
input = input.toUpperCase();
input = input.replace('A', '2');
input = input.replace('B', '2');
input = input.replace('C', '2');
input = input.replace('D', '3');
input = input.replace('E', '3');
input = input.replace('F', '3');
input = input.replace('G', '4');
input = input.replace('H', '4');
input = input.replace('I', '4');
input = input.replace('J', '5');
input = input.replace('K', '5');
input = input.replace('L', '5');
input = input.replace('M', '6');
input = input.replace('N', '6');
input = input.replace('O', '6');
input = input.replace('P', '7');
input = input.replace('Q', '7');
input = input.replace('R', '7');
input = input.replace('S', '7');
input = input.replace('T', '8');
input = input.replace('U', '8');
input = input.replace('V', '8');
input = input.replace('W', '9');
input = input.replace('X', '9');
input = input.replace('Y', '9');
input = input.replace('Z', '9');
// Stops loop when -1 entered.
if(input == "-1"){
System.out.println();
break;
}
// If less than 7 digits, returns to main body of while loop
else if(input.length() < 7){
continue;
}
// If less than 11 digits, returns a 7 digit number
else if(input.length() < 11)
{
input = input.substring(0,3) + "-" + input.substring(3,7);
}
// If greater than 10 digits, returns an 11 digit number
else{
input = input.substring(0,1) + "-" + input.substring(1,4) + "-" +
input.substring(4,7) + "-" + input.substring(7,11);
}
System.out.println(input);
}
}
}