Character Input, IsDigit

Character Input, IsDigit

The following program ask for character input. 1 for all kind of character, the other only accepts digits. You’re required to use your basic java knowledge to try to resolved.

Knowledge required

  • Character build in functions
  • Array, ArrayList
  • Array to String

Given the sample code

class TextInput { }	
class NumberInput { }

public class UserInput {
   public static void main(String[] args ) {}    
}

Requirement

  • implement method void add(char c) and String getValue()
  • NumberInput class inherit TextInput and override the methods
  • Expected output:

 TextInput input = new NumericInput();
 input.add(‘9’);
input.add(‘z’);
 input.add(‘9’);
 System.out.println(input.getValue());

Output = 99

Sample Code

class TextInput {
    private ArrayList<Character> list = new ArrayList<>();
		
    public void add(char c) {
      list.add(c);
    }
		
    public String getValue() {
      Character[] arr = list.toArray(new Character[list.size()]);
      StringBuilder sb = new StringBuilder();
      for (Character c: arr) {
        sb.append(c);
      }
      return sb.toString();
    }
}
	
class NumberInput extends TextInput {
    private ArrayList<Character> list = new ArrayList<>();
    
    @Override
    public void add(char c) {
      if ( Character.isDigit(c)) {
        list.add(c);
      }
    }
		
    @Override
    public String getValue() {
      Character[] arr = list.toArray(new Character[list.size()]);
			
      StringBuilder sb = new StringBuilder();
      for (Character c: arr) {
        sb.append(c);
      }
      return sb.toString();
    }	
}

public class UserInput {
  public static void main(String[] args) {
    TextInput input = new NumberInput();
    input.add('9');
    input.add('a');
    input.add('9');
    System.out.println(input.getValue());
  }
}

Write a Reply or Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.