5.10
public class Test {
public static void main(String[] args){
//程序说明:输出100-1000之间能同时被5和6整除的整数
int count = 1;
for (int i = 100; i <= 1000; i++) {
if(i % 5 == 0 && i % 6 == 0)
System.out.print((count++ % 10 != 0) ? i + " ": i + "\n");
}
}
}
总结:
- 条件表达式
- 输出格式:最后一个数字后不带空格
5.11
public class Test {
public static void main(String[] args){
//程序说明:输出100-200之间能被5或6整除,但不能同时被5和6整除的整数
int count = 1;
for (int i = 100; i <= 200; i++) {
if((i % 5 == 0 ^ i % 6 == 0))
System.out.print((count++ % 10 != 0) ? i + " ": i + "\n");
}
}
}
总结:
- 异或的使用
5.14
public class Test {
public static void main(String[] args){
//程序说明:找最大公约数
//提示用户输入两个正整数
System.out.print("Enter the two number:");
Scanner input = new Scanner(System.in);
int n1 = input.nextInt();
int n2 = input.nextInt();
//找到并显示最大公约数
//找到更小的那个数
// int s = 0;
// if(n1 < n2)
// s = n1;
// else
// s = n2;
int s = (n1 < n2) ? n1 : n2;
while(s > 0)
{
if(n1 % s == 0 && n2 % s == 0)
break;
s--;
}
System.out.print("GCD of " + n1 + " and " + n2 + " is " + s);
}
}
总结:
- 条件表达式的使用
- break是跳出这个循环,并且是跳出与其接触最密切的一个循环
5.15
public class Test {
public static void main(String[] args){
//程序说明:打印ASCII字符
int count = 1;
for (int i = '!'; i <= '~'; i++) {
System.out.print((count++ % 10 != 0) ? (char)i + " " : (char)i + "\n");
}
}
}
总结:
- 打印字符:强制转换成char类型
- 输出格式:最后一个数字后不带空格
5.16
public class Test {
public static void main(String[] args){
//程序说明:升序输出一个数的所有因子
//提示用户输入整数
System.out.print("Enter a positive integer:");
Scanner input = new Scanner(System.in);
int a = input.nextInt();
//输出因子
int f = 2;
while(f <= a)
{
if(a % f == 0)
{
System.out.println(f);
a = a / f;
}
else
f++;
}
}
}
总结:
- 整数的因子问题的思考
5.17
public class Test {
public static void main(String[] args){
//Prompt the user to enter the number of lines
System.out.print("Enter the number of lines:");
Scanner input = new Scanner(System.in);
int lines = input.nextInt();
//The limits of lines
if(lines <= 1 || lines >= 15)
{