Java代码TypeMismatch异常求助:变量‘first’类型不匹配
first的类型不匹配问题 Hey there! Let's break down what's going on with your code and that type mismatch error for the first variable.
首先从代码本身来看:first被声明为int类型,并且通过scanner.nextInt()赋值——nextInt()返回的就是整数,这部分编译时完全符合类型要求,不会出现类型不匹配的问题。你遇到的错误大概率是运行时的输入异常被误判,或是后续代码的隐含问题引发的混淆提示,我们一步步拆解:
核心问题1:输入缓冲区的换行残留引发的异常
当你用scanner.nextInt()读取整数后,输入流里的换行符并没有被消费掉。接下来执行ip=scanner.nextLine();时,它会直接读取这个换行符,得到一个空字符串""。
这时候执行firstpart=ip.substring(first),如果first是大于0的整数,就会抛出StringIndexOutOfBoundsException——因为空字符串的长度是0,无法从正数索引位置截取内容。这个异常可能被你的开发环境误提示为“类型不匹配”。
核心问题2:输入非整数时的类型不匹配
如果用户输入给first的不是整数(比如字母、符号),scanner.nextInt()会抛出InputMismatchException,这时候也会被描述为“类型不匹配”——因为程序期望整数,但收到了其他类型的输入。
修复方案
针对这两个问题,我们可以修改代码来解决:
方案1:修复输入缓冲区的换行残留
在读取完整数后,调用scanner.nextLine()消费掉残留的换行符,再读取目标字符串:
import java.util.*; public class Hello { public static void main(String[] args) { String ip,firstpart,lastpart; int first,last,strlen,newvar; Scanner scanner=new Scanner(System.in); first=scanner.nextInt(); // 消费nextInt()留下的换行符 scanner.nextLine(); if(scanner.hasNextInt()){ last=scanner.nextInt(); // 同样消费换行符 scanner.nextLine(); } else { last=0; } ip=scanner.nextLine(); // 先判断first是否超出字符串长度,避免索引越界 if(first >= ip.length()) { System.out.println("first值超出输入字符串的长度!"); return; } firstpart=ip.substring(first); strlen=firstpart.length(); newvar=strlen-last; // 确保截取的结束索引不小于0 newvar = Math.max(newvar, 0); lastpart=firstpart.substring(0,newvar); System.out.println(lastpart); } }
方案2:添加非整数输入的校验(可选)
如果要避免用户输入非整数导致的异常,可以提前做输入验证:
// 替换原first的赋值代码 while (!scanner.hasNextInt()) { System.out.println("请输入有效的整数!"); scanner.nextLine(); // 消费无效输入内容 } first = scanner.nextInt(); scanner.nextLine(); // 消费换行符
内容的提问来源于stack exchange,提问作者Niharika

