简体   繁体   中英

enter multiple String data in java at the same time

I have the following code:

String username="administrator", iusername="", password="password", ipassword="";
System.out.println("Please login to the system");
System.out.print("\nusername:\t");

iusername = scan.nextLine();
System.out.print("\npassword:\t");
ipassword = scan.nextLine();

i want user enter data for two variable (iusername and ipassword) but i only can enter data for ipassword, because it skip

iusername = scan.nextLine();

below is the sample of output from IDE

username:   username:   

password:   BUILD STOPPED (total time: 12 seconds)

it skip my username and go to password

This can be used to put new output on new lines automatically.

System.out.println("");

Without more code, or a clearer question this is hard to answer.

username = scan.nextLine();
System.out.print("\npassword:\t");
password = scan2.nextLine();

Should be, as you can reuse the Scanner class Instance.

username = scan.nextLine();
System.out.print("\npassword:\t");
password = scan.nextLine();

But maybe you want to do

username = scan.nextLine(); // Get user input
System.out.println("Username:\t" + username); // Show typed username
password = scan2.nextLine(); // Get user input again
System.out.println("Password:\t" + password); // Show typed password

I'm sorry, I don't catch your point... I tried this and I'm able to insert both values (iusername and ipassword):

import java.util.Scanner;

public class MultipleStringInput {

   public static void main(String[] args) {
      String username = "administrator", iusername = "", password = "password", ipassword = "";
      System.out.println("Please login to the system");
      System.out.print("\nusername:\t");

      Scanner scan = new Scanner(System.in);

      iusername = scan.nextLine();
      System.out.print("\npassword:\t");
      ipassword = scan.nextLine();
      System.out.println(iusername + " " + ipassword);
   }

}

I think this code works as expected ("i want user enter data for two variable"). It looks like your IDE is redirecting System.out to your scanner... strange... I suggest you test it from command line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM