简体   繁体   中英

Java - Reverse String null error

The input is meant to appear like this, example. \\n Kazan R \\n 6789 \\n Nzk462 \\n

However the output I receive looks like this kzn462nullnzk Why is this? and How can i solve it?

private void btnGenerateActionPerformed(java.awt.event.ActionEvent evt) {                                            

    secondname = JOptionPane.showInputDialog("Enter your surname:");
    firstname = JOptionPane.showInputDialog("Enter your firstname:");
    idno = JOptionPane.showInputDialog("Enter your idno:");
    nametag = firstname.substring(0, 1);
    initials = secondname + " " + nametag;

    int randnum;
    do {
        randnum = (int) (Math.random() * 900) + 100;
    } while (randnum % 2 != 0);

    code = secondname.replaceAll("[aeiou || AEIOU](?!\\b)", "")+randnum ;
    txaDisplay.append(initials + '\n' + idno.substring(6,10) + '\n' + code);

    int length = secondname.length();
    for (int i = length - 1; i >= 0; i--) {
        reverse = reverse + secondname.charAt(i);
    }
    String end = reverse + code;

   txaDisplay.append( reverse);

Why don't you use

new StringBuilder(secondname).reverse().toString()

to reverse your String ? It's better, simple and more maintanable.

  1. Get the character array from your source string
  2. Create a new char array of same length
  3. Start iterating from 0 to (sourceStringLength-1)
  4. In each iteration, get the last character from the end in your source array and populate in your new array
  5. Create a new string from this new array

      String source = "abcdefg"; char[] chars = source.toCharArray(); char[] reverseChars = new char[source.length()]; int len = source.length(); for(int i= 0; i < len; i++){ reverseChars[i] = chars[len-1-i]; } String reverse = new String(reverseChars); System.out.println(reverse); 

Since You don't want to use StringBuilder/StringBuffer.

Try this

String reversedString="";
for(int i=inputString.length-1;i>=0;){
   reversedString+=inputString.charAt(i--);  
}

I think the problem is your definition of reverse, maybe you have something like:

String reverse;

Then you don't initialize your "reverse" so when your program makes the first concatenation in your loop, it looks like this:

reverse = null + secondname.charAt(i);

The null value is converted to a string so it can be visible in the output.

I hope this information helps you.

Good Luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM