为了账号安全,请及时绑定邮箱和手机立即绑定

我需要验证用户输入的字符串的索引是否有效

我需要验证用户输入的字符串的索引是否有效

猛跑小猪 2023-10-13 15:16:20
当用户输入单词时,系统会提示他们输入子字符串的第一个和第二个索引。我已经排序了这么多,但是当我尝试验证使用下面的 if 语句输入的索引时,我收到了有关这些 if 语句的错误,import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        String inputString;        int startIndex;        int endIndex;        System.out.println("Enter a string : ");        inputString = scanner.nextLine();        System.out.println("Enter the first index of the substring : ");        startIndex = scanner.nextInt();        if (int startIndex > inputSting.length) {            System.out.println("Index is not in string length, try again.");        }        System.out.println("Enter the second index of the substring : ");        endIndex = scanner.nextInt();        if (int endIndex > inputSting.length) {            System.out.println("Index is not in string length, try again.");        }         char[] ch = new char[endIndex - startIndex + 1];        inputString.getChars(startIndex, endIndex + 1, ch, 0);        System.out.println("Output : " + String.valueOf(ch));    }}
查看完整描述

2 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

你的代码绝对不是Java语言。

第一的:

if (int startIndex > inputSting.length) { .. }

您不能在if语句内或比较表达式中声明变量,而且该变量startIndex已经存在。

第二:

inputSting变量不存在并且它肯定没有属性lengthinputString可能是+ string 有方法length()而不是属性的拼写错误。


查看完整回答
反对 回复 2023-10-13
?
开满天机

TA贡献1786条经验 获得超12个赞

更改以下内容:


int startIndex到startIndex,


int endIndex到endIndex,


inputSting.length到inputString.length()


所以固定代码,


 public class Main {

     public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        String inputString="";

        int startIndex;

        int endIndex;


        System.out.println("Enter a string : ");

        inputString = scanner.nextLine();


        System.out.println("Enter the first index of the substring : ");

        startIndex = scanner.nextInt();


        if ( startIndex > inputString.length()) {

            System.out.println("Index is not in string length, try again.");

        }



        System.out.println("Enter the second index of the substring : ");

        endIndex = scanner.nextInt();


        if ( endIndex > inputString.length()) {

            System.out.println("Index is not in string length, try again.");

        }

        char[] ch = new char[endIndex - startIndex + 1];

        inputString.getChars(startIndex, endIndex + 1, ch, 0);

        System.out.println("Output : " + String.valueOf(ch));

    }

 }


查看完整回答
反对 回复 2023-10-13
  • 2 回答
  • 0 关注
  • 68 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信