“线程中的异常”;“主要”;Main.Main上的java.lang.NegativeArraySizeException
无效的输入流不起作用-每次我给出一个负的月值时,它都会返回此异常 代码:“线程中的异常”;“主要”;Main.Main上的java.lang.NegativeArraySizeException,java,arrays,for-loop,Java,Arrays,For Loop,无效的输入流不起作用-每次我给出一个负的月值时,它都会返回此异常 代码: import java.util.Scanner; 公共班机{ 公共静态void main(字符串[]args){ 扫描仪输入=新扫描仪(System.in); System.out.println(“输入月份:”); int month=input.nextInt(); 如果(月如输入所示,则无法创建大小为负数的数组。您正在正确检查输入的月,但当您获得负值时,您不会终止流。返回ing或退出ing在该点应该可以完成此操作。
import java.util.Scanner;
公共班机{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
System.out.println(“输入月份:”);
int month=input.nextInt();
如果(月如输入所示,则无法创建大小为负数的数组。您正在正确检查输入的月
,但当您获得负值时,您不会终止流。返回
ing或退出
ing在该点应该可以完成此操作。例如:
if (month < 0) {
System.out.println("Invalid Input");
return; // Here
}
if(月<0){
System.out.println(“无效输入”);
return;//在这里
}
或者您可以将else
语句与if
语句一起使用
Scanner input= new Scanner(System.in);
System.out.println("Enter the number of months :");
int month = input.nextInt();
if(month<0)
{
System.out.println("Invalid Input");
}else{
int sum = 0;
int a[] = new int[month];
System.out.println("Enter the profit of each month in shipment");
for (int i=0; i<month; i++)
{
a[i] = input.nextInt();
sum = sum+a[i];
}
System.out.println("Total profit : "+sum);
}
扫描仪输入=新扫描仪(System.in);
System.out.println(“输入月份:”);
int month=input.nextInt();
如果(一个月)当你查看你的代码流时,你可以看到你的实际消息应该是“无效输入,但我正在处理它”(monthEureka!!这就是问题所在,谢谢你帮助我这样的新手!!谢谢这也很有效!!谢谢你的时间和输入抱歉stackoverflow的新消息..现在投票给你..再次感谢你的帮助
Scanner input= new Scanner(System.in);
System.out.println("Enter the number of months :");
int month = input.nextInt();
if(month<0)
{
System.out.println("Invalid Input");
}else{
int sum = 0;
int a[] = new int[month];
System.out.println("Enter the profit of each month in shipment");
for (int i=0; i<month; i++)
{
a[i] = input.nextInt();
sum = sum+a[i];
}
System.out.println("Total profit : "+sum);
}