Programming Finals
What is in the variable str String str = ""; if( 1>=0) { str = "x"; } else } str = "y"; }
"X"
public String getNewString(String s1, String s2) { String s = s1 + s1 + s2; return s; } What is a possible return value of the above method?
"aabc"
What is the value of variable s after the following code fragment? String greeting = "Good morning!"; s = greeting.substring(1,4);
"ood"
which of the following literals is a character literal
'C'
Which of the following is a char literal?
'c'
The result of this expression (12+8)/2-20
-10
What is the value of this? n - x given: float n = 3.2f; float m = 1.1f; int x = 9;
-5.8
When saving a Java source file, save it with an extension of
.java
These characters mark the beginning of a multi-line comment.
/*
these characters mark the beginning of a documentation comment
/**
These characters mark the beginning of a single- line comment.
//
Add code that prints "You Pass" if the student has a grade of 70 or above and "You Fail" otherwise. import java.util.Scanner; public class Passing { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Please enter grade (0 to 100"); double grade = input.nextDouble(); //Write your code here.
//import Scanner class import java.util.Scanner; //Passing class public class Passing { public static void main(String[] args) { //create Scanner class object Scanner input = new Scanner(System.in); System.out.println("Please enter score (0 to 100)"); //enter score double score = input.nextDouble(); //condition for pass if (score >= 70) { System.out.println("You Pass"); } //condition for fail else { System.out.println("you Fail"); } } }
To display the output on the next line, you can use the println method or use this escape sequence in the print method.
/n
What output does this while loop generate? j = 0; while (j < 6) { System.out.print(j + ", "); j++; }
0, 1, 2, 3, 4, 5,
What output does this while loop generate? j = 0; while (j < 6) { System.out.print(j + ", "); j = j + 2; }
0, 2, 4,
If int[] x = new int[15], what would be the range of valid index values that could be used with x[]?
0-14
What would be the value of discountRate after the following statements are executed? double discountRate, purchase = 1250; char cust = 'N'; if (purchase > 1000) if (cust == 'Y') discountRate = 0.05; else discountRate = 0.04; else if (purchase > 750) if (cust == 'Y') discountRate = 0.04; else discountRate = 0.03; else discountRate = 0;
0.04
System.out.println(7/5); What is the output?
1
When a method tests an argument and returns a true or false value, it should return
A boolean value
What is the result of this expression? ( 3 + 3 > 2 + 2) && (15%4 == 0) && (5 != 3)
false
What kind of statement lets a program carry out different actions depending on a condition?
if statement
To use a class in another package you need to ________ it.
import
int number = 0; int counter = 100; while (counter >= 100 & counter <= 200) { number +=2 }
program enables infinite loop
In java, identifiers are
words or names defined by the programmer
If x has been declared an int, which of the following statements is invalid?
x = 1,000;
Which of the following is a valid Boolean expression
x == 100 && y!= 200
Which of the following is the correct boolean expression to test for: int x being a value between, but not including, 500 and 650?
x > 500 && x < 650
Assume that the following is a constructor, which appears in a class public Rectangle(double len, double w) { length = len; width = w; } (a) What is the name of the class that this constructor appears in? (b) Write a statement that creates an object form the class and passes the value 25 and 20 as arguments to the constructor
a.Rectangle b.Rectangle box = new Rectangle(25, 20);
If a is an array, which of the following expression return the number of elements in a?
a.length
If a is a string, which of the following expression return the number of characters in a?
a.length()
The following statement contains System.out.println(Happy Thanksgiving!);
compile-time error
Which of the following would be an acceptable way to declare a variable that is used to hold the score of a math exam (with fractional points)?
double DOUBLE is used to store fractional values i.e: 1.1, 1.2,0.5........
It is common practice in object-oriented programming to make all of a class's ________.
fields private
A class specifies the ________ and ________ that a particular type of object has.
fields; methods
What is the value of flag ag at the end of this code? boolean flag; flag (3 > 5) || (4.2 > 1.2) && (2012 >= 2012)
flag = (3 > 5) || (4.2 > 1.2) && (2012 >= 2012) = (False) || (4.2 > 1.2) && (2012 >= 2012) = (False) || (True) && (2012 >= 2012) = (False) || (True) && (True) = (True) && (True) = True
25/4 + 4* 10 % 3
7
Based on the following statement, primes[3] = _____. int[] primes = {2, 3, 5, 7, 11};
7
Which of the following are not valid assignment statements?
72 = Amount
Which of the following is a double numberic literal
789.789
x = 2 + (4%5) + 20/6; What is the value of x?
9
Consider the following statement String[] players = {"Alex", "Tom", "David", "Jim"}; What is the last element in the players array, and what is its index?
"Jim", 3
What output does this while loop generate? j = 6; while (j > 0) { System.out.print(j + ", "); j--; }
6, 5, 4, 3, 2, 1,
Which of the following are illegal's variable names?
6pack
E notation number of 0.00123
1.23E-3
What is the value of ans after the following code has been executed? int x = 35; int y = 20, ans = 80; if (x > y) ans = ans + y;
100
What will be the value of x after the following code is executed? int x = 10; while (x < 100) { x = x + 10; }
100
What will be the value of bonus after the following code is executed? int bonus, sales = 10000; if (sales < 5000) bonus = 200; else if (sales < 7500) bonus = 500; else if (sales < 10000) bonus = 750; else if (sales < 20000) bonus = 1000; else bonus = 1250;
1000
What would be the value of bonus after the following statements are executed? int bonus, sales = 85000; char dept = 'S'; if (sales > 100000) if (dept == 'R') bonus = 2000; else bonus = 1500; else if (sales > 75000) if (dept == 'R') bonus = 1250; else bonus = 1000; else bonus = 0;
1000
How many times will the following for loop be executed? for (int count = 10; count <= 21; count++) System.out.println("Java is great!!!");
12
Choose the answer that shows the proper E notation version of the number 0.00123
123E-3
What is the value of x after the following code has been executed? int x = 75; int y = 90; if ( x != y) x = x + y;
165
How many iterations does the following for loop perform? for (int i = 2; i <= 20; i++)System.out.println("Java is great!!!");
19
z = x/n; Assume: double x = 5; double y = 8; double z; int m = 1; int n = 2;
2.5 z=x/n x=5 n=2 z=5/2 z=2.5
What would be the value of bonus after the following statements are executed? int bonus, sales = 1250; if (sales > 1000) bonus = 100; if (sales > 750) bonus = 50; if (sales > 500) bonus = 25; else bonus = 0;
25
What will be returned from the following method? public static int getSum() { int a = 20 + 15; return a; }
35
10 / 3 - 10 % 4
4
How many times will the following while loop iterates? int x = 5; while (x<=20) { System.out.println(x); x = x + 5;
4
public double getAverage(double a, double b, double c) { double average = (a + b + c)/3; return average; } What would the method call getAverage(2.0, 3.0, 7.0) return?
4.0
What will be the value of x after the following code is executed? int x = 10; for (int y = 5; y < 20; y +=5) x += y;
40
10 + 5 * 3 - 20
5
How many times will the following do-while loop be executed? int x = 11; do { x += 20; }while (x <= 100);
5
What will the println staement in the following program segment display? int x = 5; System.out.println(x++);
5
What output does this while loop generate? j = 5; while (j < 10) { System.out.print(j + ", "); j++; }
5, 6, 7, 8, 9,
What will be printed after the following code is executed? for (int number = 5; number <= 15; number +=3) system.out.print(number + ", ");
5, 8, 11, 14
How many iterations does the following for loop execute? for (x = 1; x <= 50; x = x * 2) System.out.println(x);
6
What will the println staement in the following program segment display? int x = 5; System.out.println(++x);
6
Which of the following operator is a relational operator? && + >= ! *
>=
Which is not a valid java arithmetic operator
@
Which of the following is not true about loops?
A Loop cannot be placed inside another loop
If a loop does not contain within itself a way to terminate, it is called
An infinite loop
Is the following line of code a method header or a method call? public static void calcTotal()
method header
In the following code, st1.charAt(1), is an example of ________. char letter; String st1 = "123";letter = st1.charAt(1);
A value-returning method
What is a local variable?
A variable that is declared in the body of a method.
When an object, such as a String, is passed as an argument, it is
Actually a reference to the object that is passed
Which of the following is not part of the method header? Access specifier Method name Return type Parameter variable declaration All of the above are parts of the method header
All of the above are parts of the method header
A value-returning method must use ________ in its header.
Any valid data type
A method that gets a value from a class's field but does not change it is known as a mutator method.
False
No two methods in the same program can have a local variable with the same name.
False
a group of statements such as the contents of a class or a method are enclosed in
Braces {}
This while loop is an infinite loop. int i = 5; while (i > 10) { System.out.println(i); i++;
False
What would be the value of discountRate after the following statements are executed? double discountRate, purchase = 100; if (purchase > 1000) discountRate = 0.05; else if (purchase > 750) discountRate = 0.03; else if (purchase > 500) discountRate = 0.01;
Cannot tell from code
If method A calls Method B, and method B calls method C, when method C finishes, what happens?
Control is returned to method B
You must specify the ________ of the return value in the method header.
Data type
What is wrong with the following method call? displayMessage(String s);
Do not include the data type in the method call
A method header can contain
method modifiers, the method return type, the method name, a list of parameter declarations
Based on the following statement, what is the name of the constructor? Employee harry = new Employee("Hacker, Harry", 50000);
Employee
Class objects normally have ________ that perform useful operations on their data, but primitive variables do not.
methods
int x = 21; while (x>=0) { x = x - 7; {
It runs the loop 4 times
Which of the following high-level programming we're learning?
Java
Local variables
May have the same name as local variables in other methods Lose the values stored in them when the method, in which the variable is declared, finishes execution Are hidden from other methods. They are all of above.
String name = "mary"; System.out.println("My name is " + "name" + ", nice to meet you); What is the output?
My name is name, nice to meet you
Which one is a legal identifier in Java? || else && NameDate
NameDate
______are used to indicate the end of a Java statement
Semicolons
Only one object can be created from a class.
Only one object can be created from a class.
The lifetime of a method's local variable is
Only while the method is executing
Before entering a loop to compute a running total, the program should first
Set the accumulator where the total will be kept to an initial value, usually zero
An _______ is a special language used to write computer program
Programming language
_____is a cross between human language and a programming language
Pseudocode
Which of the following is not part of a method call?
Return type
Write a program that uses a loop to ask the user to enter a number at each loop iteration. The loop should iterate 6 times and keep a running total of the numbers entered
Scanner keyboard = new Scanner(System.in); int total = 0; for (int i = 1; i <= 6; i++) System.out.println("Enter a number"); int value = keyboard.nextInt(); { total = total + value; } System.out.println("The total is " + total); } }
Which of the following is not a part of the method header?
Semicolon
Which of the following declares a variable that will store a welcoming message
String welcome;
To print "Hello, world" on the monitor, use the following Java statement:
System.out.printIn("Hello, world");
Which of the following are valid printIn statements?
System.out.println("Hava n nice day");
What values for number could you enter to terminate the following while loop? System.out.print("Enter a number: "); int number = Keyboard.readInt(); while (number < 100 && number > 500) { System.out.print("Enter another number: "); number = Keyboard.readInt();
The boolean condition can never be true because In the given code the while condition(i.e number<100 && number>500) can never be true because number is less then 100 and greater then 500 so its false.
Which statement is true about running a Java program on a different CPU?
The code generated by the Java compiler runs on different CPUs.
What will be the result of the following code? String st1 = "Hello"; String s = st1.toUpperCase(string st1);
The last line of code will cause an error
Assuming the String variable river holds the value "Mississippi", what is the value of river.substring (1, 2)? Of river.substring(2, river.length() - 3)?
The string "i" and "ssissi".
int x = 2; int y = 5; if( x > 1) { x = x -y System.out.println("The value of x is " + x); } else { x = x + y System.out.println("The value of x is " + x); }
The value of x is -3
What will be the value of x after the following code is executed? int x = 10, y = 20; while (y < 100) { x += y; }
This is an infinite loop
What will be returned from the following method? public static int MethodA() { double a = 8.5 + 9.5; return a; }
This method always gives you a compile time error as in this method you are assigning a double literal to int , this is because double requires more memory than int.
A method that stores a value in a class's field or in some other way changed the value of a field is known as a mutator method.
True
A parameter variable's scope is the method in which the parameter is declared.
True
Each object of a class has its own set of field variables.
True
Java has nine primitives types
True
Logical errors are mistakes that cause the program to produce erroneous results.
True
The expression in a return statement can be any expression that has a value of the same data type as the return type.
True
The java virtual machine is a program that reads Java byte code instructions and executes them as they read
True
The private access specifier for an field indicates that the field can not be accessed by statements outside the class.
True
This while loop is an infinite loop. int i = 5; while (i > 0) { System.out.println(i); i++; }
True
What is the boolean value of the following expression (11< 2) || (9.5 != 6) || (-2>=4)
True
boolean flag = false; double x = 42.8; double y = 12.3; flag = (x > y)
True
boolean flag = false; double x = 42.8; double y = 12.3; flag = (x > y);
True
Key words are
Words that have a special meaning in the programming language
What is the range of the valid position numbers of characters in the string "Hello"?
[0, 4]
Match the following expressions and the data types of their results 1. int 2. double 3. boolean 4. char 5. String 6. float
__1__ 5 / 3 __3__ !(1<2) __6__ (float)2 __2__ 2.5 / 2 __5__ "5" + 3 __5__ "Hello".substring(1,2) __3__ (3>2) || (4 ==5) __5__ "Hello, " + "Tom" __3__ 5 > 3 __5__ 531 + "" __1__ Integer.parseInt("120") __4__ "Hello".charAt(0) __1__ "Hello".length() __1__ (int)3.2
Rank the following languages from the lower level to the higher level (Level 1 is the lowest level, Level 3 is the highest level)
__1__ Level 1 __3__ Level 3 __2__ Level 2 1. machine language 2. Java byte code 3. Java language
public double getHalf(double a) { double result = a/2; return result; } What is the method name, the return type of the method, the parameter variables, the local variable of the above method?
__1__ method name __2__ local variable __3__ return type __4__ parameter variable 1. getHalf 2. result 3. double 4. a
Match the following statements and their outputs.
__2__ System.out.println(11 + "22"); __3__ System.out.println("11 + 22"); __1__ System.out.println(11 + 22);
Assume String s = "Mississippi"; Match the following expressions and their results.
__2__ s.toUpperCase() __6__ s.length() __5__ s.substring(2) __7__ s.equals("river") __4__ s.substring(1, 2) __3__ s.charAt(2) __1__ s.toLowerCase() 1. "mississippi" 2. "MISSISSIPPI" 3. 's' 4. "i" 5. "ssissippi" 6. 11 7. false
In a general sense, a method is
a collection of statements that performs a specific task
When an array is created, all elements are initialized with ___.
a fixed value that depends on the element type
A runtime error is usually the result of
a logical error
Every Java application program must have
a method named main
What will be the values of ans, x, and y after the following statements are executed? int ans = 0, x = 15, y =25; if ( x >= y) { ans = x + 10; x = x- y; } else { ans = y + 10; y = y + x; }
ans = 35, x = 15, y = 40
Because Java byte code is the same on all computers, compiled Java programs
are highly portable
Based on the following statement, primes[5] = _____. int[] primes = {2, 3, 5, 7, 11};
bounds error
After the header, the body of the method appears inside a set of
braces, {}
The Java compiler translates source code into what type code?
byte code
The java complier generates
byte code
What is the output of the following code segment? j = 5; while(j > 0) { Write("{0} ", j); j--; } a. 0 b. 5 c. 5 4 3 2 1 d. 5 4 3 2 1 0
c. 5 4 3 2 1
The name of the constructor is always the same as the name of the ____.
class
a java program must have least one
class definition
In the cookie cutter method: Think of the ________ as a cookie cutter and ________ as the cookies.
class; objects
The body of a method is enclosed in
curly braces {}
This is automatically provided for a class if you do not write one yourself.
default constructor
Given the following method header, which of the method calls would be an error? public void displayValues(double x, int y)
displayValue(a,b); where a is a short and b is a long
If we want to loop body to be executed at least once, which loop structure should we choose?
do-while
This type of loop slways executes at least once.
do-while
public static void m(int num) { System.out.println(num);
does not compile
Look at the following method header. What type of value does the method return? public static double getValue(int a, float b, String c)
double
What is the name of the type that denotes floating point numbers that can have fractional parts
double
Write a Java program that asks the user for the user's annual salary (e.g $250,000). Print out the following based on the user's salary. 1. Social security tax (7% of the salary) 2. Federal tax (20% of the salary) 3. State tax (10% of the salary) 4. Tax return (30% of the total paid taxes) 5. Annual income after taxes (includes the tax return) Partial credit is given but the standards are much higher for the extra credit problems import java.util.Scanner; <pre>public class TaxCalculator { public static void main(String[] args)
double annualSalary, socialTax, federalTax, stateTax, annualIncome, taxReturn; annualIncome = annualSalary - socialTax - stateTax - federalTax + taxReturn; socialTax = annualSalary * 0.07; federalTax = annualSalary * 0.2; stateTax = annualSalary * 0.1; taxReturn = (socialTax + stateTax + federalTax) * 0.3; System.out.println("The Social scecurity tax is $" + socialTax); System.out.println("The Federal Tax is $" + federalTax); System.out.println("The State tax is $ " + stateTax); System.out.println("The tax return is $ " + taxReturn); System.out.println("The Annual income after the taxes is $" + annualIncome);
Which of the following declares a variable that will store measurement with fractional parts?
double measure;
What is the process of hiding object data and providing methods for data access called?
encapsulation
Complete the for loop below to display the following messages 10 weeks left to Thanksgiving. 8 weeks left to Thanksgiving. 6 weeks left to Thanksgiving. 4 weeks left to Thanksgiving. 2 weeks left to Thanksgiving. 0 weeks left to Thanksgiving.
for (int i = 10; i >= 0; i = i - 2) { System.out.println(i + " weeks left to Thanksgiving"); }
The ________ is ideal in situations where the exact number of iterations is known.
for loop
In the following statement, the object is ________ and the class is ________ Employee harry = new Employee("Hacker, Harry", 50000);
harry;Employee
Write a loop that asks the user to enter a number during each iteration of the loop. The loop should iterate 10 times and keep a running total of the numbers entered. The loop should display the running total.
import java.util.*; //Java class with name loop public class loop { public static void main(String[] args) { //object of Scanner class Scanner sc=new Scanner(System.in); //declaring variable to store running total int runningTotal=0; //using for loop for(int i=1;i<=10;i++) { //asking user to enter a number System.out.print("Enter a number : "); //reading a number and storing in the variable runningTotal runningTotal+=sc.nextInt(); } //display total System.out.println("Total : "+runningTotal); } }
Programming Exercise: Number of Days in a Month Write a program that asks the user to enter a month ( 1 = January, 2 = February, and so on) and then prints the number of days of the month. For February, print "28 days". For example: Pleas enter a month: 5 31 days
import java.util.Scanner; public class DaysInMonth { public static void main(String[] args) { int month; Scanner input = new Scanner(System.in); System.out.println("Please enter a month here: "); month = input.nextInt(); if (month == 1) System.out.println("31 days"); else if (month == 2) System.out.println("28 Days"); else if (month == 3) System.out.println("31 Days"); else if (month == 4) System.out.println("30 Days"); else if (month == 5) System.out.println("31 Days"); else if (month == 6) System.out.println("30 Days"); else if (month == 7) System.out.println("31 Days"); else if (month == 8) System.out.println("31 Days"); else if (month == 9) System.out.println("30 Days"); else if (month == 10) System.out.println("31 Days"); else if (month == 11) System.out.println("30 Days"); else if (month == 12) System.out.println("31 Days"); else System.out.println("The month you entered is invalid."); } }
Without using the keyword static, define the readString method. This method should not take a parameter but should use an instance variable for the Scanner. The instance variable should be declared private. This method should get a String from the user and return it to the main method. The main method should then print the String. Your output should be similar to the output shown below:
import java.util.Scanner; public class ReadStringInstanceMethod { private Scanner input; private String readString() { System.out.print("Enter string: "); String s = input.nextLine(); return s; } public static void main(String [] args) { ReadStringInstanceMethod rsi = new ReadStringInstanceMethod(); rsi.input = new Scanner(System.in); String str = rsi.readString(); System.out.println("String read from console is : " + str); } }
Programming Exercise: Restaurant Bill Write a program that computes the tax and tip on a restaurant bill. The program should ask the user to enter the charge for the meal. The tax should be 6.75 percent of the meal charge. The tip should be 15 percent of the total after adding the tax. The program should display the meal charge, tax amount, tip amount, and total amount of the bill on the screen.
import java.util.Scanner; public class RestaurantBill { public static void main(String[] args) { Scanner input = new Scanner(System.in); double mealCharge; double taxAmount; double totalTaxCost; double tipAmount; double totalBillCost; System.out.println("Enter the charge for your metal? $ "); mealCharge = input.nextDouble(); taxAmount = mealCharge * 0.0675; totalTaxCost = mealCharge + taxAmount; tipAmount = totalTaxCost * 0.15; totalBillCost = totalTaxCost + tipAmount; System.out.println("The charge of the meal is: $" + mealCharge); System.out.println("The tax amount is: $" + totalTaxCost); System.out.println("The tip amount is: $" + tipAmount); System.out.println("The total bill cost is: $" + totalBillCost); } }
Programming Exercise: String Manipulator Write a program that asks the user to enter the name of his or her favorite city using the Scanner class. Use a String variable to store the input. The program should display the following: 1. The number of characters in the city name 2. The name of the city in all uppercase letters 3. The name of city in all lowercase letters The first character in the name of the city
import java.util.Scanner; public class StringManipulator { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Please enter the name of your favorite city: "); String favoriteCity = input.nextLine(); input.close(); System.out.println("The number of characters: " + favoriteCity.length()); System.out.println("The name of the city in all uppercase letters: " + favoriteCity.toUpperCase()); System.out.println("The name of city in all lowercase letters: " + favoriteCity.toLowerCase()); System.out.println("The first character in the name of the city: " + favoriteCity.charAt(0)); } }
Write a program that has variables to hold three test scores. The program should ask the user to enter three test scores and then assign the values entered to the variables. The program should display the average of the test scores and the letter grade that is assigned for the test score average. Use the grading scheme in the following table: Test Score Average Letter Grade 90-100 A 80-89 B 70-79 C 60-69 D Below 60 F
import java.util.Scanner; public class TestScores { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double Testscore1, Testscore2, Testscore3; double averageScore; System.out.print("Please enter the first test score: "); Testscore1 = sc.nextDouble(); System.out.print("Please enter the second test score: "); Testscore2 = sc.nextDouble(); System.out.print("Please enter the second test score: "); Testscore3 = sc.nextDouble(); averageScore = (Testscore1 + Testscore2 + Testscore3) / 3; if (averageScore < 60) System.out.println("The average score is " + averageScore + ". You have a F." ); else if (averageScore < 70) System.out.println("The average score is " + averageScore + ". You have a D." ); else if (averageScore < 80) System.out.println("The average score is " + averageScore + ". You have a C." ); else if (averageScore < 90) System.out.println("The average score is " + averageScore + ". You have a B." ); else if (averageScore <= 100) System.out.println("The average score is " + averageScore + ". You have a A." ); else System.out.println("The average score is " + averageScore + ". Score is invalid." ); } }
Programming Exercise: Word Game Write a program that plays a word game with the user. The program should ask the user to enter the following: 1. His or her name 2. His or her age 3. The name of a city 4. The name of a college 5. A profession 6. A type of animal 7. A pet's name After the user has entered these items, the program should display the following story, inserting the user's input into the appropriate locations. There once was a person named NAME who lives in CITY. At the age of AGE, NAME went to college at COLLEGE. NAME graduated and went to work as a PROFESSION. Then, NAME adopted a(n) ANIMAL named PETNAME. They both lived happily ever after!
import java.util.Scanner; public class WordGame { public static void main(String[] args) { Scanner input = new Scanner(System.in); String name, age, city, college, profession, animal, petName; System.out.print("Enter a girls name: "); name = input.next(); System.out.print("What is your age? " ); age = input.next(); System.out.print("What city were you born in? "); city = input.next(); System.out.print("What college do you go to? "); college = input.next(); System.out.print("What is your profession? "); profession = input.next(); System.out.print("What is your favorite type of animal? "); animal = input.next(); System.out.print("What is the name of your pet? "); petName = input.next(); System.out.println("There once was a person named " + name + " who lives in " + city + ". At the age of " + age + ", she went to college at " + college + ". Then " + name + " graduated and went to work as a " + profession + ". Then, " + name + " adopted a " + animal + " named " + petName + ". They both lived happily ever after!"); } }
Given the classification and GPA, print all the awards a student can get. If GPA is 3.75 and above, "Excellence Award" If freshman and GPA is 3.5 and above, "Great Start Award"
import java.util.Scanner; public class GpaAward { public static void main(String[] args) { double gpa; int classification; Scanner g = new Scanner(System.in); System.out.println("Enter the GPA: "); gpa = g.nextDouble(); System.out.println("Enter the classification (1-freshman, 2-sophomore, 3-junior, 4-senior: "); classification = g.nextInt(); if(gpa >= 3.75) { System.out.println("Excellence Award"); } if(classification == 1 && gpa >= 3.5) { System.out.println("Great Start Award"); } } }
Programming Exercise: Sum of Numbers Write a program that asks the user for a positive nonzero integer value. The program should use a loop to get the sum of all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of 1, 2, 3, 4, ..., 50.
import javax.swing.JOptionPane; public class SumOfNumbers { public static void main(String[] args) { int number; String input1 = JOptionPane.showInputDialog("Please enter a positive nonzero integer"); number = Integer.parseInt(input1); int sums = 0; while(number >= 1){ sums += number; number--; } JOptionPane.showMessageDialog(null, "The Sum of all the intgers is: " + sums); } }
Assume s is a string, what is the data type of the value of the following expression? s.length()/5
int
Assume s is a string, what is the output type of the following expression? s.length() /2
int
What is the name of the type that denotes whole numbers?
int
What is the return type of the length method of the String class?
int
Which is not a legal Java identifier
int
System.out.println("2 apples "); System.out.println("5 apples "); System.out.println("8 apples"); System.out.println("11 apples"); System.out.println("14 apples"); Choose the correct initialization, test, and update expressions for the for loop below to rewrite the above code with this for loop. for ( ____________________________) { System.out.println(i + apples"); }
int i = 2; i <= 14; i = i+3 // implementation class Main { public static void main(String[] args) { for(int i = 2; i <= 14; i = i+3) { System.out.println( i + "apples" ); } }
Write a program to calculate the sum of series of numbers. 1* 99 + 2* 98 + 3* 97 + ... + 97* 3+ 98 * 2+99* 1 = ?
int total = 0; for (int i = 1; i <= 100; i++) { total = total + i*(100-i); } System.out.println("The total is " + total); } }
Write a program to calculate the sum of the squares of all positive numbers is less than or equal to 100. 1 * 1 + 2 * 2 + 3 * 3 + ... + 100 * 100 = ?
int total = 0; for (int i = 1; i <= 100; i++) { total = total + i*i; } System.out.println("The total is " + total); } }
1. Write a program to calculate the sum of all positive integers that is less than or equal to 100. 1 + 2 + 3 + ... + 100 = ?
int total = 0; for (int i = 1; i <= 100; i++) { total = total + i; } System.out.println("The total is " + total); } }
Write a program to calculate the sum of all positive even numbers is less than or equal to 100. 2 + 4 + 6 +... + 100 = ?
int total = 0; for (int i = 2; i <= 100; i=i+2) { total = total + i; } System.out.println("The total is " + total); } }
What is the type of a variable that references an array of integers?
int[]
Which statement declares a variable that references an array of integers?
int[] intData = new int[6];
Is the following line of code a method header or a method call? calcTotal();
method call
a(n)_______is a value that is written to the code of the program
literal
72, 'A', and "Hello World" are all examples of __________.
literals
The operators &&, ||, and ! are what type of operators?
logical
Programming Exercise: Software Sales A software company sells a package for $69. Quantity discounts are given according to the following table: Quantity Discount 5-14 10% 15-34 20% 35-54 30% 55 or more 40% Write a program that asks the user to enter the number of packages purchases. The program should then display the amount of the discount (if any) and the total amount of the purchase after the discount.
mport java.util.Scanner; public class SoftwareSales { public static void main(String[] args) { int s; double discount = 0.0; Scanner keyboard = new Scanner(System.in); System.out.println("Please enter the number of packages purchased: "); s = keyboard.nextInt(); if (s >= 5 && s <= 14) discount = 0.1 * (double)s * 69.0; else if (s >= 15 && s <= 34) discount = 0.2 * (double)s * 69.0; else if (s >= 35 && s <= 54) discount = 0.3 * (double)s * 69.0; else if (s >= 44) discount = 0.4 * (double)s * 69.0; double total = ( (double)s * 69.0) - discount; System.out.println("The discount is: $" + discount); System.out.println("The total is: $" + total); }
Which of the following is a valid Java identifier
name
Which of the following substring method call extract the substring "Georgia" from string name, where String name = "Georgia Gwinnett College";
name.substring(0,7);
Which of the following substring method call extract the substring "Gwinnett" from string name, where String name = "Georgia Gwinnett College";
name.substring(8, 16)
Which operator creates an object in memory?
new
Which code constructs an array of 6 integers?
new int[6]
which scanner class ethod would you use to read a double as input?
nextDouble
Which Scanner class method would you use to read a string as input?
nextLine
In the expression number++, the ++ operator is in which mode?
postfix
Flip the bits in a byte that is represented as a String. Assume that all Input are 8 bit binary digits (expressed as a String).
public String flipBits(String s) { String res = ""; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == '0') { res += '1'; } else { res += '0'; } } return res; }
Given a string and a non-negative int n, return a larger string that is n copies of the original string. formRepeatingString("Hi", 3) → "HiHiHi" formRepeatingString("Ho", 4) → "HoHoHoHo" formRepeatingString("He", 6) → "HeHeHeHeHeHe
public String formRepeatingString(String s, int n){ String result = ""; for (int i = 1; i <= n; i++) { result = result + s; } return result; }
Given a string and a non-negative int n, return a larger string that is n copies of the first 2 characters of the original string. For example, if the input string is "Hello", the input int is 3, then the method should return "HeHeHe". (Difficulty Level: 3) formRepeatingSubString("river", 2) → "riri"formRepeatingSubString("BEAR", 3) → "BEBEBE"formRepeatingSubString("Mississippi", 5) → "MiMiMiMiMi"
public String formRepeatingSubString(String s, int n){ String result = ""; String str = s.substring(0,2); for (int i = 0; i < n; i++) { result = result + str; } return result; }
Given a string and a non-negative int n, return a larger string that is n copies of the original string if n is less than or equal to 3; if n is greater than 3, the returned larger string is formed by 3 copies of the original string getMutipleCopies("Hi", 1) → "Hi" getMutipleCopies("Ho", 2) → "HoHo" getMutipleCopies("He", 3) → "HeHeHe"
public String getMutipleCopies(String s, int i){ if (i==1) return s; else if (i==2) return s+s; else return s+s+s; }
We'll say that a number is "teen" if it is in the range 13..19 inclusive. Given 3 int values, return the string "NoTeen" if none of them is teen; return the string "OneTeen" if only 1 number is a teen; return the string "TwoTeen" if two of them are teen; return the string "ThreeTeen" if all of them are teen. getTeenString(5, 8, 9) → "NoTeen" getTeenString(11, 14, 7) → "OneTeen" getTeenString(13, 15, 6) → "TwoTeen"
public String getTeenString(int a, int b, int c){ boolean isATeen = a>=13 && a <=19; boolean isBTeen = b>=13 && b <=19; boolean isCTeen = c>=13 && c <=19; if(!isATeen && !isBTeen && !isCTeen) return "NoTeen"; else if (isATeen && isBTeen && isCTeen) return "ThreeTeen"; else if ((isATeen && isBTeen && !isCTeen) || (isATeen && !isBTeen && isCTeen) || (!isATeen && isBTeen && isCTeen)) return "TwoTeen"; else return "OneTeen"; }
Given a string, return a new string that is formed by removing all the appearance of the character 'a' from the original string. For example, "cat" -> "ct" (Difficulty Level: 3) removeAs("Hello") → "Hello" removeAs("access") → "ccess" removeAs("balance") → "blnce"
public String removeAs(String s){ String result = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c != 'a') result = result + c; } return result; }
Given a string, return true if the number of times that character 'a' appears anywhere in the string is more than that of character 'b', otherwise, return false. For example, "aab" -> true, and "abb" -> false(Difficulty Level: 3) isMoreAsThanBs("abb") → false isMoreAsThanBs("aab") → true isMoreAsThanBs("ac") → true
public boolean isMoreAsThanBs(String s){ int countA = 0; int countB = 0; for (int i = 0; i < s.length(); i++){ char c = s.charAt(i); if (c == 'a') countA++; } for (int i = 0; i < s.length(); i++){ char c = s.charAt(i); if (c == 'b') countB++; } if (countA > countB) return true; else return false; }
• Example: - BankAccount Class • Operations of a bank account: - deposit money - withdraw money - get current balance
public class BankAccount { //fleid variable private double balance; //constructor public BankAccount(double initialBalance) { balance = initialBalance; } //methods public double getBalance() { return balance; } public void deposit(double amount) { balance = balance + amount; } public void withdraw(double amount) { balance = balance - amount; } } //Tester public class BankAcountTester { public static void main(String args[]) { BankAccount harrysChecking = new BankAccount(1000); harrysChecking.deposit(2000); harrysChecking.withdraw(500); System.out.println(harrysChecking.getBalance()); } }
Programming Exercise: Circle Class Write a Circle class that has the following fields: • radius: a double • PI: a final double initialized with the value 3.14159 This class should have a constructor that accepts the radius of the circle as an argument. This class should also have the following methods: • setRadius: A mutator method for the radius field • getRadius: An accessor method for the radius field • getArea: Returns the area of the circle, which is calculated as area = PI * radius * radius • getDiameter: Returns the diameter of the circle, which is calculated as diameter = radius * 2 • getCircumference: Returns the circumference of the circle, which is calculated as circumference = 2 * PI *radius You also need to implement a class named CircleTester to test the Circle class. To implement the CircleTester class, you need to provide a main method. public static void main(String[] args) In the main method, first it asks the user to input the circle's radius, then creates a Circle object, and then reporting the circle's area, diameter, and circumference.
public class Circle { //field variables private double radius; private final double PI = 3.14159; //constructor public Circle(double r) { radius = r; } //methods public void setRadius(double r) { radius = r; } public double getRadius() { return radius; } double getArea() { return PI * radius * radius; } double getDiameter() { return radius * 2; } double getCircumference() { return 2 * PI * radius; } } Tester: public class CircleTester { public static void main(String[] args) { Circle circle = new Circle(10); // creating a circle object System.out.println("Radius of the circle is " + circle.getRadius()); System.out.println("Area of the circle is " + circle.getArea()); System.out.println("Diameter of the circle is " + circle.getDiameter()); System.out.println("Circumference of the circle is " + circle.getCircumference()); circle.setRadius(15); System.out.println("Radius of the circle is " + circle.getRadius()); System.out.println("Area of the circle is " + circle.getArea()); System.out.println("Diameter of the circle is " + circle.getDiameter()); System.out.println("Circumference of the circle is " + circle.getCircumference()); } }
Programming Exercise: Employee Implement a class Employee. An employee has a name (a string) and a salary (a double). Provide a constructor with two parameters public Employee(String employeeName, double currentSalary) and methods public string getName() public double getSalary() public void raiseSalary(double byPercent) These methods return the name and salary, and raise the employee's salary by a certain percentage. Sample usage: //Construct an employee object with name "Hacker, Harry" //and salary $50000 Employee harry = new Employee("Hacker, Harry", 50000); //Harry get 10% raise harry.raiseSalary(10); Give the implementation of the class Employee. Supply an EmployeeTester class that tests all methods of the Employee class.
public class Classemployee { //field variables private String name; private double salary; //constructor public Classemployee(String employeeName, double currentSalary) { name = employeeName; salary = currentSalary; } //methods public String getName() { return name; } public double getSalary() { return salary; } public void raiseSalary(double byPercent) { salary = salary + salary * byPercent / 100.0; } } ///Tester public class ClassemployeeTester { public static void main(String[] args) { Classemployee harry = new Classemployee("Hacker, Harry", 50000); System.out.println("The name of the employee is " + harry.getName()); System.out.println("The salary of the employee is " + harry.getSalary()); harry.raiseSalary(10); System.out.println("After a raise, the salary of the employee is " + harry.getSalary()); } }
Write a program that has the following String variables: firstName, middleName, and lastName. Initialize these with your first, middle, and last names. The program should also have the following char variables: firstInitial, middleInitial, and lastInitital. Store your first, middle, and last initials in these variables. The program should display the contents of these variables on the screen
public class Names { public static void main(String[] args) { String firstName = "First", middleName = "Middle", lastName = "Last"; char firstInitial = firstName.charAt(0), middleInitial = middleName.charAt(0), lastInitital = lastName.charAt(0); System.out.println(firstName); System.out.println(middleName); System.out.println(lastName); System.out.println(firstInitial); System.out.println(middleInitial); System.out.println(lastInitital); } }
Write a program that calculates the amount a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day and continues to double each day. The program should ask user to enter the number of days worked and use input validation: do not accept a number less than 1 for the number of days worked. The program should display a table showing the salary for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies. For example, Please enter the number of days worked: 7 Your salary over this period of time: day 1: 0 dollars 1 cents day 2: 0 dollars 2 cents day 3: 0 dollars 4 cents day 4: 0 dollars 8 cents day 5: 0 dollars 16 cents day 6: 0 dollars 32 cents day 7: 0 dollars 64 cents Total: 1 dollars 27 cents
public class PenniesforPay { public static void main(String[] args) { int numberOfDays; double salary = 0.01; double totalSalary = 0.01; int day = 1; Scanner keyboard = new Scanner(System.in); NumberFormat dt = DecimalFormat.getInstance(); dt.setMaximumFractionDigits(2); System.out.print("Please enter the number of days you worked: "); numberOfDays = keyboard.nextInt(); while (numberOfDays < 1){ System.out.print("This is invliad. Please enter the number of days you worked:"); numberOfDays = keyboard.nextInt(); } System.out.println("Day " + " Your Salary " + "Your Total Salary"); while (numberOfDays > 0){ System.out.println(day + " $" + salary + " $" + dt.format(totalSalary)); salary *= 2; totalSalary += salary; day++; numberOfDays--; } } }
Rectangle - width : double - length : double + setWidth(w : double) : void + setLength(len : double): void + getWidth() : double + getLength() : double + getArea() : double
public class Rectangle { //field variables private double length; private double width; public Rectangle(double len, double w) { length = len; width = w; } //Mutator //Methods // store a value in the length field. public void setLength(double len /*parameter variable. Declared in the method header*/) { if (len < 100) length = len; } //Mutator // setWidth: store a value in the width field. public void setWidth(double w) { width = w; } //getLength: return the value in the length field public double getLength() { return length; } //Accessor public double getWidth() { return width; } public double getArea() { double area; //local variable area = width * length; return area; } }
Rectangle Tester
public class RectangleTester { public static void main(String[] args) { /*Rectangle box = new Rectangle(); box.setLength(10); box.setWidth(20); System.out.println("The box's length is " + box.getLength()); System.out.println("The box's width is " + box.getWidth()); System.out.println("The box's area is " + box.getArea());*/ Rectangle kitchen = new Rectangle(10, 14); Rectangle bedroom = new Rectangle(15, 12); Rectangle den = new Rectangle(20, 30); double totalArea = kitchen.getArea() + bedroom.getArea() + den.getArea(); System.out.println("The total area is " + totalArea); kitchen.setLength(10*2); kitchen.setWidth(14*2); bedroom.setLength(15*2); bedroom.setWidth(12*2); den.setLength(20*2); den.setWidth(30*2); totalArea = kitchen.getArea() + bedroom.getArea() + den.getArea(); System.out.println("Now, The total area is " + totalArea); kitchen.setLength(10*3); kitchen.setWidth(14*3); bedroom.setLength(15*3); bedroom.setWidth(12*3); den.setLength(20*3); den.setWidth(30*3); totalArea = kitchen.getArea() + bedroom.getArea() + den.getArea(); System.out.println("Next. This total area is " + totalArea); } }
Write a recursive method String reverse(String s) that returns the reverse of s. For example, if s is "Hello world" then the method would return "dlrow olleH".
public class ReverseStringRecursive { public static String reverse(String s) { if(s.isEmpty()) { return ""; } else { return reverse(s.substring(1)) + s.charAt(0); } } public static void main(String[] args) { System.out.println(reverse("Hello world")); } }
• A method executes when it is called. • The main method is automatically called when a program starts, but other methods are executed by method call statements. displayMessage(); • Notice that the method modifiers and the return type are not written in the method call statement. Those are only written in the method header.
public class SimpleMethod { public static void main(String[] args) { System.out.println("Hello from the main method."); displayMessage(); System.out.println("Back in the main method."); } public static void displayMessage() { System.out.println("Hello from the displayMessage method.");
. Programming Exercise: Square Write a Square class that has the following field: • sideLength: a double This class should have a constructor that accepts the side length of a square as an argument. Here is the constructor header: public Square(double initialLength) This class should also have the following methods: • setSideLength: A mutator method for the sideLength field. Here is the method header: public void setSideLength(double length) • getSideLength: An accessor method for the sideLength field. Here is the method header: public double getSideLength() • getArea: Returns the area of the square, which is calculated as area = sideLength * sideLength Here is the method header: public double getArea() • grow: Double the value of the sideLength field. Here is the method header: public void grow() You also need to implement a class named SquareTester to test the Square class. To implement the SquareTester class, you need to provide a main method. public static void main(String[] args) In the main method, first the program creates a square with side length 10. Next, it reports the area of the square. Then, call the grow method. After that, call the getArea method again to get the new area of the square.
public class Square { // field private double sideLength; // constructor public Square(double initialLength) { sideLength = initialLength; } // methods public void setSideLength(double length) { //void is a mutator method sideLength = length; } public double getSideLength() { return sideLength; } public double getArea() { return sideLength * sideLength; } public void grow() { sideLength = 2 * sideLength; } } Tester: public class SquareTester { public static void main(String[] args) { Square mySqaure = new Square(10); System.out.println("The side length of the sqaure is " + mySqaure.getSideLength()); System.out.println("The area of the sqaure is " + mySqaure.getArea()); mySqaure.grow(); System.out.println("The side length of the sqaure is " + mySqaure.getSideLength()); System.out.println("The area of the sqaure is " + mySqaure.getArea()); }
Write a program to calculate the sum of all positive numbers between 100 and 200
public class SumOfIntegers { public static void main(String[] args) { int sum = 0; for(int i = 100; i <= 200; i++) { sum = sum + i; } System.out.println("The sum of all positive numbers between 100 and 200 is " + sum); } }
Write a complete method that accepts two sides of a rectangle in inches and returns the area of the rectangle in inches. (side may include a partial inch like 1.5). getArea(1.0, 2.0) → 2.0 getArea(1.5, 3.0) → 4.5 getArea(10, 8.6) → 86.0
public double getArea(double width, double length){ double area = width * length; return area; }
Write a complete method that accepts two sides of a rectangle in Inches and returns the area of the rectangle in Inches.
public double getArea(double width, double length){ double getArea = (width * length * 2) / 2; return getArea; {
Some products are now on sale. Given the discount rate of a product and the regular price of the product, what is its discount price? getDiscountPrice(0, 100) → 100.0 getDiscountPrice(0.2, 100) → 80.0 getDiscountPrice(0.5, 200) → 100.0
public double getDiscountPrice(double discountRate, double regularPrice){ double getDiscountPrice = discountRate * regularPrice; getDiscountPrice = regularPrice - getDiscountPrice; return getDiscountPrice; }
The fuel efficiency of tom's car is 25 miles per gallon. Given gas price and distance his car traveled in a trip. How much does he pay for the fuel cost? Assume the Gas Price is constant.
public double getFuelCost(double distance, double gasPrice){ double getFuelCost = (distance / 25 * gasPrice); return getFuelCost; } or
There is a bank account that earns 4.5 percent interest per year. Given the account balance, return the interest amount earned by the account after one year. (Difficulty Level: 1) getInterest(200) → 9.0 getInterest(1000) → 45.0 getInterest(50000) → 2250.0
public double getInterest(double balance){ return balance * 0.045; }
What is the average of the minimum and maximum value among three input arguments. 1, 2, 3 ---> 2. Min is 1, Max is 3, and Average is 2.
public double getMinMaxAverage( int a, int b, int c){ double getMinMaxAverage = (a + c) / 2.0; return getMinMaxAverage; }
What is the average of the minimum and maximum value among three input arguments? e.g. 1,2,3 -> 2 , because the min value is 1 , max value is 3, and the average of the two is 2. getMinMaxAverage(3, 6, 8) → 5.5 getMinMaxAverage(2, 7, 9) → 5.5 getMinMaxAverage(1, 2, 3) → 2.0
public double getMinMaxAverage(int a, int b, int c) { double minimum; double maximum; double average; if( a > b && a > c) maximum = a; else if (b > a && b > c) maximum = b; else maximum = c; if (a < b && a < c) minimum = a; else if (b < a && b < c) minimum = b; else minimum = c; average = (maximum + minimum) / 2; return average; }
A customer can only order two types of beverages from the BucksStar coffee shop. Namely, Americano and Mocha. A cup of Americano is $2.07 and a cup of Mocha is $3.69. But this price applies when it is not in the evening. In the evening, the price for a cup of Americano and Mocha are each reduced by a dollar. Write the following method that returns the total price of an order. getOrderPrice(true, 1, 1) → 3.76 getOrderPrice(false, 1, 1) → 5.76 getOrderPrice(true, 2, 2) → 7.52
public double getOrderPrice(boolean evening, int americano, int mocha) { if(evening == true) return (americano * (1.07) + mocha * (2.69)); else return (americano * (2.07) + mocha * (3.69)); }
Given an positive number n, return the sum of all positive integers that is less than or equal to n
public int computeSum(int n){ int sum = 0; for (int i = 0; i <= n; i++) { sum = sum + i; } return sum; }
Given an positive number n, return the sum of all positive even numbers that is less than or equal to n. (Difficulty Level: 2) computeSumOfEvenNumbers(3) → 2 computeSumOfEvenNumbers(5) → 6 computeSumOfEvenNumbers(10) → 30
public int computeSumOfEvenNumbers(int n){ int sum = 0; for (int i = 2; i <=n; i+=2) { sum += i; } return sum; }
Given an positive number n, return the sum of the squares of all positive integers that is no more than n. computeSumOfSquares(1) → 1 computeSumOfSquares(2) → 5 computeSumOfSquares(3) → 14
public int computeSumOfSquares(int n){ int sum = 0; for (int i = 1; i <= n; i++) { sum = sum + (i * i); } return sum; }
Given a string, return the number of times that the character "a" appears anywhere in the given string. (Difficulty Level: 3) countAs("Hello") → 0 countAs("access") → 1 countAs("balance") → 2
public int countAs(String s){ int count = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == 'a') count++; } return count; }
Calculate the average of values in an array. getAverageOfArrayElements([1, 2, 3, 4, 5]) → 3 getAverageOfArrayElements([-2, 3, 5, 8, 11]) → 5 getAverageOfArrayElements([20, 31, 45]) → 32
public int getAverageOfArrayElements(int[] numbers){ int total = 0; for (int i = 0; i < numbers.length; i++) { total = total + numbers[i]; } int avg = total/numbers.length; return avg; }
Get the maximum of values in an array. getMaxOfArrayElements([11, 12, 34, 14, 5]) → 34 getMaxOfArrayElements([-1, 3, 5, 8, 28]) → 28 getMaxOfArrayElements([20, 31, 45, 23]) → 45
public int getMaxOfArrayElements(int[] numbers){ int max = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (max < numbers[i]) max = numbers[i]; } return max; }
Get the minimum of values in an array. getMinOfArrayElements([15, 12, 3, 54, 25]) → 3 getMinOfArrayElements([1, 3, -5, -8, 11]) → -8 getMinOfArrayElements([20, 31, 45]) → 20
public int getMinOfArrayElements(int[] numbers){ int min = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (min > numbers[i]) min = numbers[i]; } return min; }
Get the number of odd numbers in an array. getNumOfOdd([15, 12, 3, 54, 25]) → 3 getNumOfOdd([1, 3, 5, 8, 11]) → 4 getNumOfOdd([20, 31, 45]) → 2
public int getNumOfOdd(int[] numbers){ int odd = 0; for (int i = 0; i < numbers.length; i++) { if (numbers[i]%2==1) odd++; } return odd; }
Write a method that counts the number of characters that are not X's in a string. getNumberOfNonX("ZXCZZXZZZZZZZZ") → 12 getNumberOfNonX("AFKJDFKXXXJSLKJ") → 12 getNumberOfNonX("XOXXEGREWGXX") → 7
public int getNumberOfNonX(String str) { int count = 0; for(int i = 0; i < str.length(); i++) { char c = str.charAt(i); if(c != 'X') count++; } return count; }
There is a bank account that earns 5 percent interest per year. The initial account balance is $10000. Given a target balance (for example, $20000), return the number of years that it takes for the account balance to reach the target balance. The number of years should be an integer. (Difficulty level: 2) getNumberOfYears(12000) → 4 getNumberOfYears(15000) → 9 getNumberOfYears(20000) → 15
public int getNumberOfYears(double targetBalance){ int years = 0; double balance = 10000; while (balance < targetBalance) { double interest = balance * 0.05; balance = balance + interest; years++; } return years; }
You are creating an artificially intelligent agent for a tic-tac-toe computer player, and you need to create an evaluation routine. The computer is 'O' and the human player is 'X'. Given a String of three letters representing a row of the tic-tac-toe board, compute the value of the row. The value is 1 if the row is "OOO". The value is -1 if the row is "XXX". In all other cases, the value is 0. getRowValue("OOO") → 1 getRowValue("XXX") → -1 getRowValue("XOX") → 0
public int getRowValue(String row){ if (row == "OOO") return 1; else if (row == "XXX") return -1; else return 0; }
getSumOfArrayElements([1, 2, 3, 4, 5]) → 15 getSumOfArrayElements([-1, 3, 5, 8, 11]) → 26 getSumOfArrayElements([20, 31, 45]) → 96
public int getSumOfArrayElements(int[] numbers){ int total = 0; for (int i = 0; i < numbers.length; i++) { total = total + numbers[i]; } return total; }
Return the greater of two numbers but if the two numbers are equal return -1. max(1, 1) → -1 max(12, 15) → 15 max(1, 2) → 2
public int max(int a, int b) { if (a>b) return a; else if (b > a) return b; else return -1; }
Given an integer number of 5 digit, return an array that contains each digit of the number. For example, 12345 -> {1, 2, 3, 4, 5} getDigitArray(12345) → [1, 2, 3, 4, 5] getDigitArray(25673) → [2, 5, 6, 7, 3] getDigitArray(57902) → [5, 7, 9, 0, 2]
public int[] getDigitArray(int number){ int[] digit = new int[5]; String s = number + ""; for (int i = 0; i < s.length(); i++){ char c = s.charAt(i); String cs = c + ""; int d = Integer.parseInt(cs); digit[i] = d; } return digit; }
Given an non-negative integer, return an array that contains each digit of the number. For example, 12345 -> {1, 2, 3, 4, 5}, 123->{1, 2, 3} getDigitArray2(5) → [5] getDigitArray2(23) → [2, 3] getDigitArray2(123) → [1, 2, 3]
public int[] getDigitArray2(int number){ String num = number + ""; int len = num.length(); int[] digits = new int[len]; String str = number + ""; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); String s = c + ""; int d = Integer.parseInt(s); digits[i] = d; } return digits; }
Write the header for a method named distance. The method should return a double and have two double parameter variables: rate and time.
public static double distance(double rate, double time)
write a method that counts the number of characters that are not X's in a string
public static int getNumberOfNonX(String str){ // variable to store count of non 'X' int getNumberOfNonX = 0; // for every charater in string str for(int i=0 ;i<str.length(); i++){ // if character is not 'X' if(str.charAt(i) != 'X'){ // increase its count getNumberOfNonX++; } } // return the count return getNumberOfNonX;
Write a program that uses a for loop to display the following set of numbers: 100, 99, 98, 97, ..., 0
public static void main(String[] args) { for (int i = 100; i >= 0; i--) { System.out.print(i + ","); } } }
Write a program that uses a forloop to display the following set of numbers:50, 51,52, 53, 54, ..., 100
public static void main(String[] args) { for (int i = 50; i <= 100; i++) { System.out.print(i + ","); } } }
Write a program that uses a while loop to display the following set of numbers: 0, 1, 2, 3, ..., 100
public static void main(String[] args) { int i = 0; while (i <= 100) { System.out.print(i+", "); i++; } } }
Write a program that uses a while loop to display the following set of numbers: following set of numbers: 0, 10, 20, 30, ..., 1000
public static void main(String[] args) { int i = 0; while (i <= 1000) { System.out.print(i+", "); i = i + 10; } } }
Write a program that contains a while loop which is used to display 10 rows of strings "I love Java!"
public static void main(String[] args) { int i = 10; while (i >= 1) { System.out.println("I love Java!"); i--; } } }
Write a program that contains a while loop that displays the following messages: 9 weeks left before Thanksgiving! 8 weeks left before Thanksgiving! 7 weeks left before Thanksgiving! 6 weeks left before Thanksgiving! 5 weeks left before Thanksgiving! 4 weeks left before Thanksgiving! 3 weeks left before Thanksgiving! 2 weeks left before Thanksgiving! 1 weeks left before Thanksgiving! Happy Thanksgiving!
public static void main(String[] args) { int i = 9; while (i > 0) { System.out.println(i + " weeks left to Thanksgiving"); --i; } System.out.println("Happy Thanksgiving!"); } }
Byte code instructions are
read and interpreted by the JVM. Correct
What kind of operator compares two values?
relational
Syntax is
rules that must be followed when writing a program
If s1 and s2 are two strings, which of the following expressions should we use to test whether they are equal?
s1.equals(s2)
String s1 = "Jessy"; String s2 "Steven"; 7 12 if( si.length() > s2.length() ) { System.out.println("sl is greater"); What is the result of the code?
s2 is greater Explanation: The 'else' statement is printed because the length of s2(Steven) is greater than s1(Jessy). The length of s2 is 6 and s1 is 5. For better understanding please look at the screenshot.
A computer program is
set of instructions that directs the computer to perform a variety of tasks.
Which of the following would be a valid method call for the following method? public static void showProduct(double num1, int num2) { double product; product = num1 * num2; System.out.println("The product is " + product); }
showProduct(3.3, 55);
There are rules that must be followed when writing a program
syntax
int x = 10; int y = 20; int z; if( x >=y) { z = x -y } else if( x = y) { z = x + y; }
the condition (x ==y) is incorrect
Computers can do many jobs because
they're programmable
All java lines of code end with a semi-colon
true
Assume x = 6 and y = 3. What is the boolean value of the following expression? x < y || y != x
true
Which of the following is a Boolean literal? "true" true
true
The distance a vehicle travels can be calculated as follows: Distance = Speed * Time For example, if a train travels 40 miles-per-hour for three hours, the distance traveled is 120 miles. Write a program that asks the user for the speed of a vehicle (in miles-per-hour) and the number of hours it has traveled. It should use a loop to display the distance a vehicle has traveled for each hour of a time period specified by the user. For example, if a vehicle is traveling at 40 mph for a three-hour time period, it should display a report similar to the one that follows: Hour Distance Traveled -------------------------------- 1 40 2 80 3 120
ublic class DistanceTraveled { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int time, speeding; System.out.println("Just how fast were you going?: "); speeding = keyboard.nextInt(); while(speeding<=0) { System.out.println("Please enter a valid speed: "); speeding = keyboard.nextInt(); } System.out.println("How long did you drive for?: "); time = keyboard.nextInt(); while(time<=0) { System.out.println("Please enter a valid time: "); time = keyboard.nextInt(); } System.out.println("Hour Distance"); System.out.println("---------------------------------"); for(int hours = 1; hours <=time; hours++) { System.out.println(hours+ " " + (hours * speeding)); } } }
Data hiding, which means that critical data stored inside the object is protected from code outside the object is accomplished in Java by ________.
using the private access specifier on the fields of the class
A ________ method performs a task and sends a value back to the code that called it.
value-returning
a(n)_____is a named stored location in the computer's memory
variable
A ________ method performs a task and then terminates.
void
In the following code, System.out.println(num), is an example of ________. double num = 5.4; System.out.println(num); num = 0.0;
void method