如何从Java中的一个String中获取多个变量集

时间:2012-12-06 12:26:22

标签: java arrays string variables split

我试图用一个println设置多个String变量。这就是我所拥有的:

Scanner scanner = new Scanner(System.in);

String teacher = "";
String classSelect = "";
String location = "";

System.out.println("Enter a teacher: ");
teacher = scanner.next();

System.out.println("Enter a class name: ");
classSelect = scanner.next();

System.out.println("Enter a location: ");
location = scanner.next();

以下是我想要完成的事情:

String section = "";
String instructor = "";
String location = "";

System.out.printf("Only fill in applicable criteria, leave the rest blank :\n"
        + "Section://Sets section var// \n"
        + "Instructor://Sets instructor var// \n"
        + "Location://Sets location var// \n");

2 个答案:

答案 0 :(得分:1)

这可能不是一种道德方式,但可以试试

System.out.printf("Only fill in applicable criteria, leave the rest blank and use | after every field:\n"
        + "Section://Sets section var// \n"
        + "Instructor://Sets instructor var// \n"
        + "Location://Sets location var// \n");

如果用户进入

abc|xyz|loc

以字符串

接受它
String input = scanner.nextLine();
String[] inputs=input.split("|");
inputs[0]//<--section
inputs[1]//<--instructor
inputs[2]//<--location

答案 1 :(得分:0)

你在找这个:

   String message = 
        String.format("Only fill in applicable criteria, leave the rest blank :\n"
        + "Section: %s \n"
        + "Instructor: %s \n"
        + "Location:%s \n", 
        section ,instructor,location );

还是这个?

    System.out.printf("Only fill in applicable criteria, leave the rest blank :\n"
            + "Section: %s \n"
            + "Instructor: %s \n"
            + "Location:%s \n", 
            section ,instructor,location );