Java第三章程序控制语句

1.编写一个程序,从建盘读取字符,直到接收到句点字符为止。程序要计算空格数量,在程序的末尾显示总数?
答:

import java.io.IOException;

public class luo
	{
	
		public static void main(String[] args) throws IOException
		{  
			int sum=0;
			char ch;
			do {
			
		    ch=(char)System.in.read();
			if(ch==' ')
			{
				sum++;
			}
			
		}while(ch !='.');
			System.out.print("空格总数:"+sum);
		}
	
	}

2…写出if-else-if阶梯状语句的基本格式?
答:

 if(表达式)
    表达式;
    else if(表达式)
    表达式;
    else if(表达式)
    表达式;

**3.已知

   if(x<10)
    	if(y>100)
    	{
    	 if(!done) x=z;
    	 else y=z;
    	}
else System.out.println("error");

请问最后一个else与那个if语句相关?**
答:与if(y>100)有关。

4.写出从1000至0每次递减2的for循环语句。
答:

public class luo
	{
	
		public static void main(String[] args) 
		{  
			int sum=0;
			for(int i=1000;i>=0;i=i-2)
			{   
				sum++;	
				
			}
			System.out.println("循环"+ sum+"次");
		}
	
	}

5.下面代码有效吗?

    for(int i=0;i<10;i++)
    sum+=i;
    
    count=i;

答:无效,i在声明它的for循环外面是无效的。

6.解释break语句的作用。两种格式都要解释?
答:不带标记的break是将与它相邻的循环语句终止;带标记的break是把控制权交给标记的代码块末尾。

7.下面的代码段中,执行过break语句后会显示什么?

for(i=0;i<10;i++)
	{
	while(running)
	{   
	if(x<y) break;
	}
	System.out.println("after while");
	}
	System.out.println("After for");

答:After while。
8.下面代码段的输出结果是什么?

    for(int i=0;i<10;i++)
    {
    System.out.print(i+"  ");
    if(i%2==0)  continue;
    System.out.println();
    }

答: 0 1
2 3
4 5
6 7
8 9
9.for循环中迭代表达式不必总是以固定量来改变循环控制变量的值。相反,循环控制变量可以用任意方式来改变。利用这一概念,编写for循环来生成和显示级数:1,2,4,8,16,32…?
答:

        public class luo
		{
		
			public static void main(String[] args) 
			{  
				  for(int i=1;;i+=i)
				    {
				       System.out.print(i+" ");
				    }
			}
		
		}

10.ASll小写字母与大写字母之差为32,因此把小写字母转换为大写字母只需要减去32,利用这一点编写一个从键盘读取字符的程序。把所有小写字母转换为大写字母,并显示结果。其他字符保持不变。当用户按下句点键时,程序停止。最后,让程序显示变化字母的数量?
答:

import java.io.IOException;

public class luo
	{
	
		public static void main(String[] args) throws IOException 
		{    char ch;
		     int r;
			 do
			 {
				 ch=(char)System.in.read();
				  r=ch-32; 
				
			 }while(ch=='.');
			 System.out.println(ch+"转换为:"+(char)r);
		}
	
	}

11.什么是无限循环?
答:是一种无限进行的循环。如for(;;;)。
12.使用带有标记的break语句时,标记必须包含break语句代码块中吗?
答:对。

猜你喜欢

转载自blog.csdn.net/weixin_43437385/article/details/88064989