不要再if中定义变量,可以在while和for等循环语句中定义变量

实例

import java.util.Scanner;

public class CommonDivisor {

	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		 
		System.out.print("Please enter to integers, separate by space > ");
		while (scanner.hasNextInt()) {
			
			
			int a = scanner.nextInt();
			int b = scanner.nextInt();
			
			//int i = 0;
			if (a < b) {

				int i = a;
			} else {
		
				int i = b;
			}

			for ( ; i >= 1; i--) {

				if (a % i == 0 && b % i == 0) {
				
					System.out.println("The greatest Divisor of " + a + " and " + b + " is " + i);
					break;
				}
			}
			
			System.out.print("Please enter to integers, separate by space > ");

		}
		
		scanner.close();
	}
}

上面的代码会报错哦!
因为在if中定义了变量。
报错的大致内容是找不到符号i。

解决方案

import java.util.Scanner;

public class CommonDivisor {

	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		 
		System.out.print("Please enter to integers, separate by space > ");
		while (scanner.hasNextInt()) {
			
			
			int a = scanner.nextInt();
			int b = scanner.nextInt();
			
			int i = 0;
			if (a < b) {

				i = a;
			} else {
		
				i = b;
			}

			for ( ; i >= 1; i--) {

				if (a % i == 0 && b % i == 0) {
				
					System.out.println("The greatest Divisor of " + a + " and " + b + " is " + i);
					break;
				}
			}
			
			System.out.print("Please enter to integers, separate by space > ");

		}
		
		scanner.close();
	}
}

改成上述代码就可以了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Python3,while和for循环是两种常用的循环语句。 while循环是基于条件判断的循环语句。它会在满足条件时重复执行一段代码块,直到条件不再满足为止。在使用while循环时,首先需要定义一个循环条件,当这个条件为True时,代码块的语句就会被执行。执行完一次代码块后,再次检查条件是否为True,如果为True,则继续执行,直到条件不再为True时,循环停止。 例如,以下是一个使用while循环计算1到10之间整数和的示例代码: ``` sum = 0 i = 1 while i <= 10: sum += i i += 1 print("1到10之间的整数和为:", sum) ``` 在上述代码,初始值sum为0,i为1。在每次循环,sum增加i的值,i增加1。当i大于10时,循环停止,打印出计算结果。 而for循环则是基于序列(如列表、字符串、元组等)的循环语句,它会遍历序列的元素,并针对每个元素执行一段代码块。在使用for循环时,通常会使用in关键字指定一个序列,for循环会依次遍历序列的元素并执行代码块。 例如,以下是一个使用for循环打印列表元素的示例代码: ``` fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) ``` 在上述代码定义了一个列表fruits,for循环会依次将列表的元素赋值给fruit变量,并执行代码块的打印语句。执行结果会依次打印出列表的元素:"apple"、"banana"和"cherry"。 总结起来,while循环适用于在未知循环次数的情况下,根据条件判断来控制循环执行;而for循环适用于已知循环次数的情况下,遍历序列的元素进行操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值