Home > Back-end > In Java if else judgment under the condition of the else execution is not the problem
In Java if else judgment under the condition of the else execution is not the problem
Time:11-22
Package LeiHeDuiXiang;
import java.util.Scanner;
Public class CusttomeBiz { String [] names=new String [30].
//add name Public void addname (String name) { for(int i=0; iIf (names [I]==null) { Names [I]=name; break; } } } //output name Public void showname () { System. The out. Println (" customer name list "); for(int i=0; iIf (names [I]!=null) { System. The out. Print (names [I] + "\ t"); } } } //modify the customer name //oldname old customer name //newname new customer name Public Boolean editname (String oldname, String newname) { Boolean find=false; for(int i=0; iIf (names [I] equals (oldname)) { Names [I]=newname; The find=true; break; } } Return the find;
} Public static void main (String [] args) { Scanner input=new Scanner(System.in); CusttomeBiz ab=new CusttomeBiz (); for(int i=0; i<5; I++) { System. The out. Print (" please input the customer's name: "); String newname=input. Next (); Ab. Addname (newname); } Ab. Showname ();
System. The out. Println (" please input to modify the user name: "); String oldname=input. Next (); System. The out. Println (" please enter a new user name: "); String newname=input. Next (); System. The out. Println (" * * * * * * * * modify result * * * * * * * * "); If (ab. Editname (oldname, newname)) { System. The out. Println (" username change success "); } The else { System. The out. Println (" the user was not found "); } Ab. Showname (); } }
When change the name of the existing can run Modify the name does not exist when not
Welcome bosses give directions
CodePudding user response:
You this is an unusual, so will not enter the else, the exception is thrown directly, Reason is mainly because your names [I] is null, because you only have 1, 2, 3, 4, 5, after (that is, names [5]) after the array element is null, and you input the oldname is 11, the for loop lookup, former names don't match [5] before, continue to find back again, just names [5] is null, namely becomes null. Equals (oldname), so a null pointer exception,
CodePudding user response:
Else covers too much, you don't have a name change, the pointer will find you to change the name, will be submitted to the null pointer exception, and not to say that you literally a wrong will return to you "do not check the user name" If you enter modify user name is! # # $$... * & amp; The noise, he will still be submitted to the null pointer exception, but he should be quoted "illegal input name" error
Conclusion: you have too many else conditions include, should add more conditions