gpt4 book ai didi

java - 从用户获取的输入总是少于 1

转载 作者:行者123 更新时间:2023-12-01 22:44:10 24 4
gpt4 key购买 nike

我正在尝试从用户那里获取 n 行输入(字符串)

  • 首先设置 n
  • 我初始化一个字符串数组来保存输入,并初始化 for 循环来保存它们。

问题是它总是达不到意义

  • 如果 n=1 则程序终止
  • 如果 n=2,则仅需要 1 个输入
  • 如果 n=3,则仅需要 2 个输入,依此类推......

出了什么问题?

Scanner sc = new Scanner(System.in);
//how many lines should be taken
int lines = sc.nextInt();
// initialize input array
String[] longWords = new String[lines] ;

//set the input from the user into the array
for (int i = 0; i < longWords.length; i++) {
longWords[i] = sc.nextLine() ;
}

最佳答案

这样做:

Scanner sc = new Scanner(System.in);
//how many lines should be taken
int lines = sc.nextInt();

//read the carret! This is, the line break entered by user when presses Enter
sc.nextLine();

// initialize input array
String[] longWords = new String[lines] ;

//set the input from the user into the array
for (int i = 0; i < longWords.length; i++) {
longWords[i] = sc.nextLine() ;
}

关于java - 从用户获取的输入总是少于 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25583983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com