kemkoi kemkoi - 1 month ago 22
Java Question

Concat String in a for loop

I'm trying to create a program that takes each number typed in by the user and sort them out as even, odd and the number zero values.

The result should look like something like this:

User Input: 14005

Output:
Even Numbers: 4
Odd Numbers: 1, 5
Zero's: 0, 0


This is the code I've written, I thought of using string concatination in order to add a new value each time the loop checks for the next character, don't know whether I'm thinking right or not though, would appriciate if someone could tell me where I'm thinking in the wrong way.

package com.craydesign;

import javax.swing.JOptionPane;

public class Main {

public static void main(String[] args) {
String number = JOptionPane.showInputDialog("Please enter a number: ");
String evenNumbers = "";
String oddNumbers = "";
String numberZero = "";

for(int i = 0; i < number.length(); i++) {
if(number.charAt(i) % 2 == 0) {
evenNumbers.concat(Integer.toString(i) + ", ");
} else if(number.charAt(i) % 2 != 0) {
oddNumbers.concat(Integer.toString(i) + ", ");
} else if (number.charAt(i) == 0){
numberZero.concat(Integer.toString(i) + ", ");
}
}

JOptionPane.showMessageDialog(null, "Even numbers: " + evenNumbers + "\n" + "Odd numbers: " + oddNumbers + "\n" + "Zero's: " + numberZero);

}

}

Answer

use Character.getNumericValue() instead of charAt(i)

public static void main(String[] args) throws IOException
    {

          String number = JOptionPane.showInputDialog("Please enter a number: ");
          StringBuffer evenNumbers = new StringBuffer();
          StringBuffer oddNumbers =new StringBuffer();
          StringBuffer numberZero =new StringBuffer();

        for(int i = 0; i < number.length(); i++) {
          int value=Character.getNumericValue(number.charAt(i));
          if(value!=0 && value % 2 == 0) {
              evenNumbers.append(value).append(',');
          } else if(value % 2 != 0) {
              oddNumbers.append(value).append(',');
          } else if (value == 0){
              numberZero.append(value).append(',');
          }
        }

          JOptionPane.showMessageDialog(null, "Even numbers: " + evenNumbers + "\n" + "Odd numbers: " + oddNumbers + "\n" + "Zero's: " + numberZero);


      }

EDIT:(displaying numbers in sorted order)

     String evenNo[]=evenNumbers.toString().split(",");
      String oddNo[]=oddNumbers.toString().split(",");

      Arrays.sort(evenNo);
      Arrays.sort(oddNo);

      JOptionPane.showMessageDialog(null, "Even numbers: " +  Arrays.toString(evenNo) + "\n" + "Odd numbers: " + Arrays.toString(oddNo) + "\n" + "Zero's: " + Arrays.toString(numberZero.toString().substring(0, 

numberZero.length()-1).split(",")));