简体   繁体   English

使用JOptionPane计算java中的连续字母?

[英]Counting consecutive letters in java using JOptionPane?

I'm trying to count consecutive letters in java using JOptionPane and when I try to compile and run my code I get this: 我正在尝试使用JOptionPane计算java中的连续字母,当我尝试编译并运行代码时,我得到以下信息:

exception in thread main java.lang.StringIndexOutOfBoundsException: String index out of range: 5

I feel like I have most of it down so I'm not exactly sure what's wrong here. 我觉得我大部分时间都没有了,所以我不确定这是怎么回事。 Any help would be appreciated. 任何帮助,将不胜感激。

My code: 我的代码:

import javax.swing.JOptionPane;

public class Project {

    public static void main(String[] args) {

        String input = JOptionPane.showInputDialog("Enter a string...");

        while (true) {

            if (input.equals("Stop")) System.exit(0);

            else {
                int count = 0;
                int len = input.length();
                for (int i = 0; i < len; i++) {
                    if (input.charAt(i) == input.charAt(i + 1)) count++;
                }

                JOptionPane.showMessageDialog(null, "There are " +
                    count + "pairs of consecutive letters.");

                input = JOptionPane.showInputDialog(null,
                    "Enter a string...");
            }
        }
    }
}

Problem is: 问题是:

input.charAt(i + 1)

This will throw an error because when you are at the last element of the array it will try and get the next element but there isn't one. 这将引发错误,因为当您位于数组的最后一个元素时,它将尝试获取下一个元素,但没有一个。 Consider revising your logic slightly. 考虑稍微修改一下逻辑。

In your for loop you could do: 在您的for循环中,您可以执行以下操作:

for (int i = 0; i < len - 1; i++) {

The JOptionPane has absolutely nothin to do with that, you should fix your title. JOptionPane绝对没有与此相关的内容,您应该修复标题。 The problem is here : 问题在这里:

for (int i = 0; i < len; i++) {
   if (input.charAt(i) == input.charAt(i + 1)) count++;
}

replace that piece of code with 用那段代码代替

for (int i = 0; i < len - 1 ; i++) {
    if (input.charAt(i) == input.charAt(i + 1)) count++;
}

This is a basic error, it is important for an efficient programer to be able to deal with this alone and quickly. 这是一个基本错误,对于高效的编程人员而言,能够单独快速地解决此问题很重要。

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

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