是否可以在没有break语句的情况下编写此程序?

问题描述 投票:0回答:1

编写一个要求用户输入字符串的程序。然后要求用户输入索引值(整数)。您将使用字符串类中的charAt()方法来查找并输出该索引所引用的字符。允许用户通过将其置于循环中来重复这些操作,直到用户为您提供一个空字符串。现在意识到,如果我们用错误的值(负值或大于字符串大小的整数)调用charAt方法,将引发异常。添加代码以捕获此异常,输出警告消息,然后继续循环

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!");
            }
        }
    }
}
java break
1个回答
1
投票

是。您可以依靠赋值评估分配的值。另外,在呼叫Scanner.hasNextInt()之前先呼叫Scanner.nextInt()。喜欢,

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!");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.