Padd Solutions

Converted by Falcon Hive

Showing posts with label AP Computer Science. Show all posts
Showing posts with label AP Computer Science. Show all posts
public class variousArrays
{
    public static void main (String[] args)
    {
        System.out.println ("*****CLASS SCHEDULE*****");
        
        String[] classes = {"Pham", "Wason", "Henninger", "Cardoza", "also Cardoza", "Bartolotti"};
        
        for (int i = 0; i < (classes.length); i++)
        {
            System.out.println ("Period " + i + ": " + classes[i]);
        }
        
        
        System.out.println ();
        System.out.println ();
        
        System.out.println ("*****MOVIES*****");
        
        String[] titles = {"Dr. Horrible's Sing-Along Blog", "Memento", "Serenity"};
        String[] directors = {"Joss Whedon", "Christopher Nolan", "Joss Whedon again"};
        String[] stars = {"Neil Patrick Harris", "Guy Pearce", "Nathan Fillion"};
        
        for (int i = 0; i < titles.length; i++)
        {
            System.out.println ((i + 1) + ". " + titles[i]);
            System.out.println ("Directed by: " + directors[i]);
            System.out.println ("Starring: " + stars[i]);
            System.out.println ();
        }
        
        
        System.out.println ();
        System.out.println ();
        
        System.out.println ("*****LOTTERY*****");
        int a = ((int) (Math.random () * 9) + 1);
        int b = ((int) (Math.random () * 9) + 1);
        int c = ((int) (Math.random () * 9) + 1);
        int d = ((int) (Math.random () * 9) + 1);
        int e = ((int) (Math.random () * 9) + 1);
        int f = ((int) (Math.random () * 9) + 1);
        
        int[] lottery = {a, b, c, d, e, f};
        
        System.out.print ("The winning numbers are: ");
        for (int i = 0; i < lottery.length; i++)
        {
            System.out.print (lottery[i] + " ");
        }
    }
}
import java.util.Scanner;

public class PrimeChecker
{
    public static void main (String[] args)
    {
        Scanner scan = new Scanner (System.in);

        // Create an array of prime numbers between 0 and 50
        // 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47

        int[] arrayPrime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};
       
        System.out.println ("**********************");
        System.out.println ("* PRIME CHECKER 3000 *");
        System.out.println ("**********************");
        System.out.println ();
        System.out.print ("Please enter a number between 1 and 50: ");
        int number = scan.nextInt ();
       
        boolean isPrime = false;
       
        // check to see if the number entered is prime
        for (int i = 0; i< arrayPrime.length; i++)
        {
            if (number == arrayPrime[i])
                isPrime = true;
        }

        if (isPrime)
            System.out.println ("Yes, " + number + " is a prime number.");
        else
            System.out.println ("No, " + number + " is not a prime number.");
    }
}
public class Looping
{
    public static void main (String[] args)
    {
        System.out.println ("Here is my loop!");
       
        for (int i = 10; i >= 0; i--)
        {
            System.out.println (i);
        }
    }
}
public class Arrays
{
    public static void main (String[] args)
    {
       int[] arrayOne = new int[6];
       //6 empty spots
       int[] arrayTwo = {5, 10, 15, 20, 25, 30};
      
       //System.out.println (arrayTwo[3]);
       //arrayTwo[3] = 18;
      
       //System.out.println (arrayTwo[3]);
      
      
       //arrayOne[4] = 9;
       //arrayOne[5] = "Fish" wont work bc it only holds int, as shown at top
      
       //System.out.println ();
       //System.out.println ();
       // starting new stuffs
      
       //for (int i = 0; i <= 6; i++)
       //{
       //    System.out.println (arrayTwo[i]);
       //}
       // //out of bounds
      
       //if (args[0] = "UUDDLRLRBAS")
       //lives += 1000000000;
      
       //shelley was also here
       //I know. I'm EVERYWHERE! :D
       //EVERYWHERE!
      
       double[] arrayThree = new double[4];
      
       String[] arrayFour = {"Fudge", "Cookies", "Cake"};
      
       System.out.println ("Good Morning, " +args[0]);
    }
}

1

The behavior of an object is defined by the object's

a. instance data
b. constructor
c. visibility modifiers
d. methods
e. all of the above


Your Answer: D       Correct Answer: D

Explanation: The methods dictate how the object reacts when it is passed messages. Each message is implemented as a method, and the method is the code that executes when the message is passed. The constructor is one of these methods but all of the methods combine dictate the behavior. The visibility modifiers do impact the object's performance indirectly.


2

The relationship between a class and an object is best described as

a. classes are instances of objects
b. objects are instances of classes
c. objects and classes are the same thing
d. classes are programs while objects are variables
e. objects are the instance data of classes


Your Answer: D       Correct Answer: B

Explanation: Classes are definitions of program entities that represent classes of things/entities in the world. Class definitions include instance data and methods. To use a class, it is instantiated. These instances are known as objects. So, objects are instances of classes. Program code directly interacts with objects, not classes.


3

To define a class that will represent a car, which of the following definitions is most appropriate?

a. private class car 
b. public class car
c. public class Car
d. public class CAR
e. private class Car


Your Answer: C       Correct Answer: C

Explanation: Classes should be defined to be public so that they can be accessed by other classes. And following Java naming convention, class names should start with a capital letter and be lower case except for the beginning of each new word, so Car is more appropriate than car or CAR.


4

Which of the following reserved words in Java is used to create an instance of a class?

a. class
b. public
c. public or private, either could be used
d. import
e. new


Your Answer: C       Correct Answer: E

Explanation: The reserved word "new" is used to instantiate an object, that is, to create an instance of a class. The statement new is followed by the name of the class. This calls the class' constructor. Example: Car x = new Car( ); will create a new instance of a Car and set the variable x to it.


5

In order to preserve encapsulation of an object, we would do all of the following except for which one?

a. make the instance data private
b. Define the methods in the class to access and manipulate the instance data
c. make the methods of the class public
d. Make the class final
e. All of the above preserve encapsulation


Your Answer: A       Correct Answer: D

Explanation: Encapsulation means that the class contains both the data and the methods needed to manipulate the data. In order to preserve encapsulation properly, the instance data should not be directly accessible from outside of the classes, so the instance data are made private and methods are defined to access and manipulate the instance data. Further, the methods to access and manipulate the instance data are made public so that other classes can use the object. The reserved word "final" is used to control inheritance and has nothing to do with encapsulation.


6

If a method does not have a return statement, then

a. it will produce a syntax error when compiled
b. it must be a void method
c. it can not be called from outside the class that defined the method
d. it must be defined to be a public method
e. it must be an int, double, or String method


Your Answer: B       Correct Answer: B

Explanation: All methods are implied to return something and therefore there must be a return statement. However, if the programmer wishes to write a method that does not return anything, and therefore does not need a return statement, then it must be a void method (a method whose header has "void" as its return type).


7

Consider a sequence of method invocations as follows: main calls m1, m1 calls m2, m2 calls m3 and then m2 calls m4, m3 calls m5. If m4 has just terminated, what method will resume execution?

a. m1
b. m2
c. m3
d. m5
e. main


Your Answer: C       Correct Answer: B

Explanation: Once a method terminates, control resumes with the method that called that method. In this case, m2 calls m4, so that when m4 terminates, m2 is resumed.


8

For questions 8-10, use the following class definition

import java.text.DecimalFormat;
public class Student
{
private String name;
private String major;
private double gpa;
private int hours;

public Student(String newName, String newMajor, double newGPA, int newHours)
{
name = newName;
major = newMajor;
gpa = newGPA;
hours = newHours;
}

public String toString( )
{
return name + "\n" + major + "\n" + gpa + "\n" + hours
}
}
Which of the following could be used to instantiate a new Student s1?
a. Student s1 = new Student( );
b. s1 = new Student( );
c. Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33);
d. new Student s1 = ("Jane Doe", "Computer Science", 3.333, 33);
e. new Student(s1);






Your Answer: C       Correct Answer: C

Explanation: To instantiate a class, the object is assigned the value returned by calling the constructor preceded by the reserved word new, as in new Student( ). The constructor might require parameters, and for Student, the parameters must be are two String values, a double, followed by an int.




9

Assume that another method has been defined that will compute and return the student's class rank (Freshman, Sophomore, etc). It is defined as:

public String getClassRank( )
Given that s1 is a student, which of the following would properly be used to get s1's class rank?
 a. s1 = getClassRank( );
b. s1.toString( );
c. s1.getHours( );
d. s1.getClassRank( );
e. getClassRank(s1);






Your Answer: D       Correct Answer: D

Explanation: To call a method of an object requires passing that object a message which is the same as the method name, as in object.methodname(parameters). In this situation, the object is s1, the method is getClassRank, and this method expects no parameters. Answers a and e are syntactically illegal while answer b returns information about the Student but not his/her class rank, and there is no "getHours" method so c is also syntactically illegal.




10

Another method that might be desired is one that updates the Student's number of credit hours. This method will receive a number of credit hours and add these to the Student's current hours. Which of the following methods would accomplish this?

a. public int updateHours( )
{
return hours;
}

b. public void updateHours( )
{
hours++;
}

c. public updateHours(int moreHours)
{
hours += moreHours;
}

d. public void updateHours(int moreHours)
{
hours += moreHours;
}

e. public int updateHours(int moreHours)
{
return hours + moreHours;
}






Your Answer: D       Correct Answer: D

Explanation: This method will receive the number of new hours and add this to the current hours. The method in d is the only one to do this appropriately. Answer c is syntactically invalid since it does not list a return type. The answer in e returns the new hours, but does not reset hours appropriately.




11

The Coin class, as defined in Chapter 4, consists of a constructor, and methods flip, isHeads and toString. The method isHeads returns true if the last flip was a Heads, and false if the last flip was a Tails. The toString method returns a String equal to "Heads" or "Tails" depending on the result of the last flip. Using this information, answer questions 16 – 17



What does value in the following code compute?

int num = 0;
for(int j = 0; j < 1000; j++)
{
c.flip( );
if(c.isHeads()) num++;
}
double value = (double) num / 1000;

a. the number of Heads flipped out of 1000 flips
b. the number of Heads flipped in a row out of 1000 flips
c. the percentage of heads flipped out of 1000 flips
d. the percentage of times neither Heads nor Tails were flipped out of 1000 flips
e. nothing at all






Your Answer: A       Correct Answer: C

Explanation: The code iterates 1000 times, flipping the Coin and testing to see if this flip was a 0 ("Heads") or 1 ("Tails"). The variable num counts the number of Heads and the variable value is then the percentage of Heads over 1000.




12

Use the following information to answer questions 19 - 20. The Die class from chapter 4 has two constructors defined as follows. Assume MIN_FACES is an int equal to 4.

public Die( )
{
numFaces = 6;
faceValue = 1;
}

public Die(int faces)
{
numFaces = faces;
faceValue = 1;
}
12)	The instruction Die d = new Die(10); results in
 a. The Die d having numFaces = 6 and faceValue = 1
b. The Die d having numFaces = 10 and faceValue = 1
c. The Die d having numFaces = 10 and faceValue = 10
d. The Die d having numFaces = 6 and faceValue = 10
e. A syntax error






Your Answer: B       Correct Answer: B

Explanation: Since an int parameter is passed to the constructor, the second constructor is executed, which sets numFaces = 10 (since numFaces >= MIN_FACES) and faceValue = 1.




13

The instruction Die d = new Die(10, 0); results in

a. The Die d having numFaces = 6 and faceValue = 1
b. The Die d having numFaces = 10 and faceValue = 1
c. The Die d having numFaces = 10 and faceValue = 10
d. The Die d having numFaces = 6 and faceValue = 10
e. A syntax error






Your Answer: E       Correct Answer: E

Explanation: The Die class has two constructors, one that receives no parameters and one that receives a single int parameter. The instruction above calls the Die constructor with 2 int parameters. Since no constructor matches this number of parameters exists, a syntax error occurs.




14

For questions 14 - 16, use the following class definition:

public class Swapper
{
private int x;
private String y;
public int z;

public Swapper(int a, String b, int c)
{
x = a;
y = b;
z = c;
}

public String swap( )
{
int temp = x;
x = z;
z = temp;
return y;
}

public String toString( )
{
if (x < z) return y;
else return "" + x + z;
}
}
14)	If the instruction Swapper s = new Swapper(0, "hello", 0); is executed followed by s.toString( ); what value is returned from s.toString( )?
 a. "hello"
b. "hello00"
c. "00"
d. "0"
e. 0






Your Answer: C       Correct Answer: C

Explanation: The toString method compares x and z, and if x < y it returns the String y. In this case, x == z, so the else clause is executed, and the String of "" + x + z is returned. This is the String "00".




15

Which of the following criticisms is valid about the Swapper class?

a. The instance data x is visible outside of Swapper
b. The instance data y is visible outside of Swapper
c. The instance data z is visible outside of Swapper
d. All 3 instance data are visible outside of Swapper
e. None of the methods are visible outside of Swapper






Your Answer: C       Correct Answer: C

Explanation: We would expect none of the instance data to be visible outside of the class, so they should all be declared as "private" whereas we would expect the methods that make up the interface to be visible outside of the class, so they should all be declared as "public". We see that z is declared "public" instead of "private".




16

If we have Swapper r = new Swapper (5, "no", 10); then r.swap( ); returns which of the following?

a. nothing
b. "no"
c. "no510"
d. "510"
e. "15"






Your Answer: B       Correct Answer: B

Explanation: The swap method swaps the values of x and z (thus x becomes 10 and z becomes 5) and returns the value of y, which is "no" for r.




17

Consider a method defined with the header: public void foo(int a, int b). Which of the following method calls is legal?

a. foo(0, 0.1); 
b. foo(0 / 1, 2 * 3);
c. foo(0);
d. foo( );
e. foo(1 + 2, 3 * 0.1);






Your Answer: B       Correct Answer: B

Explanation: The only legal method call is one that passes two int parameters. In the case of answer b, 0 / 1 is an int division (equal to 0) and 2 * 3 is an int multiplication. So this is legal. The answers for a and e contain two parameters, but the second of each is a double. The answers for c and d have the wrong number of parameters.




18

Consider a method defined with the header: public void doublefoo(double x). Which of the following method calls is legal?

a. doublefoo(0);
b. doublefoo(0.555);
c. doublefoo(0.1 + 0.2);
d. doublefoo(0.1, 0.2);
e. a, b, and c






Your Answer: E       Correct Answer: E

Explanation: In the case of a, the value 0 (an int) is widened to a double. In the case of c, the addition is performed yielding 0.3 and then doublefoo is called. The parameter list in d is illegal since it contains two double parameters instead of 1.




19

For the free response questions, write the requested portions of a class called BaseballPlayer. This class contains the following instance variables:

   private String name;
private String position;
private int numAtBats;
private int numSingles;
private int numDoubles;
private int numTriples;
private int numHomeRuns;
private double battingAverage;
Write the constructor, which is passed the player's name and position.  






Your Answer:
public BaseballPlayer (String playerName, playerPosition)
{
name = playerName;
position = playerPosition;
}


Correct Answer:
 public BaseballPlayer(String newName, String newPosition)
{
name = newName;
position = newPosition;
numAtBats = 0;
numSingles = 0;
numDoubles = 0;
numTriples = 0;
numHomeRuns = 0;
battingAverage = 0.0
}









20

Write a method that computes the player's batting average, which is the total number of hits (singles, double, triples, home runs) divided by the number of at bats.







Your Answer:
public void batAvg ()
{
battingAverage = ((numSingles+numDoubles+numTriples+numHomeRuns)/(numAtBats))
}


Correct Answer:
public void computeBattingAverage( )
{
battingAverage = (numSingles + numDoubles + numTriples + numHomeRuns) / (double) numAtBats;
}









21

Write a toString method that returns the player's name, position and batting average.







Your Answer:
public String toString ()
{
return (name+" "+position+" "+battingAverage);
}


Correct Answer:
public String toString( )
{
return name + "\t" + position + "\t" + battingAverage;
}















public class BoosterReturns
{
    private String name;
 
    private int updateSales;
    private int boxesSold;
    
    public BoosterReturns (String aName)
    {
        name = aName;
        boxesSold = 0;
    }
    
    public String getName ()
    {
        return name;
    }
    
    public void updateSales (int sold)
    {
        boxesSold += sold;
    }
    
    public String toString ()
    //^prints class
    {
        return (name+": "+boxesSold+ " boxes.");
    }
}
import java.util.Scanner;

public class BandBooster
{
    public static void main (String[] args)
    {
        Scanner scan = new Scanner (System.in);
       
        String Name1, Name2;
        int boxesSold = 0;
       
       

        System.out.println ("Please enter the band booster's name: ");
        Name1 = scan.nextLine();
       
        System.out.println ("Please enter another band booster's name: ");
        Name2 = scan.nextLine();
       
       
        BoosterReturns Person2 = new BoosterReturns (Name2);
        BoosterReturns Person1 = new BoosterReturns (Name1);

        System.out.println ("Enter the number of boxes sold by " +Person1.getName()+ " this week.");
        boxesSold = scan.nextInt();
        Person1.updateSales (boxesSold);
       
        System.out.println ("Enter the number of boxes sold by " +Person2.getName()+ "this week.");
        boxesSold = scan.nextInt();
        Person2.updateSales (boxesSold);
       
       
       
        System.out.println ("SECOND WEEK");
        System.out.println ("How many has " +Person1.getName()+" sold?");
        boxesSold = scan.nextInt();
        Person1.updateSales (boxesSold);
       
        System.out.println ("How many has " +Person2.getName()+" sold?");
        boxesSold = scan.nextInt();
        Person2.updateSales (boxesSold);
       
       
        System.out.println ("THIRD WEEK");
        System.out.println ("How many has " +Person1.getName()+" sold?");
        boxesSold = scan.nextInt();
        Person1.updateSales (boxesSold);
       
        System.out.println ("How many has " +Person2.getName()+" sold?");
        boxesSold = scan.nextInt();
        Person2.updateSales (boxesSold);
       
        System.out.println (Person1);
        System.out.println (Person2);
    }
}

Graphics

Graphics Lesson Intro

Graphics and Applets are not part of the AP* Exam, but they are very important in programming. The System.out window is very primitive and would never be used for any real application. Creating your own graphical interface (even if it only diplays text) is a very important step in making any program. Luckily, as with all other things in Java, somebody else has done most of the work and you can simply import their code and use it to make your own things.

We will not do any class assignments that involve graphics, but I would like to give you the opportunity to learn about them. So, I will be adding Graphics lessons that you can do at your own pace if you choose to. There may be extra credit points available for using graphics later, but other than that these are completely done on your own for the sake of gaining knowledge.

One bit of caution - You should not start doing graphics if you are not comfortable with the material we've been covering. This is much different and can really confuse you if you don't yet understand the other stuff.

The first lesson follows.


Graphics Lesson 1

Example, which draws a rectangle on the screen. This example is looked at in more detail in the lines below.

import java.applet.Applet;
import java.awt.*;

public class Shape extends Applet
{
public void paint (Graphics page)
{
page.drawRect (50, 60, 70, 80);
}
}

That class in more detail:

The first thing we need to do for a class that lets us draw is to import the two things we need.

import java.applet.Applet;
import java.awt.*;

The java.applet.Applet import is what allows us to create an applet window and java.awt.* (* means everything inside of that class) is what lets us create graphics.

Next we make our class name, which is similar to what we've already done but has a couple extra words.

public class Shapes extends Applet

In that definition, "Shapes" is the class name which is the same as all of the class names we've made and can be changed to any word you want. The last two words "extends Applet" is something that you'll just have to trust for now and will VERY MUCH be explained later on.

Next, you need to make the method. This is different from the "main" method that we've been putting into all of our programs, as you'll see.

public void paint (Graphics page)

In this method definition, you have a few things. "public" and "void" are the same as we've done before. There is no "static" or "main (String[] args)", though what we're doing here is similar. When we do a method called "main" we pass on a paramater that is (String[] args) which means we're passing an array (String[]) with the variable name "args". Here we are creating a method called "paint" and passing a parameter that is "Graphics" and calling it "page".) You could change "page" to something else, but you would also have to replace "page" with your word everywhere you see it in everything else.

After that we are ready to draw on our "page". to do this, we use a line like this:

page.drawRect (50, 60, 70, 80);

There are many drawing commands, and you must understand what they do. Let's look at the one above, which draws a square.

page.drawRect - the command to draw a rectangle
50 - the x coordinate of the top-left corner of the rectangle
60 - the y coordinate of the top-left corner of the rectangle
70 - the width of the rectangle
80 - the height of the rectangle

Important note - The x and y coordinates are not the same as they are in Math! 0,0 on a plane in Math is the bottom left. On a computer, 0,0 is the top left. Positive Y goes DOWN, not up. Other than that, they work the same.

Here are some more things you can call to draw items:

drawRect (int x, int y, int width, int height)
drawOval (int x, int y, int width, int height)
picture an oval inside of the box defined by those parameters
drawLine (int x1, int y1, int x2, int y2)
drawArc (int x, int y, int width, int height, int startAngle, int arcAngle)
that one is explained well on page 102 of your book
drawString (String str, int x, int y)
a way to put text on your page
setColor (Color color)
Set the color of whatever you're going to do next
setBackground (Color color)
Sets a background color for your applet window
fillRect (int x, int y, int width, int height)
A rectangle that is the color you set
fillOval (int x, int y, int width, int height)
fillLine (int x1, int y1, int x2, int y2)
fillArc (int x, int y, int width, int height, int startAngle, int arcAngle)
that one is explained well on page 102 of your book

Make these two classes to get a feel for how all this works.

import java.applet.Applet;
import java.awt.*;

public class Einstein extends Applet
{
public void paint (Graphics page)
{
page.drawRect (50, 50, 40, 40);
page.drawRect (60, 80, 225, 30);
page.drawOval (75, 65, 20, 20);
page.drawLine (35, 60, 100, 120);

page.drawString ("Out of clutter, find simplicity.", 110, 70);
page.drawString ("-- Albert Einstein", 130, 100);
}
}

Compile that and choose "Run Applet" from the menu where you usually run things. When the second window comes up, set it to "Run Applet in appletviewer" and click "Ok".

Another one (this one uses a couple variables):

import java.applet.Applet;
import java.awt.*;

public class Snowman extends Applet
{
public void paint (Graphics page)
{
final int MID = 150;
final int TOP = 50;

setBackground (Color.cyan);

page.setColor (Color.blue);
page.fillRect (0, 175, 300, 50); // ground

page.setColor (Color.yellow);
page.fillOval (-40, -40, 80, 80); // sun

page.setColor (Color.white);
page.fillOval (MID - 20, TOP, 40, 40); // head
page.fillOval (MID - 35, TOP + 35, 70, 50); // middle
page.fillOval (MID - 50, TOP + 80, 100, 60); // bottom

page.setColor (Color.black);
page.fillOval (MID - 10, TOP + 10, 5, 5); // eye
page.fillOval (MID + 5, TOP + 10, 5, 5); // eye

page.drawArc (MID - 10, TOP + 20, 20, 10, 190, 160); // smile

page.drawLine (MID - 25, TOP + 60, MID - 50, TOP + 40); // arm
page.drawLine (MID + 25, TOP + 60, MID + 55, TOP + 60); // arm

page.drawLine (MID - 20, TOP + 5, MID + 20, TOP + 5); // brim of hat
page.fillRect (MID - 15, TOP - 20, 30, 25); // hat
}
}
Show Code Nums
1
In the following code, what value should go in the blank so that there will be exactly six lines of output?


for (int x = 0; x < _____; x = x + 2)
System.out.println ("-");

A. 5
B. 6
C. 10
D. 11
E. 13


Correct Answer: D

Explanation:


2
What will be the largest value printed by the following code?

for (int x = 5; x > 0; x--)
for (int y = 0; y < 8; y++)
System.out.println (x*y);

A. 5
B. 8
C. 35
D. 40
E. 64


Correct Answer: C

Explanation:


3
Assume num and max are integer variables. Consider the code

While (num < max)
num++;


Which values of num and max will cause the body of the loop to be executed exactly once?
A. num = 1, max = 1;
B. num = 1, max = 2;
C. num = 2, max = 2;
D. num = 2, max = 1;
E. num = 1, max = 3;


Correct Answer: B

Explanation:


4
Which for loop is equivalent to this while loop?

int y = 5;
while (y >= 0)
{
System.out.println (y);
y--;
}

A. for (int y = 0; y < 5; y++)
System.out.println (y);
B. for (int y = 5; y > 0; y--)
System.out.println (y);
C. for (int y = 5; y >= 0; y--)
System.out.println (y);
D. for (int y = 0; y > 5; y++)
System.out.println (y);
E. for (int y = 0; y > 5; y--)
System.out.println (y);


Correct Answer: C

Explanation:


5
Which expression tests to make sure the grade is between 0 and 100 inclusive?

A. (grade <= 100) || (grade <= 0)
B. (grade <= 100) || (grade >= 0)
C. (grade < 101) || (grade > -1)
D. (grade <= 100) && (grade >= 0)
E. (grade >= 100) && (grade <= 0)


Correct Answer: D

Explanation:


1
In the following code, what value should go in the blank so that there will be exactly six lines of output?


for (int x = 0; x < _____; x = x + 2)
System.out.println ("-");

A. 5
B. 6
C. 10
D. 11
E. 13


Correct Answer: D

Explanation:


2
What will be the largest value printed by the following code?

for (int x = 5; x > 0; x--)
for (int y = 0; y < 8; y++)
System.out.println (x*y);

A. 5
B. 8
C. 35
D. 40
E. 64


Correct Answer: C

Explanation:


3
Assume num and max are integer variables. Consider the code

While (num < max)
num++;


Which values of num and max will cause the body of the loop to be executed exactly once?
A. num = 1, max = 1;
B. num = 1, max = 2;
C. num = 2, max = 2;
D. num = 2, max = 1;
E. num = 1, max = 3;



Correct Answer: B

Explanation:


4
Which for loop is equivalent to this while loop?

int y = 5;
while (y >= 0)
{
System.out.println (y);
y--;
}

A. for (int y = 0; y < 5; y++)
System.out.println (y);
B. for (int y = 5; y > 0; y--)
System.out.println (y);
C. for (int y = 5; y >= 0; y--)
System.out.println (y);
D. for (int y = 0; y > 5; y++)
System.out.println (y);
E. for (int y = 0; y > 5; y--)
System.out.println (y);


Correct Answer: C

Explanation:


5
Which expression tests to make sure the grade is between 0 and 100 inclusive?

A. (grade <= 100) || (grade <= 0)
B. (grade <= 100) || (grade >= 0)
C. (grade < 101) || (grade > -1)
D. (grade <= 100) && (grade >= 0)
E. (grade >= 100) && (grade <= 0)



Correct Answer: D

Explanation:

1

Consider the following output.

10 9 8 7 6 5 4 3 2 1

Which of the following loops will produce this output?

A. for (int i = 0; i < 10; i--)
System.out.print (i + " ");
B. for (int i = 10; i >= 0; i--)
System.out.print (i + " ");
C. for (int i = 0; i <= 10; i++)
System.out.print ((10 - i) + " ");
D. for (int i = 0; i < 10; i++)
System.out.print ((10 - i) + " ");
E. for (int i = 10; i > 0; i--)
System.out.print ((10 - i) + " ");


Correct Answer: D

Explanation:


2

A program has been written to process the scores of soccer games. Consider the following
code segment, which is intended to assign an appropriate string to outcome based
on the number of points scored by each of two teams.

if (team1Points == team2Points)
outcome = "Tie Game";
if (team1Points > team2Points)
outcome = "Team 1 Wins";
else
outcome = "Team 2 Wins";

The code doesn't work properly. For which of the following cases will the code assign the wrong string to outcome?


I. both teams score the same number of points
II. Team 1 scores more points than Team 2
III. Team 2 scores more points than Team 1
A. I only    B. II only    C. III only    D. I and III only   E. II and III only

Correct Answer: A

Explanation:


3

Consider the following code segment.

for (int i = 1; i < 5; i++)
for (int k = i; k > 2; k--)
System.out.print (k + " ");

What is printed as a result of executing the code segment?

A. 3 4 3
B. 3 4 4
C. 1 2 3 4 3
D. 2 3 2 4 3 2
E. Many digits are printed due to an infinite loop


Correct Answer: A

Explanation:


4

Consider the following code segment.

for (int i = 1; i < 25; i = i + 5)
if (i % 5 == 0)
System.out.print (i + " ");


What is printed as a result of executing the code segment?

A. 5 10 15 20
B. 5 10 15 20 25
C. 5 15
D. 6 11 16 23
E. Nothing is printed

Correct Answer: E

Explanation:


5

Consider the following while loop.

int k = 8;
while (k > 0)
{
k = k - 2;
System.out.println (k);
}

Which of the following for loops produces the same output as the while loop?

A. for (int k = 8; k >= 0; k = k - 2)
System.out.println (k);
B. for (int k = 8; k > 0; k = k - 2)
System.out.println (k);
C. for (int k = 8; k > 2; k = k - 2)
System.out.println (k);
D. for (int k = 6; k >= 0; k = k - 2)
System.out.println (k);
E. for (int k = 6; k > 0; k = k - 2)
System.out.println (k);

Correct Answer: D

Explanation:

import java.util.Scanner;

public class Shelly
{
    public static void main (String[] args)
    {
        Scanner FRUCKYOUDALE = new Scanner (System.in);
       
        String name, gender;
       
        System.out.print ("Please enter your name: ");
        name = FRUCKYOUDALE.nextLine ();
        System.out.print ("Please type in your gender. ");
        gender = FRUCKYOUDALE.nextLine ();
        gender = gender.toLowerCase ();
       
        if (name.equals ("Shelly"))
        {
            System.out.println ("I dont beleive you are a " +gender);
        }
       
        else
        {
            System.out.println ("Meh, idc :P");
        }
    }
}
import java.util. Scanner;

public class DALE
{
    public static void main (String[] args)
    {
        Scanner FRUCKYOUDALE = new Scanner (System.in);
       
        String name;
       
        System.out.println ("Please type in your name. ");
        name = FRUCKYOUDALE.nextLine ();
       
        if (name.equals ("Dale") || name.equals ("Dale Cavender"))
        {
            System.out.println ("I question your gender completely.");
        }
       
        else
        {
            System.out.println ("Either way, you should check yourself again.");
        }
    }
}
import java.util.Scanner;

public class RPS
{
    public static void main (String[] args)
    {
        Scanner wtf = new Scanner (System.in);
       
        String Ready;
       
        System.out.println ("EXTREME Rock Paper Scissors!!! ARE YOU READY?! YES????");
        Ready = wtf.nextLine();

        System.out.println ();
       
        while (Ready.equals ("n") || Ready.equals ("no") || Ready.equals ("No") || Ready.equals ("N")|| Ready.equals ("NO"))
        {
            System.out.print ("You just forfeit. You lose. Play again, loser? ");
            Ready = wtf.nextLine();
          
        }
       
        while (Ready.equals ("y") || Ready.equals ("yes") || Ready.equals ("Yes") || Ready.equals ("Y") || Ready.equals ("YES"))
        {
 
       
            System.out.print ("Choose your destiny (0 = Rock, 1 = Paper, 2 = Scissors) ");
            Scanner wow = new Scanner (System.in);
            int destiny;
            destiny = wow.nextInt();
           
            int random = (int) (Math.random () * 2);
           
            System.out.println ();
           
           
                if ((destiny == 0) && (random == 0))
                {
                    System.out.print ("Player uses Shadow Clone. Computer uses harden. Nothing is going on.");
                }
               
                else if ((destiny == 0) && (random == 1))
                {
                    System.out.print ("Player fiercely throws a shuriken. Computer dodges and summons a lightning bolt. You lose.");
                }
               
                else if ((destiny == 0) && (random == 2))
                {
                    System.out.print ("Computer summons blue eyes white dragon. Player uses KAMEHAMEHA. You win.");
                }
               
                else if ((destiny == 1) && (random == 0))
                {
                    System.out.print ("Computer chooses Smart Child. Player summons Chuck Norris. Player wins by over 9000 points.");
                }
               
                else if ((destiny == 1) && (random == 1))
                {
                    System.out.print ("Player crawls into Narnia. Computer eats candy. Nothing happens.");
                }
               
                else if ((destiny == 1) && (random == 2))
                {
                    System.out.print ("Player shuffles a deck of cards. Computer coughs up a fireball. Computer wins.");
                }
               
                else if ((destiny == 2) && (random == 0))
                {
                    System.out.print ("Player uses the Undying Will. Computer uses Reborn. Computer wins by a slight margin.");
                }
               
                else if ((destiny == 2) && (random == 1))
                {
                    System.out.print ("Computer bitch slaps the player. Player returns with a roundhouse kick, knocking out the computer. Player wins.");
                }
               
                else if ((destiny == 2) && (random == 2))
                {
                    System.out.print ("Player smokes weed and offers Computer for a share. Both are now high. It's a tie.");
                }
               
                else
                {
                    System.out.print ("It's either ROCK, PAPERS, OR SCISSORS. You just lost.");
                }
           
            System.out.println ();
            System.out.println ();
            System.out.println ("Play again?");
            Ready = wtf.nextLine();

        }
       

       
       
    }
}
           
public class LotsOfStuff
{
    public static void main (String[] args)
    {
        /** ************* Practice ******************
         *  We'll do this one together.  We're going to
         *  add up all the values that i will be in the
         *  following loop.  We're also going to count
         *  the number of even numbers that i will be.
         */
        System.out.println ("Practice Section\n");
        int count = 0;
        int sum = 0;
        int evens = 0;
       
        for (int i = 2; i < 99; i++)
        {
            count++;
            sum += i;
           
            if (i% 2 == 0)
            {
                evens++;
            }
        }
       
        System.out.println ("Iterations: "+count);
        System.out.println ("Sum: "+sum);
        System.out.println ("Evens: "+evens);
       
       
       
        /** ************** Part 1 *******************
         *  Print how many times this loop runs
         */
        System.out.println ("\n\nPart 1\n");
       
        count = 0;
       
        for (int i = 0; i < 99; i += 3)
        {
            count++;
        }
       
        System.out.println ("Iterations: "+count);
       
       
        /** ************** Part 2 *******************
         *  Print the sum of all numbers that i will be
         */
        System.out.println ("\n\nPart 2\n");
       
        sum = 0;
       
        for (int i = 100; i > 50; i--)
        {
            sum += i;
        }
       
        System.out.println ("Sum: "+sum);

       
        /** ************** Part 3 *******************
         *  Print the number of even numbers that i has been
         */
        System.out.println ("\n\nPart 3\n");
       
        evens = 0;
       
        for (int i = 0; i < 50; i += 3)
        {
           if (i% 2 == 0)
           {
               evens++;
           }
        }
       
        System.out.println ("Evens: "+evens);
       
       
        /** ************** Part 4 *******************
         *  Print the number of times this loop runs
         *  also, print the sum of all numbers that i will be
         */
        System.out.println ("\n\nPart 4\n");
       
        count = 0;
        sum = 0;
       
        for (int i = 500; i <= 0; i -= 45)
        {
            count++;
            sum += i;
        }
       
        System.out.println ("Iterations: "+count);
        System.out.println ("Sum: "+sum);
       
        /** ************** Part 5 *******************
         *  Print the total number of times that loop runs
         *  Also, print the total number of even numbers
         *  And, print the total number of odd numbers
         */
        System.out.println ("\n\nPart 5\n");
       
        count = 0;
        evens = 0;
        int odds = 0;
       
        for (int i = 30; i <= 60; i += 3)
        {
            count++;
           
            if (i% 2 == 0)
            {
                evens++;
            }
           
            if (i% 2 != 0)
            {
                odds++;
            }
        }
       
        System.out.println ("Iterations: "+count);
        System.out.println ("Evens: "+evens);
        System.out.println ("Odds: "+odds);
       
       
        /** ************** Part 6 *******************
         *  Make a loop that will count to 100 by 5's
         *  like 5 10 15 20... 100
         *  Also, make it print that the sum of all of those numbers
         */
        System.out.println ("\n\nPart 6\n");
       
        int crap = 5;
        int stop = 20;
        sum = 0;
        for (int i = 1; i <= stop; i = i + 1)
        {
            System.out.print (crap* i+ " ");
            int stuff = crap * i;
            sum += stuff;
        }
       
        System.out.println ();
        System.out.print ("The sum of all numbers is: "+sum);
    }
}
import java.util.Scanner;

public class LetterCounter
{
    public static void main (String[] args)
    {
        Scanner scan = new Scanner (System.in);
        String phrase;
        int space=1;
        char check;
       
        System.out.println ("Enter a phrase, c'mon. DO IT!");
        phrase = scan.nextLine();
       
        int vowels = 1;
        int length = phrase.length() - 1;
        int others = -1;
        int punctuation = 0;
        for (int i = 0; i <= length; i++)
        {
            if (phrase.charAt (i) == 'a' || phrase.charAt (i) == 'e' || phrase.charAt (i) == 'i' || phrase.charAt (i) == 'o' || phrase.charAt (i) == 'u')
            {
                vowels++;
            }
           
            else if (phrase.charAt (i) == ' ')
            {
                space++;
            }
           
            else if (phrase.charAt (i) == '?' || phrase.charAt (i) == '!' || phrase.charAt (i) == '.' || phrase.charAt (i) == ',')
            {
                punctuation++;
            }
           
            else
            {
                others++;
            }
        }
       
        System.out.println ("Your phrase is made up of "+space+" words.");  
        System.out.println ("There are "+others+" consonants in your phrase.");       
        System.out.println ("There are "+vowels+" vowels in your phrase.");
    }
}
import java.util.Scanner;

public class Power
{
    public static void main (String[] args)
    {
        Scanner scan = new Scanner (System.in);
        int base, power, result;
       
        System.out.print ("Please enter a base number: ");
        base = scan.nextInt ();
       
        System.out.print ("Please enter a power: ");
        power = scan.nextInt ();
       
        result = base;
       
        while (power > 1)
        {
            power--;
           
            result *= base;
        }
       
        System.out.println ();
        System.out.println ("It's totally "+result+". How could you not know that?!");
    }
}
import java.util.Scanner;

public class Guess
{
    public static void mai (String[] args)
    {
        Scanner scan = new Scanner (System.in);
       
        int counter = 0;
        int guess;
        int random = (int)(Math.random () * 10 + 1);
       
        System.out.print ("Guess my number: ");
        guess = scan.nextInt ();
       
        while (guess != random)
        {
            counter++;
           
            System.out.print ("Try again? ");
            guess = scan.nextInt ();

        }
       
        System.out.println ("Congratulations! You finally guessed the number! It took you "+counter+" tries!");
    }
}
public class Bottles
{
    public static void main (String[] args)
    {
        int bottles = 99;
       
        while (bottles > -9001)
        {
            System.out.println (bottles+" bottles of beer on the wall, "+bottles+"bottles of beer.");
            bottles--;
            System.out.println ("If one of those bottles should happen to fall, "+bottles+"bottles of beer on the wall.");
        }
       
        System.out.println ();
        System.out.println ("You know what? It's OVER NEGATIVE 9000!!!!");
        System.out.println ("Now you owe beer to the wall... :)");
        System.out.println ("Yeah, the wall really needs beer...");
        System.out.println ("Okay, I'm done. TA-TA!!!");
    }
}

import java.util.Scanner;

public class Multiples
{
    public static void main (String[] args)
    {
        Scanner OHMAHGAWD = new Scanner (System.in);
        int numbah;
        int stop = 10;
        int sum = 0;
       
        System.out.println ("Go, go enter a number~");
        numbah = OHMAHGAWD.nextInt();
       
        System.out.println ();
       
        System.out.println ("You have HOW many KIDS?!");
        for (int i = 1; i <= stop; i = i + 1)
        {
            System.out.print (numbah *i + ", ");
        }
       
        System.out.print ("!?!?!?!?");
        System.out.println ();
        for (int i = 1; i <= stop; i = i + 1)
        {
            int crap = numbah * i;
            sum += crap;
        }       
       
        System.out.println ();
       
        System.out.println ("Together, you have "+sum+ " kids. Dayum. How do you pay your bills?");
    }
}
public class Text
{
    public static void main (String[] args)
    {
        String text = "This will be the text that I'm working with";
        //int.length (String text)
        //char charAt (int index)
        int letterCounter = 0;
       
        for (int i = 0; i < text.length (); i++)
        //"i" means index
        {
            if (text.charAt (i) == 'i' || text.charAt(i) == 'I')
            {
                letterCounter++;
            }
        }
       
        System.out.println (letterCounter);
    }
}