简体   繁体   English

程序正在运行,但当用户输入整数时出现错误

[英]Program is running but I get error when the user inputs integers

My program runs but I'm getting an error String index out of range: 3 When I enter 1 2 for example.我的程序运行但我得到一个错误String index out of range: 3例如当我输入1 2时。 I tried changing the values of 1 in partStr = str.substring(lastSpace + 1, x);我尝试在partStr = str.substring(lastSpace + 1, x);中更改1的值but that didn't work.但这没有用。 Any ideas what I'm doing wrong?任何想法我做错了什么?

public static void main(String[] args) {
    String str;
    int x;
    int length;
    int start;
    int num;
    int lastSpace = -1;
    int sum = 0;
    String partStr;
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter a series of integers separated by spaces >> ");
    str = keyboard.nextLine();
    length = str.length();
    for (x = 0; x <= length; x++) {
        if (str.charAt(x) == ' ') {
            partStr = str.substring(lastSpace + 1, x);
            num = Integer.parseInt(partStr);
            System.out.println(" " + num);
            sum += num;
            lastSpace = x;
        }
    }
    partStr = str.substring(lastSpace + 1, length);
    num = Integer.parseInt(partStr);
    System.out.println(" " + num);
    sum += num;
    System.out.println("         -------------------" + "\nThe sum of the integers is " + sum);
}

You should traverse upto length - 1.您应该遍历长度 - 1。

The indexing in String is similar to what happens in arrays.If the length of String is 5 for example,the characters are stored in 0-4 index positions. String 中的索引类似于 arrays 中发生的情况。例如,如果 String 的长度为 5,则字符存储在 0-4 个索引位置。

Your current loop is traversing beyond the size of the string.您当前的循环正在遍历字符串的大小。

str.length() will return the amount of characters of the string, let's say N str.length()将返回字符串的字符数,比如说N

for(x = 0; x <= length; x++) will loop N+1 times, instead of N , because the index starts at 0 and you also enter the loop when x is equal to the length for(x = 0; x <= length; x++)将循环N+1次,而不是N ,因为索引从 0 开始,并且当 x 等于长度时您也进入循环

replacing <= with < in the for loop will fix your problem在 for 循环中用<替换<=将解决您的问题

The issue you faced is because you tried to access a character at the index, x (ie str.charAt(x) ) from str where x is beyond the maximum value of the index in str .您面临的问题是因为您尝试从str访问索引x处的字符(即str.charAt(x) ),其中x超出了str中索引的最大值。 The maximum value of the index in str is str.length - 1 whereas the for loop is running up to str.length . str中索引的最大值是str.length - 1for循环运行到str.length In order to fix that problem, you need to change the condition to x < length .为了解决这个问题,您需要将条件更改为x < length

However, even after fixing that issue, your program may fail if any entry is non-integer or if there are multiple spaces in the input.但是,即使在解决了该问题之后,如果任何条目不是整数或输入中有多个空格,您的程序也可能会失败。 A clean way, including exception handling, to do it would be as follows:一种干净的方法,包括异常处理,如下所示:

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

public class Main {
    public static void main(String[] args) {
        String str;
        int sum = 0;
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter a series of integers separated by spaces >> ");
        str = keyboard.nextLine();

        // Split str on space(s) and assign the resulting array to partStr
        String[] partStr = str.split("\\s+");

        // Iterate through partStr[] and add each number to sum
        for (String num : partStr) {
            try {
                sum += Integer.parseInt(num);
            } catch (NumberFormatException e) {
                // Integer::parseInt will throw NumberFormatException for a non-integer string.
                // Display an error message for such entries.
                System.out.println(num + " is an invalid entry");
            }
        }

        // Display the entries and the sum
        System.out.println("Your entries are: " + Arrays.toString(partStr));
        System.out.println("The sum of the integers is " + sum);
    }
}

A sample run:示例运行:

Enter a series of integers separated by spaces >> 10 a 20 10.5 30 b xy 40 
a is an invalid entry
10.5 is an invalid entry
b is an invalid entry
xy is an invalid entry
Your entries are: [10, a, 20, 10.5, 30, b, xy, 40]
The sum of the integers is 100

暂无
暂无

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

相关问题 当用户输入以重复代码时,出现错误 - When the user inputs to repeat the code, I get an error 如何在Java中输入(除非用户输入0以终止程序)? - How do I get while input (except when the user inputs 0 that terminates the program) in Java? 我希望我的程序在用户输入除整数以外的任何内容并将其循环回时显示错误消息 - I want my program to display an error message when the user inputs anything other than an integer and loop it back 当用户输入无效的输入时,如何终止程序? - How can i terminate the program when the user inputs an invalid input? 当用户输入小数点时,如何错误处理代码以防止程序崩溃? - How can I error handle my code to prevent my program from crashing when the user inputs a decimal point? 当用户输入 1 - 2 时,scanner.nextLine() 会导致错误。如何让我的程序接受此输入为 1? - scanner.nextLine() results in an error when user inputs 1 - 2. How do I allow my program to accept this input as 1? 当程序需要整数时用户输入字符串时,如何阻止程序终止? - How do I prevent program from terminating when user inputs a string when the program expects an integer? 用户输入是时程序的继续 - continuation of program when user inputs yes 当用户输入“结束”时如何结束这个程序? - How to end this program when user inputs “end”? 如果用户输入了无效字符,我如何使我的程序向用户输出消息? - If a user inputs an invalid character how can I get my program to output a message to the user?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM