有没有办法使用 .hasNext 之外的其他方法来编写此程序?

Is there a way to write this program using another method than .hasNext?

Write a program that asks a user to input a string. Then asks a user to type in an index value(integer). You will use the charAt( ) method from the string class to find and output the character referenced by that index. Allow the user to repeat these actions by placing this in a loop until the user gives you an empty string. Now realize that If we call the charAt method with a bad value (a negative value or a integer larger than the size of the string) an exception will be thrown. Add the code to catch this exception, output a warning message and then continue with the loop

import java.util.Scanner;

class Main
{
    public static void main(String[] args)
    {
        System.out.println("");
        String s;
        int ind;
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext())
        {
            s=sc.next();
            if(s.length()==0)
                break;
            ind=sc.nextInt();
            try {
                char ch=s.charAt(ind);
                System.out.println("Character is "+ch);
            }
            catch(Exception e) {
                System.out.println("Bad index Error!");
            }
        }
    }
}

是的。您可以依赖赋值评估赋值。另外,在调用 Scanner.nextInt() 之前调用 Scanner.hasNextInt()。喜欢,

System.out.println();
String s;
Scanner sc = new Scanner(System.in);
while (sc.hasNext() && !(s = sc.next()).isEmpty()) {
    if (sc.hasNextInt()) {
        int ind = sc.nextInt();
        try {
            char ch = s.charAt(ind);
            System.out.println("Character is " + ch);
        } catch (Exception e) {
            System.out.println("Bad index Error!");
        }
    }
}

有错误; sc.next() 不能 return 此代码中的空字符串。试试这样编辑:

while(sc.hasNext()) {
    s = sc.next();
    if(s.length() == 0) {
        System.out.println("Woah, Nelly!");
        break;
    }
    // ...
}

看看是否可以通过输入空行或其他任何内容让程序打印 "Woah, Nelly!"。我不能,假设我正确理解 the documentationif 条件不可能在这里成立(强调我的):

Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern "\s" could return empty tokens since it only passes one space at a time.

此模式 "\s+" 是默认模式,您还没有设置其他模式,因此您的扫描器永远不会 return 空标记。所以对 "is there a way to write this program without the break statement?" 的严格回答是:是的,你可以只删除 if(...) break; 代码,它不会以任何方式改变行为。

但是,这并不能真正解决您的问题,因为它没有为用户提供退出程序的方法。您应该使用 nextLine() 而不是 next() 以允许从用户读取空白行。