繁体   English   中英

如何在 JAVA 中将多个 int 用户输入存储在一个堆栈中

[英]How to Store multiple int user input in one into STACK in JAVA

我对编程很陌生,我不确定我一直在做什么。 我正在创建一个程序,允许我们用户在单行中输入多个 int 值并将其存储到堆栈中。

例如

输入数字:1 2 3 4 5 6

但我发现唯一的扫描仪只能得到第一个数字。 我怎样才能在一行中获取所有数字并将其存储在堆栈中。

到目前为止,这是我的代码

import java.util.Scanner;
import java.util.Stack;

public class StackPractice {    

    public static void main(String[] args)  {    
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the number of elements to place on the stack [1-10]:");
        int stackSize = sc.nextInt();
        Stack <Integer> stack = new Stack<>();

        System.out.println("Enter " + stackSize + " element(s):");
        for( int i = 0; i < stackSize;i++){
        while(sc.hasNextInt() && i < stackSize){
            stack.push(sc.nextInt());

                int number = sc.nextInt();
                stack.push(number);
            }
        }
        System.out.println(stack);            
    }
}

您的问题在于您的while循环, for循环也是不必要的。 我对您的代码进行了一些更改。

public static void main(String[] args)  {    
    Scanner sc = new Scanner(System.in);

    System.out.println("Enter the number of elements to place on the stack [1-10]:");
    int stackSize = sc.nextInt();
    Stack <Integer> stack = new Stack<>();

    System.out.println("Enter " + stackSize + " element(s):");
   
    int i = 0;
    while(i < stackSize){
        
            int number = sc.nextInt();
            stack.push(number);
            
            i++;
        }
    
    System.out.println(stack);            
}

OUTPUT

 Enter the number of elements to place on the stack [1-10]:
 4
 Enter 4 element(s):
 4 3 3 4
 [4, 3, 3, 4]

暂无
暂无

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

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