java中循环期间的子字符串

java中循环期间的子字符串,java,string,Java,String,我昨天在试一个问题(这不是问题),但它一再给我错误。 我要做的是取一个子字符串,将它转换为int,然后打印出来 但它给出了错误 线程“main”java.lang.StringIndexOutOfBoundsException中的异常:字符串索引超出范围:2 这是我的实现 import java.util.Scanner; import java.io.*; class gerald{ public static void main(String [] s) {

我昨天在试一个问题(这不是问题),但它一再给我错误。 我要做的是取一个子字符串,将它转换为int,然后打印出来 但它给出了错误
线程“main”java.lang.StringIndexOutOfBoundsException中的异常:字符串索引超出范围:2

这是我的实现

import java.util.Scanner;
import java.io.*;
class gerald{
    public static void main(String [] s)
    {
        long t2,t3,t,a,b,c;

        Scanner sc=new Scanner(System.in);
        t=sc.nextInt();
            for(int i=1;i<=t;i++)
            {
              String time1=new String(sc.nextLine());

                long t1=Integer.parseInt(time1.substring(0,2));
                System.out.println(t1);
            }
     }
}
import java.util.Scanner;
导入java.io.*;
杰拉尔德班{
公共静态void main(字符串[]s)
{
长t2、t3、t、a、b、c;
扫描仪sc=新的扫描仪(System.in);
t=sc.nextInt();

对于(int i=1;i在执行
time1.substring(0,2)
之前,您应该首先检查
time1的长度。您可以做的最好的事情是调试它。您可以做的另一件事是处理异常行为,您可以先询问
if-else
if(timer1.length()<2)
或使用
试试catch

让我试试看

    public static void main(String [] args){
            int t,t1;
            Scanner sc=new Scanner(System.in);
            t=sc.nextInt();
            String time1=null;
            for(int i=1;i<=t;i++){
                 time1=sc.nextLine();
                 try{
                       t1=Integer.parseInt(time1.substring(0,2));
                       System.out.println(t1);
                 }catch(NumberFormatException e){
                       System.err.println("input string is not a number ---> "+time1);  
                 }catch(StringIndexOutOfBoundsException e){
                       System.err.println("input string is shorter than required ---> "+time1);   
                 }

             }
   }
publicstaticvoidmain(字符串[]args){
int t,t1;
扫描仪sc=新的扫描仪(System.in);
t=sc.nextInt();
字符串time1=null;

对于(int i=1;我认为这取决于您的输入……此外,您不需要调用
新字符串(…)
sc.nextLine()
已经返回了一个字符串。当我插入tso的值时,会出现此错误。我是否应该编写一个条件?是的,您可能还需要尝试捕获整数的可能NumberFormatException。parseInt()谢谢,我明白了。我必须介绍if-else。虽然这段代码总是捕获异常。@不客气,我对您的代码做了一些更改,比如使用
int
而不是
long
,因为它不是必需的,或者不是每次都创建
新字符串
,并将局部变量放在循环的外部!也捕获一个可能性le
NumberFormatException