How to take a scanner object and make it a String

user2558595 picture user2558595 · Jul 7, 2013 · Viewed 48.3k times · Source

I need help doing the following:

  1. receiving input using Scanner class (I got this)
  2. taking input from scanner and making it a String
  3. use replaceAll to remove numbers 0-9 from user input.

The below code is what I have so far but it is only returning user input and not removing numbers:

public static void main(String[] args) {

    Scanner firstname = new Scanner(System.in);
    System.out.println("Please enter your first name:");
    String firstname1 = firstname.next();
    firstname1.replaceAll("[^0-9]","");
    System.out.println(firstname1);

Updated Code. Thank you Hovercraft. I am now investigating how to retrieve all alpha characters as with the code below, I am only getting back the letters prior to the numeric values entered by the user:

import java.util.Scanner;    

public class Assignment2_A {

    public static void main(String[] args) {

        Scanner firstname = new Scanner(System.in);
        System.out.println("Please enter your first name:");
        String firstname1 = firstname.next();
        firstname1 = firstname1.replaceAll("[^A-Z]","");
        System.out.println(firstname1);

Answer

Neo picture Neo · Jul 7, 2013
String input = yourScannerObject.nextLine ();

where "yourScannerObject" is the name you give your scanner.