#10841: Java新手 請問Overflow怎麼處理


jing850306 (unknown)


import java.util.Scanner;

public class Test244 {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N,a,b,c,result;
while(sc.hasNext())
{
N=sc.nextInt();
for(int i=0;i<N;i++)
{
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
switch(a)
{
case 1:
result=b+c;
System.out.printf("%d\n",result);
break;
case 2:
result=b-c;
System.out.printf("%d\n",result);
break;
case 3:
result=b*c;
System.out.printf("%d\n",result);
break;
case 4:
result=b/c;
System.out.printf("%d\n",result);
break;
}
}
}
}

}

#10846: Re:Java新手 請問Overflow怎麼處理


tomoyaken14 (歐練)


import java.util.Scanner;

public class Test244 {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N,a,b,c,result;
while(sc.hasNext())
{
N=sc.nextInt();
for(int i=0;i<N;i++)
{
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
switch(a)
{
case 1:
result=b+c;
System.out.printf("%d\n",result);
break;
case 2:
result=b-c;
System.out.printf("%d\n",result);
break;
case 3:
result=b*c;
System.out.printf("%d\n",result);
break;
case 4:
result=b/c;
System.out.printf("%d\n",result);
break;
}
}
}
}

}



long?

#55520: Re: Java新手 請問Overflow怎麼處理


qwertyuiopowengary@gmail.com (李璟豪Owen)


1. 使用更大的型態

  • 如果數字可能超過 int,改用 long(64 位元,範圍更大)。

  • 如果還不夠,可以用 BigInteger(無限大整數,靠物件運算)。

    2. 檢查運算前後

    • 在運算前先檢查是否會超過範圍。

    • Java 提供 Math.addExact()Math.multiplyExact() 等方法,若溢位會丟出 ArithmeticException