JavaGuy1 JavaGuy1 - 1 month ago 18
Java Question

ArrayList Get Method

I have an ArrayList and I am trying to get the first element. I am using

nameofarray.get(0);
when printed it prints the entire array, not the first element. I need to get the first element but I am confused as to why it is getting the entire array, not just the first element. Any help is appreciated, thanks!

import java.util.ArrayList;
import java.util.Scanner;

public class Driver {

public static void main(String[] args) {
Scanner k = new Scanner(System.in);
String msb;
String convertedBinary;
ArrayList<String> binaryInput = new ArrayList<String>();
System.out.println("Press 1 to use the Binary Converter: Press 2 to use the Decimal Converter:");
int userChoice = k.nextInt();

if (userChoice == 1) {
System.out.println("Welcome to the Binary Converter!");
System.out.println("Please enter a 10 bit binary number");
// Adding the input to the ArrayList
binaryInput.add(k.next());
msb = binaryInput.get(0);
System.out.println(msb);

}
}


}

Answer

I don't think Scanner.next() necessarily returns one character at a time so when you add it to the list it is adding a chunk of input. So you may have to manually split the text returned before inserting into the list.

"The java.util.Scanner.next() method finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern." from here

Comments