简体   繁体   English

运行时错误_字符串索引超出范围异常_打印字符串奇偶索引

[英]Run Time Error_String index out of bound Exception_Printing string odd and even indexes

Code:代码:

import java.io.进口 java.io。 ; ; import java.util.导入 java.util。 ; ;

public class Solution {公共 class 解决方案 {

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

    int n = sc.nextInt();
    String[] sa = new String[n];
    for(int i=0;i<n;i++){

        sa[i] = sc.nextLine();
    }
        String odd="";
        String even="";
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<sa[i].length();j++)
            {
             if(j%2!=0){
               odd = odd+sa[j].charAt(j);
            }
            else {
                even = even+sa[j].charAt(j);
            }
       
            }
            System.out.println(odd+" "+even);
            }
}

} }

ISsue: GEtting run time exception while running the code.问题:运行代码时出现运行时异常。 --> String index out of bound exception --> 字符串索引越界异常

You can try below code.你可以试试下面的代码。 It is because of calling a method like nextInt() before sc.nextLine()这是因为在sc.nextLine() nextInt()的方法

The problem is that nextInt() does not consume the '\n', so the next call to nextLine() consumes it and then it's waiting to read the input for next element.问题是 nextInt() 不消耗 '\n',所以下一次调用 nextLine() 消耗它,然后它等待读取下一个元素的输入。

You need to consume the '\n' before calling nextLine() or You can directly call nextLine() for array size as well.您需要在调用nextLine()之前使用 '\n' 或者您也可以直接调用nextLine()来获取数组大小。

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Array size");
        int n = Integer.parseInt(sc.nextLine());
        String[] sa = new String[n];
        for (int i = 0; i < n; i++) {
            System.out.println("Enter Element "+i);
            String val = sc.nextLine();
            sa[i]=val;
        }
        String odd = "";
        String even = "";
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < sa[i].length(); j++) {
                if (j % 2 != 0) {
                    odd = odd + sa[j].charAt(j);
                } else {
                    even = even + sa[j].charAt(j);
                }

            }
            System.out.println(odd + " " + even);
        }
    }

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

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