Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Solutions to Java Lab 2 
 
1. (1 point) Create a new class called UsingControlStructures. 
 
2. (2 points) Add a main method to the class, and in the main method declare and initialize 
a variable to represent a person's age. 
 
3. (2 points) In the main method, write an if-else construct to print out "You are old 
enough to drive" if the person is old enough to drive and "You are not old enough to 
drive" if the person is too young. 
 
class UsingControlStructures { 
  public static void main(String[] args) { 
    int age = 15; 
    if (age >= 18) { 
      System.out.println("You are old enough to drive."); 
    } else { 
      System.out.println("You are not old enough to drive."); 
    } 
  } 
} 
 
4. (3 points) Write a for loop that prints out all the odd numbers from 100 to 0 in 
decreasing order. 
 
for (int i = 100; i > 0; i--) { 
  if (i % 2 == 1) { 
    System.out.println(i); 
  } 
} 
 or 
 
for (int i = 99; i > 0; i -= 2) { 
  System.out.println(i); 
} 
 
5. (2 points) Do Step 4 with a while loop instead of a for loop. 
 
int i = 100; 
while(i > 0) { 
  if (i % 2 == 1) { 
    System.out.println(i); 
  } 
  i--; 
} 
 or 
 
int i = 99; 
while(i > 0) { 
    System.out.println(i); 
    i--; 
}