java - 如何从 for 循环内的文本字段获取多个值并将其接收到数组中

标签 java arrays loops for-loop textfield

我是java方面的新手,我想做的是用户说出他将输入多少数字,所以我将这个数字保存在一个变量中,例如:他想输入5个数字,所以int x= 5; 然后我想接收他将在数组中输入的 5 个数字, 所以我使用 for 循环来获取他将输入的所有数字并将其保存在我的数组中,但是当我运行程序并输入第一个值时,循环仅获取第一个值并完成,所以它不给我机会输入其余数字。

public class Cuentafacil extends Application  {

    int numero_gastos;
    int b;


  @Override
    public void start(Stage stage) 
    {
        Scanner scn=new Scanner(System.in);
        Label label=new Label("cuantos gastos tienes hoy ");
        Button Agregar=new Button("Listo");
        TextField nrgastos = new TextField();
        TextField nrgastos2=new TextField();
        Label label2=new Label();
Agregar.setOnAction((ActionEvent e) ->
        {

          numero_gastos= Integer.parseInt(nrgastos.getText());
           root.getChildren().remove(Agregar);
           root.getChildren().remove(nrgastos);
           label.setText("Comiezna a poner los gastos");
           Agregar.setText("Agregar");

           root.getChildren().add(nrgastos2);
           root.getChildren().add(Agregar);


           nrgastos2.setPromptText("entra un gasto");
           nrgastos2.setTranslateX(160);
           nrgastos2.setTranslateY(50);
           int [] w = new int[numero_gastos];




            Agregar.setOnAction((ActionEvent s)->
            {
              b=Integer.parseInt(nrgastos2.getText());
             for (int x=0;x<numero_gastos;x++)
         {
             try{

         w[x]=b;
           nrgastos2.nextWord();

         nrgastos2.clear();


             }
             catch (Exception f)
             {
             System.out.println("here is the problem");
             }
         }

            System.out.println(IntStream.of(w).sum());

            });


        });

最佳答案

您可以做的是为文本字段字符串创建一个Scanner,然后将元素存储在数组中,如下所示:

Scanner numReader = new Scanner(nrgastos.getText());
int [] w = new int[numero_gastos];

for (int i = 0; i < numero_gastos; i++) {
    w[i] = numReader.nextInt();
}

numReader.close();

关于java - 如何从 for 循环内的文本字段获取多个值并将其接收到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56719108/

相关文章:

Javac 找不到类路径中引用的包

java - 嵌入 Tomcat 并向部署的应用程序发出请求

java - 自定义 OutputStreamAppender 未运行 : LOGBACK: No context given for <MYAPPENDER>

java - 是否可以使用Java检查hadoop集群是否启用了yarn?

javascript - 如何找到与两个数组相交的所有对象?

java - 如何使用条件语句检查数组是否等于矩阵的一行?

python - 当第一个维度的第一个大小匹配时,创建数组的数组失败

Java 程序计算平均值。如何显示最高平均值?

Java 数组循环行为

Bash 循环获取文件名中的前 12 个字符,使用输出为每个文件运行 touch -t 命令