プログラミング演習4.21(SSNの確認)ユーザーに社会保障番号の入力を求めるプログラムを作成します。形式はDDD-DD-DDDDです。Dは番号です。プログラムは、入力が合法であるかどうかを判断する必要があります。



Programming Exercise 4



学校でJavaを初めて使用する学生は、IntroductionToJavaProgramming(Java Language Programming Basicsの元の本の第10版)を読んだときに、この本で問題を解決しました。現在のレベルは限られているので、やりました。これがJavaプラクティスノートです。コードは少し長めだと思いますが、何か欠点があれば、コメントでいくつかのポインタを共有していただければ幸いです。

//Set up a logo first to facilitate the processing of the output boolean flag=false while(true){ Scanner input=new Scanner(System.in) //The first input prompt and out // Enter the prompt again after the error if(!flag) { System.out.println('Please enter a ssn:') }else{ System.out.println('Please enter exactly again: ') } String ssn=input.nextLine() //First determine whether the length of the entered number string is correct if(ssn.length()!=11){ System.out.println('Invalid input length! ') //The length does not match, modify the value of flag flag=true //Stop here and go back to the next while loop continue } //Set up a sign again to determine whether the format of the entered number is completely correct int t=0 //Further judge whether the character format of each position is correct for(int i=0i<ssn.length()i++){ if(i==3||i==6){ if(ssn.charAt(i)!='-') { //The format is wrong, modify the value of the flag flag = true //Exit the for loop break } }else if(!Character.isDigit(ssn.charAt(i))){ //The format is wrong, modify the value of the flag flag=true //Exit the for loop break } //Every time a character is judged to be in the correct format, +1 t++ } //Outside the for loop, judge whether the mark t is equal to the length of the input number if(t==ssn.length()){ System.out.print('Enter format correctly.') //Exit the program normally System.exit(0) } //Judging the output by the flag value if(flag){ System.out.println('Wrong input format!') //Stop here and go back to the next while loop continue } }

実行結果の例:
画像