简体   繁体   English

阵列无法正确打印出所有答案

[英]Array not printing out all answers correctly

Im making a main method that creates an array to keep track of some presidential candidates. 我正在制作一种主要方法,该方法创建一个数组来跟踪某些总统候选人。 The user inputs the number of candidates they want, and then inputs the candidates names they want in the election, then prints out the candidates with what position they were put in (1, 2, 3 not 0, 1, 2). 用户输入他们想要的候选人数量,然后输入他们想要的选举候选人名称,然后打印出候选人所处的位置(1、2、3而不是0、1、2)。 Right now the method only prints out the 2nd and 3rd names, and will not print the 1st name. 现在,该方法仅打印出第二和第三名称,而不会打印出第一名称。

public class RunElection


/**
 * 
 */
public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    System.out.println("Please input the number of candidates you would like in this election.");  
    int numCandidates = scan.nextInt();
    while (numCandidates <= 0) {
        System.out.println("Please input a number that is greater than zero.");   
        numCandidates = scan.nextInt(); 
    } 
    String[] candidates;
    candidates = new String[numCandidates];  

    System.out.println("Please input the name of the candidates in the election."); 
    String newCandidate = scan.nextLine(); 
    String newString = " "; 
    String finalString = " "; 

    for (int i = 0; i<candidates.length; i++) {
        candidates[i] = newCandidate; 
        newCandidate = scan.nextLine();    
    }

    for(int i = 0; i<candidates.length; i++) {
        newString = "the candidates names are: " + " " + i + " ) " + candidates[i];
        finalString = finalString+ newString;  
    }
    System.out.println(finalString); 


}

Here, the following for loop is the problem 在这里,下面的for循环就是问题所在

for (int i = 0; i<candidates.length; i++) {
        candidates[i] = newCandidate; 
        newCandidate = scan.nextLine();    
}

What happens is, even though you feel like you are entering 5 candidates, you have actually stored 4 in the array. 发生的是,即使您感觉要输入5个候选者,您实际上已经在阵列中存储了4个。 To resolve this, just interchange the lines as, 要解决此问题,只需将行交换为

for (int i = 0; i<candidates.length; i++) {
    newCandidate = scan.nextLine();
    candidates[i] = newCandidate;     
}

In your first for loop you are reading numCandidates -1 values instead of numCandidates , so you could just swap the lines inside your for loop: 在您的第一个for循环中,您正在读取numCandidates -1值,而不是numCandidates ,因此您可以在for循环内交换行:

for (int i = 0; i<candidates.length; i++) {
    newCandidate = scan.nextLine();
    candidates[i] = newCandidate;     
}

I guess you can even remove the variable newString and just use the variable finalString : 我想你甚至可以删除变量newString ,只是使用的变量finalString

import java.util.Scanner;

public class RunElection {
  public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Please input the number of candidates you would like in this election.");
      int numCandidates = scan.nextInt();

      while (numCandidates <= 0) {
          System.out.println("Please input a number that is greater than zero.");
          numCandidates = scan.nextInt();
      }

      String[] candidates;
      candidates = new String[numCandidates];

      System.out.println("Please input the name of the candidates in the election.");
      String newCandidate = scan.nextLine();
      String finalString = "";

      for (int i = 0; i<candidates.length; i++) {
          newCandidate = scan.nextLine();
          candidates[i] = newCandidate;
      }

      for(int i = 0; i<candidates.length; i++) {
          finalString += "The candidates names are: " + " " + i + ") " + candidates[i] + "\n";
      }

      System.out.println(finalString);
    }
}

looping problem,the code must be as follows. 循环问题,代码必须如下。

public class RunElection



public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    System.out.println("Please input the number of candidates you would like in this election.");  
    int numCandidates = scan.nextInt();
    while (numCandidates <= 0) {
        System.out.println("Please input a number that is greater than zero.");   
        numCandidates = scan.nextInt(); 
    } 
    String[] candidates;
    candidates = new String[numCandidates];  

    System.out.println("Please input the name of the candidates in the election."); 

    String newString = " "; 
    String finalString = " "; 

    for (int i = 0; i<candidates.length; i++) {
newCandidate = scan.nextLine();  
            candidates[i] = newCandidate; 

    }

    for(int i = 0; i<candidates.length; i++) {
        newString = "the candidates names are: " + " " + i + " ) " + candidates[i];
        finalString = finalString+ newString;  
    }
    System.out.println(finalString); 


}

This is a reoccurring problem. 这是一个经常发生的问题。 nextInt() stops when it encounters a non-digit, and it leaves that non-digit in the input stream. nextInt()遇到一个非数字时,它将停止,并将该非数字留在输入流中。

int numCandidates = scan.nextInt();
String newCandidate = scan.nextLine();

If your input stream consists of: 如果您的输入流包括:

3
Alice
Bob
Carol

It actually looks to the Scanner like: 扫描仪实际上看起来像:

3 \n A l i c e \n B o b \n C a r o l \n

After nextInt() is called (which returns 3 , as expected), the input stream is left with: 调用nextInt() (按预期返回3 )后,输入流将保留:

\n A l i c e \n B o b \n C a r o l \n

When nextLine() is called, all the characters up to the next newline character are read, and returned, and the newline is consumed. 调用nextLine() ,读取并返回直到下一个换行符的所有字符,并且消耗了换行符。 Thus, "" is returned for newCandidate , not "Alice" ! 因此, ""则返回newCandidate ,而不是"Alice"

If done in a loop: 如果循环完成:

int numCandidates = scan.nextInt();
for(int i=0; i<numCandidates; i++) {
    String newCandidate = scan.nextLine();
    //...
}

The 3 candidates returned are: 返回的3名候选人为:

  • "" “”
  • "Alice" “爱丽丝”
  • "Bob" “鲍勃”

The take home is to remember to call nextLine() to remove trailing newline characters after a line has been partially read by other nextXXX() calls. 带回家的地方是记住在其他nextXXX()调用已部分读取一行后,调用nextLine()删除尾随的换行符。

First you have some unnecessary string variables. 首先,您有一些不必要的字符串变量。 Try this out, at least it works fine on my machine! 试试看,至少在我的机器上可以正常工作!

        String[] candidates = new String [numCandidates];
        System.out.println("Please input the name of the candidates in the election, one on each line"); 
        Scanner scan = new Scanner(System.in);
        StringBuilder finalCandidates = new StringBuilder(); 

        for (int i = 0; i < candidates.length; i++) {
            candidates[i] = scan.nextLine(); 
        }
        scan.close();

        for(int i = 0; i < candidates.length; i++) {
            finalCandidates.append(i + 1 + ") " + candidates[i] + " ");
        }

        System.out.println("The candidates names are: " + " " + finalCandidates.toString());

EDIT : Samples 编辑 :样本

Assuming numCandidates = 3 and names entered are Will Linger, Andy Putty, Jimmy , the output should be " The candidates names are: 1) Will Linger 2) Andy Putty 3) Jimmy " 假设numCandidates = 3并且输入的名称是Will Linger, Andy Putty, Jimmy ,则输出应为“ The candidates names are: 1) Will Linger 2) Andy Putty 3) Jimmy

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

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