【问题标题】:Increment array index for input为输入增加数组索引
【发布时间】:2013-12-11 14:59:24
【问题描述】:

我正在寻找用户输入要输入到数组中的名称,然后程序将提供输入另一个名称的选项,因此我希望将第二个名称输入到数组中的下一个索引中。目前我只能获取名称来填充数组的所有索引,或者只是它不断覆盖的第一个。

下面的代码将其写入所有索引:

while (nameArrayCount < 10) {
  studentNamesArray[nameArrayCount] = studentName;
  nameArrayCount++;
}

我理解为什么它会这样做,因为 nameArraycount 每次都在递增并且它符合语句的条件,但我不知道如何让它退出 while 循环并递增值。如果我尝试以下代码,程序会在输入名称后挂起 - 我假设这是因为它永远递增 nameArrayCount?

while (nameArrayCount < 10) {
  studentNamesArray[nameArrayCount] = studentName;
}
nameArrayCount++;

如果条件为真,我怎样才能让程序只输入一个新索引,然后递增nameArraycount 并退出while 循环? (如果用户然后选择输入另一个我要检查的名称的选项已输入少于 10 个)

我尝试过使用if 语句,但我只能让它填充数组中的第一个索引,如果用户输入第二个名称,它会一直覆盖它。

【问题讨论】:

  • 您只提供了一部分代码。这段代码之前的实际输入读数是多少?如果是这样,它从根本上被破坏了,因为在循环期间不会读取新数据,使其一遍又一遍地使用相同的字符串。
  • 输入读数确实在显示的代码之前。那么将输入的值传递给单独的函数以将它们插入数组会更好吗?

标签: java if-statement while-loop increment


【解决方案1】:

最后,这是我在其他人做类似事情时使用的解决方案,但我会说,如果你有选择,你应该绝对遵循@Chris 给出的答案。

String[] studentNamesArray = new String[10];

int nameArrayCount = 0;

字符串学生姓名;

    if (nameArrayCount < 10) {
      System.out.println("Enter the student's name in the following format - surname, forename: ");
      studentName = input.next();
      studentNamesArray[nameArrayCount] = studentName;
      nameArrayCount = nameArrayCount + 1;
    }

【讨论】:

    【解决方案2】:

    所以如果我理解正确的话,你想要做的是关于以下内容:

    if (containsName(studentNamesArray, studentName) == false) {
      addStudent(studentNamesArray, studentName);
    }
    

    此外,这可以使用 Java Set 轻松解决,如下所示:

    studentSet.add(studentName); // automatically ignores duplicates
    

    您需要为第一个代码部分做的就是编写函数containsNameaddStudent

    boolean containsName(String[] studentNamesArray, String studentName) {
      for (int i = 0; i < studentNamesArray.length; ++i) { // specialized while loop over all array elements
        if (studentName.equals(studentNamesArray[i])) { // use equals for String comparison! This will as well not match on "null"
          return true; // we found a match
        }
      }
      return false; // no match was found
    }
    

    void addStudent(String[] studentNamesArray, String studentName) {
      int i = 0; 
      while ((studentNamesArray[i] != null) && // this student entry is already filled by someone else
             (i < studentNamesArray.length)) { // we are still within the array bounds
        ++i;
      }
      if (i < studentNamesArray.length) { // is i still within the array bounds?
        studentNamesArray[i] = studentName; // add the student
      } else {
        // we have too many students. What to do now?
      }
    }
    

    这段代码有几处没有检查:

    • 如果学生人数超过数组大小怎么办?
    • 如果 studentName 是 null 怎么办?

    这种编写代码的方法称为Top-down approach,如果您了解一般程序逻辑但还不了解详细信息,则可以更轻松地编写代码。

    编辑:完整代码:

    import java.util.Scanner;
    
    public class Test {
    
      static boolean containsName(String[] studentNamesArray, String studentName) {
        for (int i = 0; i < studentNamesArray.length; ++i) { // specialized while loop over all array elements
          if (studentName.equals(studentNamesArray[i])) { // use equals for String comparison! This will as well not match on "null"
            return true; // we found a match
          }
        }
        return false; // no match was found
      }
    
      static void addStudent(String[] studentNamesArray, String studentName) {
        int i = 0;
        while ((studentNamesArray[i] != null) && // this student entry is already filled by someone else
                (i < studentNamesArray.length)) { // we are still within the array bounds
          ++i;
        }
        if (i < studentNamesArray.length) { // is i still within the array bounds?
          studentNamesArray[i] = studentName; // add the student
        } else {
          // we have too many students. What to do now?
        }
      }
    
      public static void main(String[] args) {
        final String[] studentNamesArray = new String[10];
        String studentName;
    
        final Scanner scanner = new Scanner(System.in);
    
        do {
          System.out.println("Please insert your name:");
          studentName = scanner.nextLine();
          if (studentName.length() > 0) {
            if (containsName(studentNamesArray, studentName) == false) {
              addStudent(studentNamesArray, studentName);
              System.out.println(studentName + " added.");
            } else {
              System.out.println(studentName + " was already in the list.");
            }
          }
        } while (studentName.length() > 0);
    
        for (int i = 0; i < studentNamesArray.length; ++i) {
          System.out.println("Student #" + i + ": " + studentNamesArray[i]);
        }
      }
    }
    

    使用示例输入,我得到以下信息:

    请填写您的姓名:
    二
    加了两个。
    请填写您的姓名:
    测试
    添加了测试。
    请填写您的姓名:
    测试
    测试已经在列表中。
    请填写您的姓名:
    测试
    添加了测试。
    请填写您的姓名:
    测试
    test 已经在列表中。
    请填写您的姓名:
    
    学生 #0:两个
    学生 #1:测试
    学生#2:测试
    学生 #3:空
    学生 #4:空
    学生 #5:空
    学生 #6:空
    学生 #7:空
    学生 #8:空
    学生 #9:空
    

    【讨论】:

    • 我已经尝试实现您的解决方案,但它似乎仍然覆盖了数组中的第一个索引。
    • 看来containsName 总是返回false
    • 请将我的完整代码与您的进行比较。函数工作正常,所以你的实现中一定有错误。
    【解决方案3】:

    我没有仔细阅读您的帖子,但我觉得最好使用List&lt;String&gt; 并在输入学生姓名时添加他们。之后,您只需查询列表的大小即可获得输入的名称数量。

    类似这样的伪代码:

    List<String> names = new ArrayList<>();
    
    while( names.size() < 10 ) {
      String name = //ask the user for another name
      if( meetsCondition(name) ) {
        names.add( name );
      } 
    
      //maybe also add an option to enter less names, e.g. ask the user
      if( userWantsToFinish() ) {
        break;
      }
    }
    
    int numNamesEntered = names.size();
    

    如果您真的必须使用数组,请将列表替换为数组并单独跟踪名称的数量:

    String[] names = new String[10]; 
    int numNamesEntered = 0 ;    
    
    while( numNamesEntered < names.length ) {
      String name = //ask the user for another name
      if( meetsCondition(name) ) {
        names[numNamesEntered] = name;
        numNamesEntered++; //for clarity, could also be done in the line above
      } 
    
      //maybe also add an option to enter less names, e.g. ask the user
      if( userWantsToFinish() ) {
        break;
      }
    }    
    

    【讨论】:

      【解决方案4】:

      您真的应该避免这样做,而是采用 OOP 方法。

      public class Student
      {
          private String firstName;
          private String secondName;
      
          public Student(String firstName, String secondName)
          {
              this.firstName = firstName;
              this.secondName = secondName; 
          }
      }
      

      然后您可以简单地创建一个Student 类型的数组,然后根据需要填充它。

      示例

      Student[] students = new Student[10];
      int position = 0;
      
      String firstName = scanner.readLine();
      String secondName = scanner.readLine();
      
      students[position++] = new Student(firstName, secondName);
      

      更简单的方法是使用List 实现。

      示例

      List<Student> students = new ArrayList<Student>();
      String firstName = scanner.readLine();
      String secondName = scanner.readLine();
      students.add(new Student(firstName, secondName));
      

      如果必须使用数组

      您需要某种形式的占位符来保持您在数组中的位置。

      int position = 0;
      

      您还需要一个输入机制,我们假设它是scanner

      studentNamesArray[position++] = scanner.readLine();
      

      这将返回position 的值(此时为0),然后将其递增,使其变为1

      这将防止它覆盖数组中的名称,因为索引总是在赋值后直接增加。

      【讨论】:

      • 不幸的是,我仅限于非 OO 方法,但是我会将您的答案投票给其他可能觉得这很有用的人,因为我同意这是首选方法。
      【解决方案5】:

      当然,我会做你的功课!

      在这个文本框中编码——我会为你修复它。

      public class HomeWorkAssignment {
      
          public static void main( String... args ) throws Exception {
      
              String arrayOfNames = new ArrayOfNames[10];
              Scanner scanner = new Scanner(System.in)
      
              for( int i = 0; i < arrayOfNames.length; i++ ) {
                  if( scanner.hasNextLine() ) {
                      String studentName = scanner.nextLine();
                      arrayOfNames[i] = studentName;
                  } else {
                      break;
                  }
              }
      
              System.out.printf( "Names: %s", Arrays.toString( studentNames ) )
      
          }
      
      }
      

      【讨论】:

      • 不是我想要的,在输入一个名称后,我希望它退出将用户带回菜单的功能。只有当他们选择再次输入名称时,我才希望他们被带回该函数并将名称写入下一个索引
      【解决方案6】:

      您可以使用ArrayList 并以这种方式检查大小。这样,如果用户在 10 点之前停止,您就不会被空值困住。

      ArrayList<String> names = new ArrayList<String>();
      
      Scanner scanner = new Scanner(System.in);
      String input = "";
      String name;
      
      while (names.size() < 10) {
          if (input.equalsIgnoreCase("no") break;
      
          System.out.println("Enter an name: ");
          name = input.nextLine();
      
          names.add(name);
      
          System.out.println("Would you like to continue?");
          input = scanner.nextLine();
      
      }
      

      【讨论】:

      • while (true &amp;&amp; names.size() &lt; 10) 这里不需要true
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      • 2022-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多