Classes, Types, and For Each Loops

Classes, Types, and For Each Loops

TOTAL POINTS 5
1.Question 1
Before you can effectively code in Java, you need to be able to understand what your code does. Try to solve the following problems in this quiz by hand!
Consider the following BlueJ program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Mystery {
/**
* read file of mysterious phrases
*/
public void DoSomething() {
// initialize instance variables
FileResource someFile = FileResource("phrases.txt");
for (String phrase : someFile.lines()){
System.out.println(phrase);
}
}
}
Which one of the following is the name of a method?

someFile

Mystery

phrase

DoSomething
1 point
2.Question 2
Consider the following Java class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Thing {
private int a;
public Thing(int x) {
a = x;
}
public int geta() {
return a;
}
public void print() {
int b = 4;
System.out.println(geta() + " " + b);
}
}
Which method is the constructor?

print

geta

Thing

a
1 point
3.Question 3
Consider the following class named Something that uses the edu.duke FileResource class.

1
2
3
4
5
6
7
8
9
public class Something {
public void run() {
FileResource f = new FileResource("words.txt");
for (String g : f.lines()) {
System.out.println(g);
}
}
}
Suppose the file words.txt contains the following lines:
cat dog
monkey lion
snake
spider
How many times is the for loop executed?
Hint: Be sure to review the documentation for FileResource if you do not recall what this class does or what methods it contains: http://www.dukelearntoprogram.com/course2/doc/.
1 point
4.Question 4
Consider the following code segment that uses the edu.duke FileResource class. The method .length() calculates how many characters are inside a string. For example, for the string "puppy", .length() would calculate a value of 5. We will learn more about strings later in this course.

1
2
3
4
5
6
7
FileResource f = new FileResource("words.txt");
for (String g : f.lines()) {
if (g.length() > 5) {
System.out.println(g);
}
}
Suppose the file words.txt contains the following lines:
cat
elephant
monkey
tiger
lion
Which one of the following would be the output from this code segment?
Hint: Be sure to review the documentation for FileResource if you do are not sure what this class does or what methods it contains: http://www.dukelearntoprogram.com/course2/doc/.

elephant
monkey
tiger

elephant
monkey

cat
elephant
monkey
tiger
lion

cat
tiger
lion
1 point
5.Question 5
Consider the following Java class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Thing {
private int a;
public Thing(int x) {
a = x;
}
public int geta() {
return a ;
}
public void print() {
int b = 4 ;
System.out.println(geta() + " " + b);
}
}
And consider the following code segment that uses the Thing class.

1
2
Thing f = new Thing(4);
System.out.println(f.geta());
Which one of the following is NOT a primitive type?

b

a

x

f
1 point

تعليقات