-4

I have a question based on character arrays. At the moment I have an input variable that takes the first letter of the word.

char input = scanner.nextLine().charAt(0);

What I want to do is for every enter, I want to put it in an array so that I can keep a log of all the letters that have been retrievied. I am assuming this is using char[] but I am having trouble implementing added each input into the array.

GBlodgett
  • 12,612
  • 4
  • 26
  • 42
Merlin
  • 175
  • 2
  • 12
  • 3
    `scanner.next()` Take a look at [this](https://stackoverflow.com/questions/13942701/take-a-char-input-from-the-scanner) question that was asked before. – Jimenemex May 08 '18 at 14:17
  • If you have trouble with code, put down that code here. If you have trouble writing that code: any good book or tutorial tells you how to create arrays, and gives examples how to use them. – GhostCat May 08 '18 at 14:18
  • 4
    Possible duplicate of [Take a char input from the Scanner](https://stackoverflow.com/questions/13942701/take-a-char-input-from-the-scanner) – Jimenemex May 08 '18 at 14:20

1 Answers1

3
char input = scanner.nextLine().charAt(0);

First thing that's unclear is what Object type is scanner? But for now I'll assume scanner is the Scanner object from Java.util.Scanner

If that's the case scanner.nextLine() actually returns a String. String has a charAt() method that will allow you to pick out a character anywhere in the string.

However scanner.nextLine() is getting the entire line, not just one word. So really scanner.nextLine().charAt(0) is getting the first character in the line.

scanner.next() will give you the next word in the line. If the line contained "Hello World" scanner.next().charAt(0) would return the character 'H'. the next call of scanner.next().charAt(0) would then return the character 'W'

public static void main(String[] args) {
    boolean finished = false;
    ArrayList<Character> firstLetters = new ArrayList<>();
    Scanner scanner = new Scanner(System.in);
    while (!finished) {
        firstLetters.add(scanner.next().charAt(0));
    }
}

The above code sample might give you the behavior you're looking for. Please note that the while loop will run forever until finished becomes true. Your program will have to decide when to set finished to true.

AND here's a couple of links about Java's Scanner class

Adam Ramos
  • 124
  • 7