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

时间:2019-10-11 06:45:15

标签: java

当用户输入单词时,他们将被提示输入子字符串的第一个和第二个索引。我进行了很多排序,但是当我尝试验证下面的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 个答案:

答案 0 :(得分:1)

更改以下内容:

int startIndexstartIndex

int endIndexendIndex

inputSting.lengthinputString.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));
    }
 }

答案 1 :(得分:0)

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

第一

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

您既不能在if语句中也不可以在比较表达式中声明变量,而且变量startIndex已经存在。

第二:

inputSting变量不存在,并且肯定没有属性lengthinputString +字符串的错别字具有方法length()不是属性。