0
import java.util.Scanner;
class testa{
  public static void main(String args[]){
     char m[ ] = new char[10];
     int i,j;
     Scanner sc = new Scanner(System.in); 
       for(i=0;i<5;i++){
       m[i]=sc.next();//I can do it via bufferedReader but how to o it with Scanner
       }
            for(j=0;j<5;j++)
    System.out.println(m[j]);
 }
}

Now the problem is that i cannot input value and execute it correctly using Scanner class but i can with bufferedreader which i dont want to do.How do i make this program work? Sample input:qwerty Sample output: q w e r t y

5 Answers5

0

In this line : m[i]=sc.next() it accepts the entire string "qwerty" . You might want to try something like this: String str= sc.next(); for(int i=0;i<5;i++) m[i] =str.charAt(i);

Riddle03
  • 3
  • 3
0
import java.util.Scanner;      // import Scanner class to input array values from user
public class ArrayExample {

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);   //Create an object of Scanner class
    int[] arr=new int[10];      //declare an integer array


    //input value from array
    for(int i=0;i<10;i++){
        arr[i]=sc.nextInt();        
    }


    //print array values from array
    for(int i=0;i<10;i++){
        System.out.println(arr[i]);
    }

}

}

0
import java.util.Scanner;
class testa{
  public static void main(String args[]){
     char[] m = new char[5];
     Scanner sc = new Scanner(System.in); 
       for(int i=0;i<5;i++){
       m[i]=sc.next().charAt(0);
       }
            for(int j=0;j<5;j++)
    System.out.print(m[j] + ' ');
 }
}

I believe this should work. I'm on my phone as of writing, so cannot verify. The important correction being

.charAt(0) and System.out.print(m[j] + ' ');

0

You could try doing :-

char c[] = new char[5];
Scanner sc = new Scanner(System.in);
String line = sc.next();
for(int i=0;i<5;i++){
   c[i] = line.charAt(i);
}

This would make a char array out of the entered String.Well, if you want a char array, you could also replace the loop with

char c[] = line.toCharArray();

At the end, just print out the array.

dumbPotato21
  • 5,353
  • 5
  • 19
  • 31
0

Though it's not very efficient, this is the only way I can think of using Scanner.

public class testa{
    public static void main(String args[]) {
        Pattern pattern = Pattern.compile(".");
        Scanner sc = new Scanner(System.in);
        String str = null;
        do  {
            str = sc.findInLine(pattern);
            if(str!= null)
                System.out.print(str.charAt(0));
                System.out.print(" ");
        } while (str != null);
        sc.close();
    }
}
Gomsy
  • 86
  • 6