import java.util.Scanner;
public class Test13{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int r;
System.out.println("“1. 求1—100的偶数和 2. 求1—100的奇数和:”");
r = sc.nextInt();
//while
int a = 1;
int c = 0;
int d = 0;
while(true){
if(r==1){
while(a<=100&&a>=1&&a%2==0){
a++;
c+=a;
}
System.out.println(c);
}
if(r==2){
while(a<=100&&a>=1&&a%2 !=0){
a++;
d+=a;
}
System.out.println(d);
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r;
System.out.println("“1. 求1—100的偶数和 2. 求1—100的奇数和:”");
r = sc.nextInt();
// while
int a = 1;
int c = 0;
int d = 0;
// while (true) {
if (r == 1) {
while (a <= 100 && a >= 1 ) {
if(a % 2 == 0){
c += a;
}
a++;
}
System.out.println(c);
}
if (r == 2) {
while (a <= 100 && a >= 1 ) {
if(a % 2 != 0){
d += a;
}
a++;
}
System.out.println(d);
}
// }
}
在你代码的基础上修改的,有以下几个错误:
1.最外面的while循环是多余的
2.a%2 == 0 判断应该放在循环里面
3.a++ 应该放在循环的最后面
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int sum = 0;
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
while (input == 1 || input == 2) {
int i = 0;//默认是输入的1,当然是2的话,i也会改变
if (input == 2) {
i = 1;
}
for (; i<= 100; i = i + 2) {
sum = i + sum;
}
System.out.println(sum);
sum = 0;//重置sum的值
input = scanner.nextInt();//用户重新输入
}
}
}