I made a program that I made when I was a newcomer, now in my second year. Today is a for statement.
Conclusion I'm not good at for sentences even after many years
Please enter the first number>
10
Please enter the second number>
20
The sum from 10 to 20 is 165
I made it as follows.
Check31.java
package practice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Check31 {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the first integer");
String line;
try {
line = reader.readLine();
int num1 = Integer.parseInt(line);
System.out.println("Please enter a second integer");
line = reader.readLine();
int num2 = Integer.parseInt(line);
int answer = calc(num1,num2);
System.out.println(num1 + "From" + num2 + "The sum up to" + answer + "is");
} catch (NumberFormatException e) {
System.out.println("Please enter an integer");
} catch (IOException e) {
e.printStackTrace();
}
}
private static int calc(int num1, int num2) {
int sum = 0;
for (int i = num1; i <= num2; i++) {
sum = sum + i;
}
return sum;
}
}
By the time we got here, the sum would be 11, 21, 175, 22527. .. for sentence is not good. I want to be able to complete a for statement in one shot. ..
Recommended Posts