天天看點

《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*/