1

I need to store input1 input2 input3 in char array of given same size.

public static void evalCharArray(int size){

      System.out.println("please enter any three string not exceed than size"+size); 
         Scanner sc=new Scanner(System.in);
         String input1=sc.nextLine();
         String input2=sc.nextLine();
         String input3=sc.nextLine();
        //what i need is-I want to store these input string in three separate charArray of same length(ie of int size)
  }

If i am using input1.toCharArray() input2.toCharArray() input3.toCharArray() these are giving me array of different size based on input.

7
  • 1
    input1, input2, and input3 in a single char array? or 3 separate char array with the same size? Commented Jun 9, 2015 at 6:56
  • these are separate arrays. Commented Jun 9, 2015 at 6:58
  • please enter any three string not exceed than size what does that mean? Commented Jun 9, 2015 at 7:00
  • What if the user enters a string more than size characters? Commented Jun 9, 2015 at 7:01
  • @NamanGala this size is the size of char array since we have to put it into char array of length size. Commented Jun 9, 2015 at 7:02

2 Answers 2

3

You can use System.arraycopy() method.

You can use this sample code.

public static void main(String[] args) {
    String s = "work";
    char[] arr = new char[10];
    System.arraycopy(s.toCharArray(), 0, arr, 0, s.toCharArray().length );
    System.out.println(arr.length); // prints 10
    System.out.println(arr); // prints work
}
Sign up to request clarification or add additional context in comments.

Comments

3

Use Arrays.copyOf(T[], int).

 char[] input1=Arrays.copyOf(sc.nextLine().toCharArray(), size);

Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.