Home > front end >  how to have multiple scanners for multiple user inputs
how to have multiple scanners for multiple user inputs

Time:10-09

I am writing a small program to create a password based off what the user inputs their first middle last name and the birthday and create a password off that and i don't know what i am doing but believe i need multiple scanners but when i do i get this error "variable scan is already defined in method main(string[]) Scanner scan = new Scanner(System.in);"

here is my code

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    System.out.print("Please Enter your first name: ");
    Scanner scan = new Scanner(System.in);
    String name = scan.nextLine();
    System.out.print("Please Enter your last name: ");
    Scanner scan = new Scanner(System.in);
    String name = scan.nextLine();
    scan.close();
  }
}

anythoughs on what could work?

CodePudding user response:

You do not need multiple Scanner objects to accept multiple inputs. You should create one Scanner object and use it to collect as many inputs as you want.

Here is an example:

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        System.out.println("Enter your first name: ");
        String fname = input.next();
        
        System.out.println("Enter your last name: ");
        String lname = input.next();
        
        System.out.println("Enter your age: ");
        int age = input.nextInt();
        
        System.out.println("Your details as entered:");
        
        System.out.println("First Name: "   fname);
        System.out.println("Last Name: "   lname);
        System.out.println("Age: "   age);
    }
}

Also some extra resources for you (for Scanner class): https://www.w3schools.com/java/java_user_input.asp

CodePudding user response:

That is because you cannot have two variables with the same name within the same scope.

You should rename one of them ..

Note that you did the same with the String variable name ;)

If you want to keep the same name for both use, then you should not re-declare the variable(s):

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scan;
    String name;

    System.out.print("Please Enter your first name: ");
    scan = new Scanner(System.in);
    name = scan.nextLine();
    scan.close();

    System.out.print("Please Enter your last name: ");
    scan = new Scanner(System.in);
    name = scan.nextLine();
    scan.close();
  }
}

Notes:

  • in this example, you will loosen the first value entered by the user. You might want to use an other variable name to store the last name.
  • there is obviously no reason to instantiate two different Scanner objects with the same InputStream.
  •  Tags:  
  • java
  • Related