Java "Study Guide" Chapter 6

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Create a conditional expression that evaluates to string "negative" if userVal is less than 0, and "non-negative" otherwise. Ex: If userVal is -9, output is: -9 is negative. import java.util.Scanner; public class NegativeOrPositive { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String condStr; int userVal; userVal = scnr.nextInt(); condStr = /* Your solution goes here */; System.out.println(userVal + " is " + condStr + ".");

*(userVal < 0) ? "negative" : "non-negative";*

5) ((x > 2) || (y < 4)) && (z == 10) Given x = 4, y = 1, and z = 10, which comparisons are evaluated? A) (x > 2), (y < 4), and (z == 10) B) (x > 2) and (z == 10) C) (x > 2) and (y < 4)

*(x > 2) and (z == 10)* -(4 > 2) is true, so the OR operator evaluates to true regardless of the result of (y < 4). Thus, the first operand of the AND operation is true, and (z == 10) is evaluated to determine the final result.

userChar is a char and encodedVal is an int. What will encodedVal be for each userChar value? switch (userChar) { case 'A': encodedVal = 1; break; case 'B': encodedVal = 2; break; case 'C': case 'D': encodedVal = 4; break; case 'E': encodedVal = 5; case 'F': encodedVal = 6; break; default: encodedVal = -1; break; } 5) userChar = 'G'

*-1* - Because no explicit case matches 'G', execution proceeds to the default case, which assigns -1 to encodedVal.

What is the output from the following print statements, assuming float myFloat = 45.1342f; 3) System.out.printf("%09.2f", myFloat);

*000045.13* - The 9 indicates 9 characters are printed: 6 digits before the decimal point, the decimal point, and 2 digits after the decimal point. The 0 pads the output with 0's when the formatted value has fewer characters than the width.

userChar is a char and encodedVal is an int. What will encodedVal be for each userChar value? switch (userChar) { case 'A': encodedVal = 1; break; case 'B': encodedVal = 2; break; case 'C': case 'D': encodedVal = 4; break; case 'E': encodedVal = 5; case 'F': encodedVal = 6; break; default: encodedVal = -1; break; } 1) userChar = 'A'

*1* - The first case assigns 1 to encodedVal and then breaks out of the switch statement.

2) For string "Light", what is i's index? A) 0 B) 1 C) 2

*1* - L's index is 0, so the next character i has index 1.

Each comparison has a problem. Click on the problem. 2) Math.abs (x - y) < 1.0

*1.0* - While difference thresholds may vary per program, 1.0 is far too large for floating-point inexactness.

numItems and userVal are int types. What is the final value of numItems for each userVal? switch (userVal) { case 1: numItems = 5; break; case 3: numItems = 12; break; case 4: numItems = 99; break; default: numItems = 55; break; 1) userVal = 3;

*12* - The case with expression 3 will execute numItems = 12 and then break.

userText is "March 17, 2034". 2) What is the index of the last character in userText?

*13* - There are 14 characters, and indexing starts with 0, so the index of the last character is 13.

userText is "March 17, 2034". 1) What does userText.length() return?

*14* - Every character is counted including spaces.

userChar is a char and encodedVal is an int. What will encodedVal be for each userChar value? switch (userChar) { case 'A': encodedVal = 1; break; case 'B': encodedVal = 2; break; case 'C': case 'D': encodedVal = 4; break; case 'E': encodedVal = 5; case 'F': encodedVal = 6; break; default: encodedVal = -1; break; } 2) userChar = 'B'

*2* - The second case assigns 2 to encodedVal and then breaks out of the switch statement.

1)What is the index of the last letter in "Hey"? A) 2 B) 3

*2* - Indices start at 0, so H is 0, e is 1, and y is 2.

2) (y == 3) || (x > 2) What value of y results in short circuit evaluation, which skips evaluating the second operand? A) 2 B) 4 C) 3

*3 * - (3 == 3) is true, so the expression evaluates to true regardless of the result of (x > 2)

3) (y < 3) || (x == 1) What value of y does not result in short circuit evaluation, such that both operands are evaluated? A) 3 B) 1 C) 2

*3* -The OR operation is not short circuited because (3 < 3) is false. The second operand is evaluated to determine the result

userChar is a char and encodedVal is an int. What will encodedVal be for each userChar value? switch (userChar) { case 'A': encodedVal = 1; break; case 'B': encodedVal = 2; break; case 'C': case 'D': encodedVal = 4; break; case 'E': encodedVal = 5; case 'F': encodedVal = 6; break; default: encodedVal = -1; break; } 3) userChar = 'C'

*4* - Because the case for 'C' has no break statement, execution falls through to the next case 'D' and executes that case's statements (without comparing userChar to 'D'). That case assigns 4 to encodedVal and then breaks out of the switch

numItems and userVal are int types. What is the final value of numItems for each userVal? switch (userVal) { case 1: numItems = 5; break; case 3: numItems = 12; break; case 4: numItems = 99; break; default: numItems = 55; break; 2) userVal = 0;

*55* - No case expression is 0, so the default case executes numItems = 55.

numItems and userVal are int types. What is the final value of numItems for each userVal? switch (userVal) { case 1: numItems = 5; break; case 3: numItems = 12; break; case 4: numItems = 99; break; default: numItems = 55; break; 3) userVal = 2;

*55* - No case expression is 2, so the default case executes numItems = 55. The fact that 2 is between 1 and 3 is irrelevant.

userChar is a char and encodedVal is an int. What will encodedVal be for each userChar value? switch (userChar) { case 'A': encodedVal = 1; break; case 'B': encodedVal = 2; break; case 'C': case 'D': encodedVal = 4; break; case 'E': encodedVal = 5; case 'F': encodedVal = 6; break; default: encodedVal = -1; break; } 4) userChar = 'E'

*6* - The statement in case 'E' assigns 5 to encodedVal. But that case has no break statement. So after assigning 5, execution proceeds to the statements in case 'F', which assigns 6 to encodedVal, and then breaks out of the switch.

1) (x < 4) && (y > 3) What value of x results in short circuit evaluation, which skips evaluating the second operand? A) 6 B) 2 C) 3

*6* - (6 < 4) is false, so the expression evaluates to false regardless of the result of (y > 3).

Complete the comparison for floating-point numbers. 2) Determine if double variables x and y are equal. Threshold is 0.0001. Math.abs(x - y) [BLANK]

*< 0.0001* -If difference is less than 0.0001, values are close enough.

Each comparison has a problem. Click on the problem. 1) Math.abs (x - y)== 0.0001

*==* - Comparison should be <, not ==. If difference is less than 0.0001, the values are deemed "close enough.

1) Write an expression that evaluates to true if myName is greater than yourName. if (myName.compareTo(yourName) BLANK 0) { .... }

*>* - compareTo returns a positive number if myName is greater than yourName

Convert each if-else statement to a single assignment statement using a conditional expression, using parentheses around the condition. Enter "Not possible" if appropriate. .. 2) if (x < 20) { y = x; } else { y = 20; } y = (x < 20) [BLANK]

*? x : 20;* - x is evaluated and assigned to y when (x < 20) is true.20is evaluated and assigned to y when (x < 20) is false

Refer to the body temperature code provided in the previous figure. 2) What is output if the user enters 97.0? A) Exactly normal B) Above normal C) Below normal

*Below normal* - The equals branch won't execute because the difference is not less than 0.0001, and the second branch won't either, leaving the third branch to execute.

3) Given: double x x == 32.0 is OK. A) True B) False

*False* -x and 32.0 are floating-point numbers, which should not use ==.

Convert each if-else statement to a single assignment statement using a conditional expression, using parentheses around the condition. Enter "Not possible" if appropriate. .. 5) if (x < 0) { y = -x; } else { z = x; } [BLANK]

*Not possible* - The if branch assigns y, while the else branch assigns z, so this cannot be converted to a conditional expression.

6.7 Short circuit evaluation

*Study*

6.8 Switch statements

*Study*

6.9 Conditional expressions

*Study*

To what does each expression evaluate? Assume str1 is "Apples" and str2 is "apples". 3) !str2.equals("oranges") A) True B) False

*True* - "apples" does not equal "oranges" so the equals method evaluates to false. The ! changes that to true.

To what does each expression evaluate? Assume str1 is "Apples" and str2 is "apples". 1) str1.equals("Apples") A) True B) False

*True* - Same length, same corresponding characters.

Indicate if the line of output is immediately flushed from the System.out buffer. // Poem by Henry David Thoreau System.out.print("My life has been the poem "); // A System.out.println("I would have writ"); // B System.out.print("But I could not "); // C System.out.flush(); System.out.print("both live and utter it.\n"); // D 1) Line A. A) True B) False

*True* - print() is not outputting a newline character, so the output is placed in the buffer without flushing.

Indicate if the line of output is immediately flushed from the System.out buffer. // Poem by Henry David Thoreau System.out.print("My life has been the poem "); // A System.out.println("I would have writ"); // B System.out.print("But I could not "); // C System.out.flush(); System.out.print("both live and utter it.\n"); // D 2) Line B. A) True B) False

*True* - println() outputs a newline character at the end of the output, so the output is placed in the buffer and then flushed.

Using a conditional expression, write a statement that increments numUsers if updateDirection is 1, otherwise decrements numUsers. Ex: if numUsers is 8 and updateDirection is 1, numUsers becomes 9; if updateDirection is 0, numUsers becomes 7. Hint: Start with "numUsers = ...". import java.util.Scanner; public class UpdateNumberOfUsers { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); int numUsers; int updateDirection; numUsers = scnr.nextInt(); updateDirection = scnr.nextInt(); /* Your solution goes here */ System.out.println("New value is: " + numUsers); } }

*numUsers = (updateDirection ==1)?(++numUsers):(--numUsers);*

Convert each if-else statement to a single assignment statement using a conditional expression, using parentheses around the condition. Enter "Not possible" if appropriate. .. 4) if (x < 0) { x = -x; } else { x = x; } [BLANK]

*x = (x < 0) ? -x : x;* - -x is evaluated and assigned to x when (x < 0) is true.xis evaluated and assigned to x when (x < 0) is false.

4) (x < 3) && (y < 2) && (z == 5) What values of x and y do not result in short circuit evaluation, such that all operands are evaluated? A) x = 2, y = 2 B) x = 1, y = 0 C) x = 4, y = 1 D) x = 3, y = 2

*x = 1, y = 0* - (1 < 3) is true, so the second operand is evaluated. (0 < 2) is also true, so the last operand is evaluated to determine the result.

Convert each if-else statement to a single assignment statement using a conditional expression, using parentheses around the condition. Enter "Not possible" if appropriate. .. 1) if (x > 50) { y = 50; } else { y = x; } y = ( [BLANK]) ? 50 : x;

*x > 50* - In the code provided(x > 50)is the condition evaluated to determine what value is assigned to y

Convert each if-else statement to a single assignment statement using a conditional expression, using parentheses around the condition. Enter "Not possible" if appropriate. .. 3) if (x < 100) { y = 0; } else { y = x; } [BLANK]

*y = (x < 100) ? 0 : x;* - 0is evaluated and assigned to y when (x < 100) is true.xis evaluated and assigned to y when (x < 100) is false.

*IMPORTANT* *READ*

Press: *Ctrl* *+* *F* to look for the question :) *ALSO* THE PASSWORD IS: 12345678

Write a switch statement that checks origLetter. If 'a' or 'A', print "Alpha". If 'b' or 'B', print "Beta". For any other character, print "Unknown". Use fall-through as appropriate. End with newline. import java.util.Scanner; public class ConvertToGreek { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); char origLetter; origLetter = scnr.next().charAt(0); /* Your solution goes here */ } }

String greekLeter = ""; switch (origLetter) { case 'A': case 'a': greekLeter = "Alpha"; System.out.println("Alpha"); break; case 'B': case'b': greekLeter = "Betta"; System.out.println("Beta"); break; default: greekLeter = "Unknown"; System.out.println("Unknown"); break; }

Assign secretID with firstName, a space, and lastName. Ex: If firstName is Barry and lastName is Allen, then output is: Barry Allen import java.util.Scanner; public class CombiningStrings { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String secretID; String firstName; String lastName; firstName = scnr.next(); lastName = scnr.next(); /* Your solution goes here */ System.out.println(secretID); } }

secretID = firstName; char spaceChar = ' '; secretID = secretID + spaceChar; secretID = secretID.concat(lastName);

Write a switch statement that checks nextChoice. If 0, print "Rock". If 1, print "Paper". If 2, print "Scissors". For any other value, print "Unknown". End with newline. import java.util.Scanner; public class Roshambo { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); int nextChoice; nextChoice = scnr.nextInt(); /* Your solution goes here */ } }

switch (nextChoice) { case 0: System.out.println("Rock"); break; case 1: System.out.println("Paper"); break; case 2: System.out.println("Scissors"); break; default: System.out.println("Unknown"); break; }

Given string userString is "Run!". Indicate char x's value. 2) x = userString.charAt(3); A) n B) !

*!* - 0:R, 1:u, 2:n, 3:!

Use myString below to determine the output from the print statements. Note: correct answers will be shown with quotations to denote string output and to show spacing. String myString = "Testing"; 2) printf("%8s", myString);

*" Testing"* - Strings shorter than the specified width are printed with spaces. "Testing" requires 7 characters, so 1 space is added as padding.

Use myString below to determine the output from the print statements. Note: correct answers will be shown with quotations to denote string output and to show spacing. String myString = "Testing"; 3) printf("%.4s", myString);

*"Test"* - "Testing" is longer than the specified precision and is truncated to 4 characters.

Use myString below to determine the output from the print statements. Note: correct answers will be shown with quotations to denote string output and to show spacing. String myString = "Testing"; 5) printf("%-8s123", myString);

*"Testing 123"* - "Testing" has 7 characters, so the 7 characters of "Testing" are output followed by 1 space as padding. The - flag outputs the padding after the string.

Use myString below to determine the output from the print statements. Note: correct answers will be shown with quotations to denote string output and to show spacing. String myString = "Testing"; 4) printf("%.10s", myString);

*"Testing"* - A maximum of 10 characters can be printed, but "Testing" has only 7 characters

Use myString below to determine the output from the print statements. Note: correct answers will be shown with quotations to denote string output and to show spacing. String myString = "Testing"; 1) printf("%4s", myString);

*"Testing"* - Strings longer than the specified width are printed without truncation.

Given string userString is "Run!". Indicate char x's value. 3) x = userString.charAt(4); A) (blank) B) (error)

*(error)* - The string's last index is 3. Thus, this access is an error, as index 4 doesn't exist for this string.

4) For string "Oh my", which character is at index 2? A) h B) (space) C) m

*(space)* - 0:O, 1:h, 2:(space). A space is a character.

str1 is "Main" and str2 is " Street" (note the leading space). 1) Use + to combine str1 and str2, so newStr should be "Main Street". newStr = str1 BLANK ;

*+ str2* - + appends str2 to str1 in a new string.

What is the output from the following print statements, assuming float myFloat = 45.1342f; 1) System.out.printf("%+.5f", myFloat);

*+45.13420* - The + indicates a + should output before a positive number, and .5 indicates 5 digits should follow the decimal point.

What is the output from the following print statements, assuming int myInt = -713; 2) printf("%05d", myInt)

*-0713* - The 5 indicates 5 characters printed: one character for the - sign, one character for the 0 used to pad the printed value, and 3 characters for the value 713.

userText is "March 17, 2034".Do not type quotes in answers. 2) What does userText.indexOf("April") return?

*-1* --> -1 is not a valid index so is used to indicate that the item was not found. If int x = userText.indexOf("April"), one might then type if (x != -1) { ... } to proceed only if the item was found

What is the output from the following print statements, assuming int myInt = -713; 3) printf("%+02d", myInt);

*-713* - myInt is a negative value, so a - sign is printed for all negative values. The value -713 is 4 characters, more characters than the specified width of 2, so the value is not truncated.

What is the output from the following print statements, assuming int myInt = -713; 1) printf("%+04d", myInt);

*-713* - myInt is a negative value, so the + sign is not printed. A - sign is printed for all negative values.

1) For string "Light", what is L's index? A) 0 B) 1

*0* - L is the first character. A string's first character has index 0

Use the variables below to answer the questions. String name = "Alice"; double gpa = 3.5; int age = 20; 1) What is output to the screen? System.out.printf("%d - %s", age, name); A) %d - %s B) age - name C) 20 - Alice

*20 - Alice* - The age variable is substituted for %d, and name is substituted for %s

userText is "March 17, 2034".Do not type quotes in answers. 4) What does userText.substring(userText.length() - 4, userText.length()) return?

*2034* - That common form can be used to get the last N characters (in this case, the last 4 characters). The length is 14, so the start index is 14 - 4 is 10. The end index is 14 - 1, or 13. Thus, the gotten substring is from index 10 to 13, which are the characters 2034.

2) What is the length of string "Hey"? A) 2 B) 3

*3* - The string has 3 characters, so has length of 3.

3) For string "Light", what is t's index? A) 4 B) 5

*4* - 0:L, 1:i, 2:g, 3:h, 4:t. Note that while "Light" has 5 characters, the last character's index is 4, not 5 (because the first index is 0, not 1).

userText is "March 17, 2034". 3) What character does userText.charAt(userText.length() - 1) return?

*4* - 14 - 1 is 13, so userText.charAt(userText.length() - 1) returns the last character.

What is the output from the following print statements, assuming float myFloat = 45.1342f; 2) System.out.printf("%.3e", myFloat);

*4.513e+01* - e is used to display float values in scientific notation, .3 specifies the digits to print following the decimal point

userText is "March 17, 2034".Do not type quotes in answers. 1) What does userText.indexOf(',') return?

*8* - ',' is the 9th character, so the index is 8

For each question userString is initially "Done". Indicate userString's value after the statement provided. Do not type quotes in your answer, so type Done rather than "Done". If appropriate, type: Error 2) userString = userString.concat('?');

*Done now* - The + operator returns a new string that appends a string to another string. A space, n, o, and w are added to the end of "Done".

For each question userString is initially "Done". Indicate userString's value after the statement provided. Do not type quotes in your answer, so type Done rather than "Done". If appropriate, type: Error 1) userString = userString.concat("!");

*Done!* - append() takes "Done" and puts "!" at the end, yielding "Done!". Internally, concat() automatically resizes the string as needed.

For each question userString is initially "Done". Indicate userString's value after the statement provided. Do not type quotes in your answer, so type Done rather than "Done". If appropriate, type: Error 4) anotherString = "yet..."; userString = userString + anotherString;

*Doneyet...* - The + operator can take any item that evaluates to a string, like a string literal, or in this case a string variable. That variable's string is "yet...", so y, e, t, period, period, and period get added to "Done".

Which strings are equal? 1) "Apple", "Apple" A) Equal B) Unequal

*Equal* - Same length, same corresponding characters.

Which strings are equal? 3) "Apple pie!!", "Apple pie!!" A) Equal B) Unequal

*Equal* - Spaces and special symbols are compared just like other characters.

For each question userString is initially "Done". Indicate userString's value after the statement provided. Do not type quotes in your answer, so type Done rather than "Done". If appropriate, type: Error 3) userString = userString + " now";

*Error* - '?' is a character literal due to having single quotes. concat() doesn't work for a character. "?" would work and would yield: Done?

Refer to the body temperature code provided in the previous figure. 1) What is output if the user enters 98.6? A) Exactly normal B) Above normal C) Below normal

*Exactly normal* - 98.6 - 98.6 will be less than 0.0001, despite any rounding.

Refer to the body temperature code provided in the previous figure. 3) What is output if the user enters 98.6000001? A) Exactly normal B) Above normal C) Below normal

*Exactly normal* - 98.6000001 - 98.6 is 0.0000001, which is less than 0.0001. The comparison for "close enough" isn't a perfect approach. If the programmer really wants to detect such small differences, the programmer would use a smaller epsilon, like 0.000000001

2) If a floating-point variable is assigned with 0.2, and prints as 0.2, the value must have been represented exactly. A) True B) False

*False* - Although the value is printed as 0.2, 0.2 is not exactly represented when using a floating-point variable. When using type double, the nearest floating-point value is 0.200000000000000011102230246251565404236316680908203125. Rounding occurs when variables are printed due to the limited number of printed digits.

1) Floating-point values are always stored with some inaccuracy. A) True B) False

*False* - Sometimes a floating-point number can be represented exactly in the finite number of bits, like 0.0, 2.0, or 0.25. Thus, sometimes == will work, but other times will fail, so still should not be used.

To what does each expression evaluate? Assume str1 is "Apples" and str2 is "apples". 2)str1.equals(str2) A) True B) False

*False* - 'A' and 'a' differ.

5) Given: double x x == 32 is OK. A) True B) False

*False* - Comparing a floating-point with an integer is very bad practice. The comparison should be with 32.0. And floating-point comparisons should not use ==.

1) Given: float x, y x == y is OK. A) True B) False

*False* - Floating-point numbers should not use == for comparison, due to inexact representation

userText is "Monday". 2) userText.charAt(userText.length()) yields 'y'. A) True B) False

*False* - Probably the most common cause of out-of-range access. Use length - 1 (because indexing starts with 0, so last index is length - 1).

To what does each expression evaluate? Assume str1 is "Apples" and str2 is "apples". 4) A good way to compare strings is: str1 == str2. A) True B) False

*False* - That actually compares the strings' addresses, rather than the strings' contents. That's a common error.

userText is "Monday". 1) userText.charAt(7) = '!' may write to another variable's location and cause bizarre program behavior. A) True B) False

*False* - The .charAt() method will generate an exception because "Monday" has only 6 characters so charAt(7) is out-of-range.

2) Given: double x, y x == y is OK. A) True B) False

*False* - Variables of type double are floating-point numbers, which should not use ==

To what value does each evaluate? userStr is "Hey #1?". 7) Character.toLowerCase(userStr.charAt(6)) yields an error because '?' is not alphabetic. A) True B) False

*False* -No error, just returns '?'.

To what value does each evaluate? userStr is "Hey #1?". 6) Character.toLowerCase(userStr.charAt(2)) yields an error because 'y' is already lower case . A) True B) False

*False* -No error, just returns 'y'.

Indicate if the line of output is immediately flushed from the System.out buffer. // Poem by Henry David Thoreau System.out.print("My life has been the poem "); // A System.out.println("I would have writ"); // B System.out.print("But I could not "); // C System.out.flush(); System.out.print("both live and utter it.\n"); // D 3) Line C. A) True B) False

*False* -print() is not outputting a newline character, so the output is placed in the buffer without flushing. When flush() is called on the next line, the output is flushed

To what value does each evaluate? userStr is "Hey #1?". 1) Character.isLetter('7') A) True B) False

*False* -'7' is not an alphabetic letter (a-z or A-Z.)

To what value does each evaluate? userStr is "Hey #1?". 4) Character.isDigit(userStr.charAt(6)) A) True B) False

*False* -That character is '?'.

userText is "March 17, 2034".Do not type quotes in answers. 3) What does userText.substring(0, 3) return?

*Mar* - The substring method returns string starting at index 0 and ending at index 2.

Write an expression that will cause the following code to print "Equal" if the value of sensorReading is "close enough" to targetValue. Otherwise, print "Not equal". Ex: If targetValue is 0.3333 and sensorReading is (1.0/3.0), output is: Equal import java.lang.Math; import java.util.Scanner; public class SensorThreshold { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); double targetValue; double sensorReading; targetValue = scnr.nextDouble(); sensorReading = scnr.nextDouble(); if (/* Your solution goes here */) { System.out.println("Equal"); } else { System.out.println("Not equal"); } } }

*Math.abs(sensorReading - targetValue) < 0.0001*

Complete the comparison for floating-point numbers. 1) Determine if double variable x is 98.6. [ BLANK] (x - 98.6) < 0.000

*Math.abs* - Math.abs() computes floating-point absolute value

6) For string "You wish!", which character is at index 9? A) h B) ! C) " D) No such character

*No such character* - That string has 9 characters, but the last character ! is at index 8. No 9th index exists in that string.

3) Is a string's length the same as a string's last index? A) Yes B) No, the length is 1 greater. C) No, the length is 1 less.

*No, the length is 1 greater.* - For example, "Hey" has length 3, but last index 2.

Given string userString is "Run!". Indicate char x's value. 1) x = userString.charAt(0); A) R B) u

*R* -0 is the index of the string's first character, which is R.

6.2 String comparisons

*Study*

6.3 String access operations

*Study*

6.4 More string operations

*Study*

6.5 Output formatting

*Study*

6.6 Floating-point comparison

*Study*

Chapter 6.1 Character operations

*Study*

Write a single statement that prints outsideTemperature with 2 decimals. End with newline. Sample output with input 103.46432: 103.46 import java.util.Scanner; public class OutsideTemperatureFormatting { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); double outsideTemperature; outsideTemperature = scnr.nextDouble(); /* Your solution goes here */ } }

*System.out.printf("%.2f%n", outsideTemperature);*

Use the variables below to answer the questions. String name = "Alice"; double gpa = 3.5; int age = 20; 3) What outputs "20, 21"? A) System.out.printf("%d, %d\n", age, age + 1); B) System.out.printf("%d, %d\n", age); C) System.out.printf("%d, %d\n", age, age);

*System.out.printf("%d, %d\n", age, age + 1);* - The values of age and age + 1 replace the two %d format specifiers.

Use the variables below to answer the questions. String name = "Alice"; double gpa = 3.5; int age = 20; 2) What outputs "3.500000% 20"? A) System.out.printf("%f% %d\n", gpa, age); B) System.out.printf("%f%% %d\n", gpa, age); C) System.out.printf("%d%% %f\n", gpa, age);

*System.out.printf("%f%% %d\n", gpa, age);* - The %f is replaced with the gpa variable, %% is replaced with the "%" character, and %d is replaced with the age variable. Floating-point values are output to 6 decimal places by default

4) Given: int x, y x == y is OK. A) True B) False

*True* - Integer values are represented exactly, so == is OK to use

Indicate if the line of output is immediately flushed from the System.out buffer. // Poem by Henry David Thoreau System.out.print("My life has been the poem "); // A System.out.println("I would have writ"); // B System.out.print("But I could not "); // C System.out.flush(); System.out.print("both live and utter it.\n"); // D 4) Line D. A) True B) False

*True* - print() outputs a newline character at the end because the String literal ends with \n, so the output is placed in the buffer and then flushed.

To what value does each evaluate? userStr is "Hey #1?". 2) Character.isLetter(userStr.charAt(0)) A) True B) False

*True* -'H' is alphabetic.

To what value does each evaluate? userStr is "Hey #1?". 5) Character.toUpperCase(userStr.charAt(1)) returns 'E'. A) True B) False

*True* -'e' becomes 'E'.

To what value does each evaluate? userStr is "Hey #1?". 3) Character.isWhitespace(userStr.charAt(3)) A) True B) False

*True* -That character is a space ' ' between the y and #.

Which strings are equal? 4) "Apple", "apple" A) Equal B) Unequal

*Unequal* - 'A' and 'a' differ. Case matters.

Which strings are equal? 2) "Apple", "Apples" A) Equal B) Unequal

*Unequal* - Different lengths.

userText is "March 17, 2034".Do not type quotes in answers. 5) In the above email username example, what was the second argument passed to substring()?

*atSymbolIndex* - The indexOf() method got the index of @. If found (i.e. not -1), then that index was used to indicate the size of the substring preceding the @. So for [email protected], the @ is at index 10, which is the number of letters in AbeLincoln. Thus, substring() starts at index 0 and gets 10 characters, namely "AbeLincoln".

2) Write an expression that evaluates to true if authorName1 is less than authorName2. if ( BLANK ) { ... }

*authorName1.compareTo(authorName2) < 0* - compareTo returns a negative number if authorName1 is less than authorName2.

str1 is "Main" and str2 is " Street" (note the leading space). 2) Use concat to append a period to str2, so str2 should be " Street." str2 = str2. BLANK ;

*concat(".")* - The concat method creates new string with "." appended str2.

Indicate the result of comparing the first string with the second string. 2) "merry", "Merry" A) less than B) equal C) greater than

*greater than* - The coded value for 'm' is greater than the coded value for 'M'

Indicate the result of comparing the first string with the second string. 1) "Apples", "Oranges" A) less than B) equal C) greater than

*less than* - 'A' is less than 'O'

Indicate the result of comparing the first string with the second string. 3) "banana", "bananarama" A) less than B) equal C) greater than

*less than* -If existing characters are equal, the shorter string is less than.

str1 is "Main" and str2 is " Street" (note the leading space). 3) Replace "ai" with "our" in str1, so str1 should be "Mourn". str1 = str1. BLANK ;

*replace("ai", "our")* - Creates a new String in which all occurrences of "ai" are replaced with "our".

Assign the size of userInput to stringSize. Ex: if userInput is "Hello", output is: Size of userInput: 5 import java.util.Scanner; public class StringSize { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String userInput; int stringSize; userInput = scnr.nextLine(); /* Your solution goes here */ System.out.println("Size of userInput: " + stringSize); return; } }

*stringSize = userInput.length();*

Write an expression to detect that the first character of userInput matches firstLetter. import java.util.Scanner; public class CharMatching { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String userInput; char firstLetter; userInput = scnr.nextLine(); firstLetter = scnr.nextLine().charAt(0); if (/* Your solution goes here */) { System.out.println("Found match: " + firstLetter); } else { System.out.println("No match: " + firstLetter); } return; } }

*userInput.charAt(0) == firstLetter*

5) For string "You wish!", which character is at index 4? A) (space) B) w

*w* - 0:Y, 1:o, 2:u, 3:(space), 4:w.

Complete the comparison for floating-point numbers. 3) Determine if double variable x is 1.0 Math.abs([BLANK]) < 0.0001

*x - 1.0* -The subtraction order doesn't matter, because the absolute value is taken

Set hasDigit to true if the 3-character passCode contains a digit. import java.util.Scanner; public class CheckingPasscodes { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); boolean hasDigit; String passCode; hasDigit = false; passCode = scnr.next(); /* Your solution goes here */ if (hasDigit) { System.out.println("Has a digit."); } else { System.out.println("Has no digit."); } } }

/* Your solution goes here */ if(Character.isDigit(passCode.chart0))) { hasDigit = true; } if(Character.isDigit(passCode.chart(1))) { hasDigit = true; } if(Character.isDigit(passCode.chart(2))) { hasDigit = true; }

Print "Censored" if userInput contains the word "darn", else print userInput. End with newline. Ex: If userInput is "That darn cat.", then output is: Censored Ex: If userInput is "Dang, that was scary!", then output is: Dang, that was scary! Note: If the submitted code has an out-of-range access, the system will stop running the code after a few seconds, and report "Program end never reached." The system doesn't print the test case that caused the reported message. import java.util.Scanner; public class CensoredWords { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String userInput; userInput = scnr.nextLine(); /* Your solution goes here */ } }

if (userInput.contains("darn")) { System.out.println("Censored"); } else { System.out.println(userInput); }

Write an if-else statement that prints "Goodbye" if userString is "Quit", else prints "Hello". End with newline. import java.util.Scanner; public class DetectWord { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String userString; userString = scnr.next(); /* Your solution goes here */ } }

if (userString.equals("Quit")) { System.out.println("Goodbye"); } else { System.out.println("Hello"); }

Write code to print the location of any alphabetic character in the 2-character string passCode. Each alphabetic character detected should print a separate statement followed by a newline. Ex: If passCode is "9a", output is: Alphabetic at 1 Hint: Use two if statements to check each of the two characters in the string, using Character.isLetter(). import java.util.Scanner; public class FindAlpha { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String passCode; passCode = scnr.next(); /* Your solution goes here */ } }

if(Character.isLetter(passCode.charAt(0))) { System.out.println("Alphabetic at 0"); } if(Character.isLetter(passCode.charAt(1))) { System.out.println("Alphabetic at 1"); }

Print the two strings, firstString and secondString, in alphabetical order. Assume the strings are lowercase. End with newline. Sample output: capes rabbits import java.util.Scanner; public class OrderStrings { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String firstString; String secondString; firstString = scnr.next(); secondString = scnr.next(); /* Your solution goes here */ } }

if(firstString.compareTo(secondString) < 0) { System.out.println(firstString + " " + secondString); } else { System.out.println(secondString + " " + firstString); }

Modify songVerse to play "The Name Game" (OxfordDictionaries.com), by replacing "(Name)" with userName but without the first letter.Ex: If userName = "Kaitlin" and songVerse = "Banana-fana fo-f(Name)!", the program prints: Banana-fana fo-faitlin! Ex: If userName = "Kaitlin" and songVerse = "Fee fi mo-m(Name)", the program prints: Fee fi mo-maitlin Note: You may assume songVerse will always contain the substring "(Name)". import java.util.Scanner; public class NameSong { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String userName; String songVerse; userName = scnr.nextLine(); userName = userName.substring(1); // Remove first character songVerse = scnr.nextLine(); // Modify songVerse to replace (Name) with userName without first character /* Your solution goes here */ System.out.println(songVerse); }

userName = userName.substring(0); songVerse = songVerse.replace("(Name)" ,userName)


संबंधित स्टडी सेट्स

Passpoint Basic Physical Assessment

View Set

Module 1 C10 Insurance - Social Security

View Set

Ch 67 Cerebrovascular disorders, Hinkle 67 Management of Patients with Cerebrovascular Disorders, Chapter 67, Management of Patients with Cerebrovascular Disorders

View Set

EDAPT Nursing Care: Altered Intracranial Regulation

View Set

Oncology pharmacology and general

View Set

Chapter 10 wireless, mobile connection

View Set