如何在一行中输入多个不同类型的变量?例如 ->

使用用 Java 实现的哈希表,我需要获取 5 个输入值,其中 3 个是字符串,2 个是整数。用户必须能够在一行中写入所有输入值。我尝试了很多不同的方法,主要是使用数组,但我无法在网上找到正确的答案。如果有人可以帮助提供示例代码或想法,我将不胜感激:)


Scanner input = new Scanner(System.in);

        Scanner input1 = new Scanner(System.in);


        System.out.println("Enter number of people:");

        int n = input1.nextInt();


        HTable table = new HTable(100);


        String a[] = new String[5];

        for(int i=0; i<n; i++)

        {

            a = input.nextLine().split(" ");

            table.Insert(a[0], a[1], Integer.parseInt(a[2]), a[3], Integer.parseInt(a[4]));

        }

这是我尝试过的最新示例,但它一直在接受输入并且 FOR() 循环似乎没有结束。


临摹微笑
浏览 84回答 1
1回答

Cats萌萌

你可以这样尝试:public class Name{public static void main(String[] args) {&nbsp; &nbsp; Scanner scanner = new Scanner(System.in);&nbsp; &nbsp; System.out.println( "Enter Your Input ");&nbsp; &nbsp; while (scanner.hasNext())&nbsp;&nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (scanner.hasNextInt()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(" Your Value (Int) : " + scanner.nextInt());&nbsp; &nbsp; &nbsp; &nbsp; } else if (scanner.hasNextFloat()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(" Your Value (Float) " + scanner.nextFloat());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println( " String Value(String) " + scanner.next());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java