문제

I want to read char variable a in a loop, and increment variable k by one in each step of loop.

here is code in java:

public class Hello {
  public static void main(String arg[]) throws IOException {
    int k, i;
    char a;
    k=0;
    for (i=0; i<=3; i++) {
      k++;
      a=(char) System.in.read();
      System.out.println(k);
    }
  }
}

here is result:

A  //variable a
1
2
3
B  //variable a
4

i need this result:

a  //variable a
1
c  //variable a
2
b  //variable a
3
y  //variable a
4

maybe i need some other method to read CHAR in loop ( not SYSTEM.IN.READ() ), but i am new in java.

도움이 되었습니까?

해결책 4

You can use the Scanner class, which consumes input more predictably:

public static void main(String arg[]) throws IOException {
    int k, i;
    char a;
    k = 0;
    Scanner in = new Scanner(System.in);

    for (i = 0; i <= 3; i++) {
        k++;
        a = in.next().charAt(0);
        System.out.println(k);
    }
}

The next() method returns a string, consisting of all the characters typed by the user, until they press the key. So, by typing one character at a time (or by typing the desired character first), the string returned by next() will start with that character, so calling charAt(0) will retrieve it.

Note that there is no reason to run the loop for the first 4 times (0, 1, 2 and 3). You could replace the for statement with a while (true) statement.

다른 팁

You can still use the System.in.read method - but without pressing enter after you introduce the first character: I think the above answers solve your problem. However, I would like to explain you why this happens: you probably write A and press enter. The program reads A and enter - which is 2 chars: \r\n - therefore, the for loop sees at the first iteration A, at the second \r and at the third \n....

Try this:

static Scanner keyboard = new Scanner(System.in);

public static void main (String args[]) {
  int k = 0;
  String a;
  while(true){
      a = keyboard.nextLine();
      k++;
      System.out.println(k);
   }
 }
  public static void main(String args[]) {
        int charCount = 0;
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext() && charCount++<=3)
        {
            System.out.println(sc.next());
        }

      }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top