简体   繁体   English

如何在Java中用新行分割每个输入?

[英]How to split each input by a new line in Java?

I'm trying get 5 string inputs from the user and those inputs are going to be stored in an array. 我正在尝试从用户那里获得5个字符串输入,这些输入将存储在数组中。 When I enter something like "Hello World" and hit a new line I can only enter 3 more words. 当我输入“ Hello World”之类的内容并点击新行时,我只能再输入3个字。 So I want each user input to be a sentence and hitting enter should ask the user for another input on a new line. 因此,我希望每个用户输入都是一个句子,按回车键应要求用户在新行上输入另一个输入。

Here is my code so far: 到目前为止,这是我的代码:

Scanner user_input = new Scanner(System.in);   
String ask1 = user_input.next()+"\n";
String ask2 = user_input.next()+"\n";
String ask3 = user_input.next()+"\n";
String ask4 = user_input.next()+"\n";
String ask5 = user_input.next();
String[] cars = {ask1, ask2, ask3, ask4, ask5};    

According to the documentation , Scanner.next() : 根据文档 Scanner.next()

Finds and returns the next complete token from this scanner. 查找并返回此扫描仪的下一个完整令牌。 A complete token is preceded and followed by input that matches the delimiter pattern. 完整的标记在其前面,然后是与定界符模式匹配的输入。

As the default delimiter used by Scanner is whitespace, calling next() will get you individual words from user input. 由于Scanner使用的默认定界符是空格,因此调用next()将使您从用户输入中获得单个单词。 When you want to capture multiple words that end with a newline, you should use Scanner.nextLine() instead. 如果要捕获以换行符结尾的多个单词,则应改用Scanner.nextLine()

Additionally, you can remove code duplication (which you always should do, keeping things DRY ) by creating the array beforehand and allocating the user input entries within a loop: 另外,您可以通过预先创建数组并在循环内分配用户输入条目来删除代码重复(您通常应该这样做,使事情保持DRY ):

final int numberOfCars = 5;
Scanner userInput = new Scanner(System.in);   
String[] cars = new String[numberOfCars];

for (int i = 0; i < numberOfCars; i++) {
    cars[i] = userInput.nextLine();
}

I recommend that you have a certain keyword or phrase that the user can type which stops the program. 我建议您有一个用户可以键入的特定关键字或短语来停止程序。 Here, I made a simple program that uses the java.util.Scanner object to receive keyboard input. 在这里,我编写了一个简单的程序,该程序使用java.util.Scanner对象接收键盘输入。 Each value is stored in a java.util.ArrayList called "inputs." 每个值都存储在一个名为“ inputs”的java.util.ArrayList中。 When the user is done entering input, he/she will type "stop" and the program will stop. 当用户完成输入后,他/她将键入“停止”,程序将停止。

import java.util.*; //you need this for ArrayList and Scanner

public class Input{

    public static void main(String[] args){

        Scanner user_input = new Scanner(System.in); //create a scanner object
        ArrayList<String> inputs = new ArrayList<String>(); //I used a java.util.ArrayList simply because it is more flexible than an array
        String temp = ""; //create a temporary string which will represent  the current input string

                while(!((temp = user_input.next()).equals("stop"))){ //set temp equal to the  new input each iteration
                inputs.add(temp); //add the temp string to the arraylist
                }
    }
}

If you want to convert the ArrayList to a normal String[], use this code: 如果要将ArrayList转换为普通的String [],请使用以下代码:

String[] inputArray = new String[inputs.size];
for(int i = 0; i < inputs.size(); i++){
    inputArray[i] = inputs.get(i);
} 

You can make this more generic by storing your question on an array and looping through a for loop prompting for input until you have question. 您可以通过将问题存储在数组上并遍历for循环提示输入,直到遇到问题为止,从而使此问题更为通用。 This why when you have more questions you can add them to list without changing anything else on the code. 这就是为什么当您有更多问题时可以将其添加到列表中,而无需更改代码中的任何其他内容。

Then, to answer your original question regarding creating a String array, you could use following method String[] a = answers.toArray(new String[answers.size()]); 然后,要回答有关创建String数组的原始问题,可以使用以下方法String[] a = answers.toArray(new String[answers.size()]);

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

public class HelloWorld
{
  public static void main(String[] args)
  {
    ArrayList<String> questions = new ArrayList<String>(5){{
        add("What is your name?");
        add("What is school you went to?");
        add("Do you like dogs?");
        add("What is pats name?");
        add("Are you batman?");
    }};

    ArrayList<String> answers = new ArrayList<String>(questions.size()); // initialize answers with the same size as question array
    String input = ""; // Stores user input here
    Scanner scanner = new Scanner(System.in);
    for(String question : questions){
      System.out.println(question); // Here we adding a new line and the user type his answer on a new line
      input = scanner.nextLine();
      answers.add(input); // Store the answer on answers array
    }
    System.out.println("Thank you.");
    String[] a = answers.toArray(new String[answers.size()]); // THis converts ArrayList to String[]
    System.out.println("You entered: " + a.toString());
  }
}

You want this instead: 您想要这个:

Scanner user_input = new Scanner(System.in);   
String ask1 = user_input.nextLine()+"\n";
String ask2 = user_input.nextLine()+"\n";
String ask3 = user_input.nextLine()+"\n";
String ask4 = user_input.nextLine()+"\n";
String ask5 = user_input.nextLine();
String[] cars = {ask1, ask2, ask3, ask4, ask5};  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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