简体   繁体   English

如何在java中使用迭代器获取数组的所有元素?

[英]how to get all the elements of an array using iterator in java?

I have tried to take inputs in an array using Scanner, But there is something unusual happening, suppose , I am giving the inputs to the integer array as 1 2, when I am trying to print it is giving me 2 0. I am giving the code for further clarification我曾尝试使用 Scanner 在数组中输入输入,但是发生了一些不寻常的事情,假设,我将整数数组的输入作为 1 2,当我尝试打印它时,它给了我 2 0。我给进一步澄清的代码

package org.prac.comp1;

import java.util.Arrays;
import java.util.Scanner;

public class TestClass {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //int count=0;
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n=sc.nextInt();
        sc.next();
        String str=sc.nextLine();
        sc.next();
        int arr[]=new int[2];
        for(int i=0;i<arr.length;i++){
            arr[i]=sc.nextInt();
            System.out.println(arr[i]);

        }
               }
    }

Input:输入:

8
2
abcdabcd
1
2

output:输出:

2 

请在此处删除 sc.next。

int n = sc.nextInt(); //sc.next(); String str = sc.nextLine();

sc.next() statement after the statement --> String str=sc.nextLine(); sc.next()语句之后的语句 --> String str=sc.nextLine(); still waits for the user to give string value.仍然等待用户提供字符串值。 So sc.next() takes value of 1 and array elements start from 2. That is the reason its showing 2 instead of 1 :)所以sc.next()取值为 1,数组元素从 2 开始。这就是它显示 2 而不是 1 的原因:)

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

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