简体   繁体   English

如何创建一个最后显示所有名称的程序?

[英]How can I create a program that displays all the names at the end?

I'm not sure why I can't get this type of concept down.我不知道为什么我不能理解这种类型的概念。 I have to keep it as simple as possible.我必须让它尽可能简单。 I am trying to get a list of students in a class, and then display them at the end when the user inputs 2.I've switched it around a few times, but end up at the same point every time.我正在尝试获取 class 中的学生列表,然后在用户输入 2 时在最后显示它们。我已经切换了几次,但每次都在同一点结束。 I tried doing if statements for a 1 and a 2 answer, but still didn't get anywhere.我尝试为 1 和 2 的答案做 if 语句,但仍然没有得到任何结果。

Thank you everyone.谢谢大家。

package peopleinclass;
import java.util.Scanner;

public class PeopleinClass {
    static Scanner get=new Scanner(System.in);
    static String yourName;
    static String studentNames = "";
    static int answer = 1;
    
    public static void main(String[] args) 
    {
        getNames();

        while(true)
        {
            if(answer == 1  )
            {
                System.out.println("Would you like to add another student? 1 for yes 2 for no ");
                answer=get.nextInt();   
                System.out.println("Please enter another students name: ");
                yourName = get.nextLine();  
                get.nextLine();
                yourName+;
                break;  
            }
        }
        Display();      
    }

    public static String getNames()
    {
        System.out.println("Please enter your students name: ");
        yourName = get.nextLine();

        return yourName;
    }

    public static void Display()
    {
        System.out.println("Below are the students in the class: ");
        System.out.println(yourName);
    }
}
  1. The code you posted doesn't compile.您发布的代码无法编译。 yourName+; can't be compiled无法编译
  2. You have a String studentNames but you never assign any value to it.您有一个 String studentNames但您从未为其分配任何值。
  3. You are reading the input in the getNames() method but you never use the return value.您正在读取getNames()方法中的输入,但您从不使用返回值。

I would suggest the following changes:我建议进行以下更改:

  1. Assign the return value of the getNames() method to the studentNames variable.getNames()方法的返回值分配给studentNames变量。
  2. remove the yourName+;删除您的yourName+; line.线。
  3. In your Display() method print studentNames instead of yourName在您的Display()方法中打印studentNames而不是yourName
  4. You have a get.nextLine() and you are not using it's value.你有一个get.nextLine()并且你没有使用它的价值。 Also concatenate the return value with your studentNames variable.还将返回值与您的studentNames变量连接起来。

This looks like a school homework to me, so I didn't post a solution just try to give you some hints.对我来说,这看起来像是一项学校作业,所以我没有发布解决方案,只是想给你一些提示。

It looks like you may be struggling a bit with the problem and your understanding of programming so I have provided a solution below with verbose commenting.看起来你可能在这个问题和你对编程的理解上有点挣扎,所以我在下面提供了一个带有详细注释的解决方案。 I urge you to read this whole post and the content in the links that I have provided underneath the code.我敦促您阅读整篇文章以及我在代码下方提供的链接中的内容。

If this is a school/college/university project then do not just take the solution and use it without understanding how it works because you will just continue to struggle throughout your studies.如果这是一个学校/学院/大学项目,那么不要在不了解它的工作原理的情况下采用解决方案并使用它,因为您将在整个学习过程中继续挣扎。 I have provided this code to try and help you understand the problem and how it can be solved.我提供了这段代码来尝试帮助您理解问题以及如何解决它。 If you need any further information then reply in the comment section below.如果您需要任何进一步的信息,请在下面的评论部分回复。

package peopleinclass;

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

class PeopleinClass {

    private static Scanner get = new Scanner(System.in);
    private static int answer = 1;
    private static String nextName = null;
    
    public static void main(String[] args) 
    {
      //Initialise an ArrayList of type String.
      ArrayList<String> listOfNames = new ArrayList<String>();

      //Request the first student name and store the value in 
      //the nextName variable which is initialised at the 
      //top of this class.
      nextName = requestFirstStudentName();

      //Add the value of nextName in to the ArrayList.
      listOfNames.add(nextName);

      //Create a do...while loop which executes all of the code 
      //inside the bracers at least once and then continues to 
      //execute the code based on the while (...) condition at 
      //the end of the bracers.
      do {

          System.out.println("Would you like to add another student? 1 for yes 2 for no ");

          //Prompt the user to enter a value which we assume is of type 
          //int. If the value the user enters here is not of type int 
          //and is a String instead, the program will crash. Type 
          //checking should be done here to make sure it is an 
          //int but for simplicity I have left type checking out.
          answer = get.nextInt();

          //Clear any tokens that are left in the scanner.
          get.nextLine();

          //If the answer given when prompted for an int (above) 
          //is equal to 1.
          if(answer == 1)
          {
            System.out.println("Please enter another students name: ");

            //Prompt the user to enter another name.
            nextName = get.nextLine();

            //Add another entry to our ArrayList of type String.
            listOfNames.add(nextName);
          }

      //While the user has given the answer of 1 (above when asked for int) 
      //go back to the top of the do...while loop and repeat the process 
      //again.
      } while (answer == 1);

      //Call the display(...) method, which accepts an ArrayList 
      //of type String and is defined in this class further 
      //down.
      display(listOfNames);
    }

    public static String requestFirstStudentName()
    {
        System.out.println("Please enter your students name: ");

        //Prompt the user to enter a name.
        nextName = get.nextLine();

        //Return the name back to where it was invoked.
        return nextName;
    }

    public static void display(ArrayList<String> listOfNames)
    {
        System.out.println("Below are the students in the class: ");

        //Create a for loop, initialising a variable of type 
        //int and set it to 0. The rest of the for loop can 
        //be read as - while i is less than the size of 
        //the ArrayList of type String, print the next 
        //String stored in the ArrayList and increment i.
        for(int i = 0; i < listOfNames.size(); i++)
        {
          System.out.println(listOfNames.get(i));
        }
    }
}

As you can see, I made use of the ArrayList data structure provided in the java.util.* package that is provided with the Java language. As you can see, I made use of the ArrayList data structure provided in the java.util.* package that is provided with the Java language. Read more about ArrayList and how it works here .在此处阅读有关ArrayList及其工作原理的更多信息。

You will also see that I have made use of a do...while loop.您还将看到我使用了do...while循环。 The do...while loop is provided in quite a few different languages but is not very commonly used, however it fits for the scenario that you have presented. do...while循环以多种不同的语言提供,但不是很常用,但它适合您所呈现的场景。 Find more about the do...while loop here .此处查找有关do...while循环的更多信息。

I also made use of a for loop to iterate through the ArrayList in the display() method.我还使用了一个for循环来遍历display()方法中的ArrayList Find out more about the for loop here .在此处了解有关 for 循环的更多信息。

In the comments I talk about reading the nextInt() from the Scanner class and how type checking should be done.在评论中,我谈到了从Scanner class 读取nextInt()以及应该如何进行类型检查。 The reason I say this is because you are relying on the user entering a number (users are generally idiots and decide to enter a String instead).我这样说的原因是因为您依赖于用户输入数字(用户通常是白痴并决定输入字符串)。

If a String was entered instead of an int then you would get a java.util.InputMismatchException so the best approach here would be to ask for the nextLine() instead and try and convert the line to an int .如果输入了String而不是int ,那么您将得到java.util.InputMismatchException所以这里最好的方法是请求nextLine()并尝试将该行转换为int

Converting from a String to an int can be found here .String转换为int可以在这里找到。 You will find the answer at that link shows the use of a try...catch block where, if trying to convert from a String to an int doesn't work, it will go to the catch block where you can set the int to a default value.您将在该链接上找到答案显示使用try...catch块,如果尝试从String转换为int不起作用,它将 go 到您可以将int设置为的 catch 块默认值。

暂无
暂无

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

相关问题 如何在循环中捕获重复出现的用户输入,然后在程序结束时全部显示它们? - How can I capture recurring user inputs in a loop and then display them all at the end of the program? 如何创建搜索方法来搜索与所有其他条目名称完全匹配的名称 - How can I create a search method to search for name which completely matches all the other entry names 我正在尝试创建一个程序,该程序读取一个字符串并显示每个字母有多少个,但是它不起作用 - I'm trying to create a program that reads a string and displays how many of each letter there is, but it isn't working 如何通过单击按钮而无需重置计数器的方法来创建一个在阵列中存储大量名称/数字的程序? - How can I create a program that stores a numerous amount of names/numbers in an array by clicking a button without the method resetting my counter? 该程序是否以无限循环结束? 我该怎么说? - Does this program end in an infinite loop? How can I tell? 当其中一名玩家获胜时,我如何结束我的计划? - How can I end my program when one of players win? 如何在Java中的try catch语句期间结束程序? - How can I end a program during a try catch statement in Java? 如何使用我的加密程序创建解密程序? - How can I use my encryption program to create a decryption program? 如何获取模式的所有表名称? - How can I get all tables names of a schema? 如何在所有行尾添加特定符号? - How can I add particular symbol in all line end?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM