天天看点

《Head First Java》练习题两则(P20,P21)

《Head First Java》练习题两则(P20,P21)

因为题目非常简单,所以书上没有答案,网上也不容易搜到,那就自己写

练习1.排排看(P20)

题目描述很弱智,就像这样,“小朋友,下面的代码被饼干大怪兽弄乱了,快和爸爸妈妈把它拼好”。

if (x == 1) {
				System.out.print("d");
				x = x - 1;
			}
           
if (x == 2) {
				System.out.print("b c");
			}
           
public class SortTest {
	public static void main(String[]args) {
           
if (x > 2) {
				System.out.print("a");
			}
           
x = x - 1;
			System.out.print("-");
           

答案

/**
 * 《head first java》P20练习
 * @author Kykywka
 *
 */
public class SortTest {
	public static void main(String[]args) {
		int x = 3;
		while(x > 0) {
			if (x > 2) {
				System.out.print("a");
			}
			
			if (x == 2) {
				System.out.print("b c");
			}
			x = x - 1;
			System.out.print("-");
			if (x == 1) {
				System.out.print("d");
				x = x - 1;
			}
			
			
		}
	}
}

           

练习2.我是编译器(P21)

这一页的Java程序代码代表一份完整的源文件。你的任务是扮演编译器的角色,判断哪个程序可以编译过关。如果有问题,哪里需要修改?

A

/**
 * P21练习A
 * @author Kykywka
 *
 */
public class Exercise1b {
	public static void main(String[]args) {
		int x = 1;
		while(x < 10) {
			if(x > 3) {
				System.out.println("big x");
		
			}
		}//死循环,但是能编译
		
		
	}
}

           

B

//public calss Exercise1b 没了,当然得出问题
public static void main(String[]args) {//报错:Syntax error on token "void", @ expected
		int x = 5;
		while(x > 1) {
			x = x - 1;
			if(x < 3) {
				System.out.println("small x");
			}
		}
	}	
           

C

public class Exercise1b {
//	public static void main(String[]args) {//
		int x = 5;
		while(x > 1) {
			x = x - 1;
			if(x < 3) {
				System.out.println("small x");
		
			}
		}	
//	}
	
}
/*错误: 在类 Exercise1b 中找不到 main 方法, 请将 main 方法定义为:
   public static void main(String[] args)
否则 JavaFX 应用程序类必须扩展javafx.application.Application*/