Java show the warning mean it may cause error. I don't want to ignore the warning of "Resource leak". How to solve resource leak, show in "switch-case" return even write keyin.close()? If I don't write keyin.close(), the "Resource leak" show in Scanner(System.in). It mean "Resource leak" must happen?? That is tricky.
Below is the program. Please help. Thanks a lot.
package JPack001_20210722;
import java.util.Scanner;
public class JClass008_20210722 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n,sum;
char addChoice;
Scanner keyin=new Scanner(System.in);
System.out.print("1+2+...+n=? Please input n: ");
n=Integer.parseInt(keyin.nextLine());
System.out.print("Which you need as odd sum(O), even sum(E) or Integer(I)?");
System.out.print("Please choose: ");
addChoice=keyin.nextLine().charAt(0);
/* charAt(index), is char at index. Get the character from the string.
* string Odd -> O is index(0), d is index(1), d is index(2)
* charAt(0), if string is Odd, will get index(0)is 'O'
* then set the O to addChoice to run switch(addChoice)
*/
switch(addChoice) {
case 'O':
sum=odd(n); // call odd(n) function and input n(line 13)
break;
case 'E':
sum=even(n); // call even(n) function and input n(line 13)
break;
case 'I':
sum=totalSum(n); // call totalSum(n) function and input n(line 13)
break;
default:
System.out.println("Your choice is wrong.");
return;
/* return :if had value will return the value to function and transfer control to who's call
* return :if no value, just transfer control to JVM, break the program.
*/
}
System.out.println("The Total Sum is "+sum);
keyin.close();
}
public static int odd(int U) {
int i,total=0;
for(i=1;i<=U;i++)
if(i%2==1)
total=total+i;
return total;
}
public static int even(int U) {
int i,total=0;
for(i=1;i<=U;i++)
if(i%2==0)
total=total+i;
return total;
}
public static int totalSum(int U) {
return odd(U)+even(U);
}
}