我是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/