Chapter 3 Fundamentals Of Programming - Java

25 July 2022
4.7 (114 reviews)
70 test answers

Unlock all answers in this set

Unlock answers (66)
question
Write a literal representing the false value .
answer
false
question
Write a literal representing the true value .
answer
true
question
Declare a variable isACustomer suitable for representing a true or false value .
answer
boolean isACustomer
question
Declare a variable hasPassedTest, and initialize it to true .
answer
boolean hasPassedTest = true;
question
Given an int variable grossPay, write an expression that evaluates to true if and only if the value of grossPay is less than 10,000.
answer
if (grossPay <= 10,000)
question
Write an expression that evaluates to true if and only if the integer x is greater than the integer y.
answer
x>y
question
Write an expression that evaluates to true if and only if the value of the integer variable x is equal to zero.
answer
x == 0
question
Write an expression that evaluates to true if and only if the variables profits and losses are exactly equal .
answer
profits == losses
question
Write an expression that evaluates to true if the value of index is greater than the value of lastIndex.
answer
index > lastIndex
question
Working overtime is defined as having worked more than 40 hours during the week. Given the variable hoursWorked, write an expression that evaluates to true if the employee worked overtime.
answer
hoursWorked > 40
question
Write an expression that evaluates to true if the value x is greater than or equal to y.
answer
x >= y
question
Given the variables numberOfMen and numberOfWomen, write an expression that evaluates to true if the number of men is greater than or equal to the number of women.
answer
numberOfMen >= numberOfWomen
question
Given a double variable called average, write an expression that is true if and only if the variable 's value is less than 60.0.
answer
average < 60.0
question
Given the char variable c, write an expression that is true if and only if the value of c is not the space character .
answer
c !=' '
question
Assume that c is a char variable has been declared and already given a value . Write an expression whose value is true if and only if c is a newline character .
answer
c == 'n'
question
Assume that c is a char variable has been declared and already given a value . Write an expression whose value is true if and only if c is a space character .
answer
c == ' '
question
Assume that c is a char variable has been declared and already given a value . Write an expression whose value is true if and only if c is a tab character .
answer
c == 't'
question
Write an expression that evaluates to true if the integer variable x contains an even value , and false if it contains an odd value .
answer
x % 2 == 0
question
Write an expression that evaluates to true if the value of the integer variable numberOfPrizes is divisible (with no remainder) by the integer variable numberOfParticipants. Assume that numberOfParticipants is not zero.
answer
numberOfPrizes % numberOfParticipants == 0
question
Write an expression that evaluates to true if the value of the integer variable widthOfBox is not divisible by the value of the integer variable widthOfBook. Assume that widthOfBook is not zero. ("Not divisible" means has a remainder.)
answer
widthOfBox % widthOfBook !=0
question
Write a conditional that assigns 10,000 to the variable bonus if the value of the variable goodsSold is greater than 500,000.
answer
if (goodsSold > 500000)bonus = 10000;
question
Write a conditional that decreases the variable shelfLife by 4 if the variable outsideTemperature is greater than 90.
answer
if(outsideTemperature > 90) shelfLife = shelfLife - 4;
question
Assume that the variables gpa, deansList and studentName, have been declared and initialized . Write a statement that adds 1 to deansList and prints studentName to standard out if gpa exceeds 3.5.
answer
if(gpa > 3.5){ deansList = deansList + 1; System.out.println(studentName); }
question
Write an if/else statement that compares the variable age with 65, adds 1 to the variable seniorCitizens if age is greater than or equal to 65, and adds 1 to the variable nonSeniors otherwise.
answer
if (age >= 65) seniorCitizens += 1; else nonSeniors += 1;
question
Write an if/else statement that compares the value of the variables soldYesterday and soldToday, and based upon that comparison assigns salesTrend the value -1 or 1. -1 represents the case where soldYesterday is greater than soldToday; 1 represents the case where soldYesterday is not greater than soldToday.
answer
if (soldYesterday > soldToday) salesTrend = -1; else salesTrend = 1;
question
NOTE: in mathematics, division by zero is undefined. So, in Java, division by zero is always an error. Given a int variable named callsReceived and another int variable named operatorsOnCall write the necessary code to read values into callsReceived and operatorsOnCall and print out the number of calls received per operator (integer division with truncation will do). HOWEVER: if any value read in is not valid input, just print the message "INVALID". ASSUME the availability of a variable , stdin, that references a Scanner object associated with standard input.
answer
callsReceived = stdin.nextInt(); operatorsOnCall = stdin.nextInt(); if (operatorsOnCall == 0) System.out.println("INVALID"); else System.out.println(callsReceived/operatorsOnCall);
question
Given a int variable named callsReceived and another int variable named operatorsOnCall write the necessary code to read values into callsReceived and operatorsOnCall and print out the number of calls received per operator (integer division with truncation will do). HOWEVER: if any value read in is not valid input, just print the message "INVALID". ASSUME the availability of a variable , stdin, that references a Scanner object associated with standard input.
answer
callsReceived = stdin.nextInt(); operatorsOnCall = stdin.nextInt(); if (operatorsOnCall == 0) System.out.println("INVALID"); else System.out.println(callsReceived/operatorsOnCall);
question
Write an if/else statement that adds 1 to the variable minors if the variable age is less than 18, adds 1 to the variable adults if age is 18 through 64 and adds 1 to the variable seniors if age is 65 or older.
answer
if(age < 18){ minors = minors + 1; }else if(age > 17 && age < 65){ adults = adults + 1; }else{ seniors = seniors + 1; }
question
Write a statement that adds 1 to the variable reverseDrivers if the variable speed is less than 0,adds 1 to the variable parkedDrivers if the variable speed is less than 1,adds 1 to the variable slowDrivers if the variable speed is less than 40,adds 1 to the variable safeDrivers if the variable speed is less than or equal to 65, and otherwise adds 1 to the variable speeders.
answer
if (speed < 0) reverseDrivers += 1; else if (speed < 1) parkedDrivers += 1; else if (speed < 40) slowDrivers += 1; else if (speed <= 65) safeDrivers += 1; else speeders += 1;
question
Write an if/else statement that compares the double variable pH with 7.0 and makes the following assignments to the int variables neutral, base, and acid: 0,0,1 if pH is less than 7 0,1,0 if pH is greater than 7 1,0,0 if pH is equal to 7
answer
if (pH < 7){ neutral = 0; base = 0; acid = 1; }else if (pH > 7){ neutral = 0; base = 1; acid = 0; }else { neutral = 1; base = 0; acid = 0; }
question
Write a statement that compares the values of score1 and score2 and takes the following actions. When score1 exceeds score2, the message "player1 wins" is printed to standard out. When score2 exceeds score1, the message "player2 wins" is printed to standard out. In each case, the variables player1Wins,, player1Losses, player2Wins, and player2Losses,, are incremented when appropriate. Finally, in the event of a tie, the message "tie" is printed and the variable tieCount is incremented .
answer
if (score1 > score2){ System.out.print("player1 wins"); player1Wins += 1; player2Losses += 1; }else if (score2 > score1){ System.out.print("player2 wins"); player1Losses += 1; player2Wins += 1; }else { System.out.print("tie"); tieCount += 1; }
question
Assume that an int variable age has been declared and already given a value . Assume further that the user has just been presented with the following menu: S: hangar steak, red potatoes, asparagus T: whole trout, long rice, brussel sprouts B: cheddar cheeseburger, steak fries, cole slaw (Yes, this menu really IS a menu!) Write some code that reads the String (S or T or B) that the user types in into a String variable choice that has already been declared and prints out a recommended accompanying drink as follows: if the value of age is 21 or lower, the recommendation is "vegetable juice" for steak, "cranberry juice" for trout, and "soda" for the burger. Otherwise, the recommendations are "cabernet", "chardonnay", and "IPA" for steak, trout, and burger respectively. Regardless of the value of age, your code should print "invalid menu selection" if the character read into choice was not S or T or B. ASSUME the availability of a variable , stdin, that references a Scanner object associated with standard input.
answer
choice = stdin.next(); if (choice.equals("S")){ if (age <= 21) System.out.println("vegetable juice"); else System.out.println("cabernet"); }else if (choice.equals("T")){ if (age <= 21) System.out.println("cranberry juice"); else System.out.println("chardonnay"); }else if (choice.equals("B")){ if (age <= 21) System.out.println("soda"); else System.out.println("IPA"); }else System.out.println("invalid menu selection");
question
Online Book Merchants offers premium customers 1 free book with every purchase of 5 or more books and offers 2 free books with every purchase of 8 or more books. It offers regular customers 1 free book with every purchase of 7 or more books, and offers 2 free books with every purchase of 12 or more books. Write a statement that assigns freeBooks the appropriate value based on the values of the boolean variable isPremiumCustomer and the int variable nbooksPurchased.
answer
freeBooks = 0; if (isPremiumCustomer == true){ if (nbooksPurchased >= 5) freeBooks = 1; if (nbooksPurchased >= 8) freeBooks = 2; }else if (isPremiumCustomer == false){ if (nbooksPurchased >= 7) freeBooks = 1; if (nbooksPurchased >= 12) freeBooks = 2; }
question
Write an expression that evaluates to true if and only if the value of the boolean variable workedOvertime is true .
answer
workedOvertime == true
question
Assume that a boolean variable workedOvertime has been declared , and that another variable , hoursWorked has been declared and initialized . Write a statement that assigns the value true to workedOvertime if hoursWorked is greater than 40 and false otherwise.
answer
workedOvertime= hoursWorked > 40;
question
Assume that isIsosceles is a boolean variable , and that the variables isoCount,triangleCount, and polygonCount have all been declared and initialized . Write a statement that adds 1 to each of these count variables (isoCount,triangleCount, andpolygonCount) if isIsosceles is true .
answer
if (isIsosceles == true) { isoCount += 1; triangleCount += 1; polygonCount += 1; }
question
Write a conditional that assigns the boolean value true to the variable fever if the variable temperature is greater than 98.6.
answer
if ( temperature > 98.6 ) fever = true ;
question
Write a conditional that multiplies the value of the variable pay by one-and-a-half if the value of the boolean variable workedOvertime is true .
answer
if (workedOvertime == true) pay = pay * 1.5;
question
Write an if/else statement that assigns true to the variable fever if the variable temperature is greater than 98.6; otherwise it assigns false to fever.
answer
if (temperature > 98.6) fever = true; else fever = false;
question
Assume that c is a char variable has been declared and already given a value . Write an expression whose value is true if and only if c is NOT what is called a whitespace character (that is a space or a tab or a newline-- none of which result in ink being printed on paper).
answer
!(c == ' ' || c== 'n' || c == 't')
question
Given that the variables x and y have already been declared and assigned values , write an expression that evaluates to true if x is non-negative and y is negative.
answer
(x >= 0 && y<0)
question
Given that the variables x and y have already been declared and assigned values , write an expression that evaluates to true if x is positive (including zero) or y is negative.
answer
(x>=0 || y<0)
question
Given the integer variables yearsWithCompany and department, write an expression that evaluates to true if yearsWithCompany is less than 5 and department is not equal to 99.
answer
yearsWithCompany < 5 && department != 99
question
Given the variables temperature and humidity, write an expression that evaluates to true if and only if the temperature is greater than 90 and the humidity is less than 10.
answer
temperature>90 && humidity<10 == true
question
Given two variables , isEmpty of type boolean , indicating whether a class roster is empty or not, and numberOfCredits of type int , containing the number of credits for a class , write an expression that evaluates to true if the class roster is empty or the class is exactly three credits.
answer
isEmpty || numberOfCredits == 3
question
Given two variables , isEmpty of type boolean , indicating whether a class roster is empty or not, and numberOfCredits of type int , containing the number of credits for a class , write an expression that evaluates to true if the class roster is not empty and the class is more than two credits.
answer
!isEmpty && numberOfCredits > 2
question
Given two variables , isEmpty of type boolean , indicating whether a class roster is empty or not, and numberOfCredits of type integer , containing the number of credits for a class , write an expression that evaluates to true if the class roster is not empty and the class is one or three credits.
answer
!isEmpty && (numberOfCredits == 1 || numberOfCredits == 3)
question
Given the variables isFullTimeStudent and age, write an expression that evaluates to true if age is less than 19 or isFullTimeStudent is true .
answer
(age<19 || isFullTimeStudent==true) ? true:false
question
Write an expression that evaluates to true if and only if value of the boolean variable isAMember is false .
answer
isAMember == false
question
Write a statement that toggles the value of onOffSwitch. That is, if onOffSwitch is false , its value is changed to true ; if onOffSwitch is true , its value is changed to false .
answer
onOffSwitch = !onOffSwitch;
question
Assume that a boolean variable isQuadrilateral has been declared , and that another variable , numberOfSides has been declared and initialized . Write a statement that assigns the value true if numberOfSides is exactly 4 and false otherwise.
answer
if (numberOfSides == 4) isQuadrilateral = true; else isQuadrilateral = false;
question
Assign to the boolean variable 'possibleCandidate' the value false if the int variable 'n' is even and greater than 2, or if the variable 'n' is less than or equal to 0; otherwise, assign true to 'possibleCandidate'. Assume 'possibleCandidate' and 'n' are already declared and 'n' assigned a value .
answer
possibleCandidate = !(n % 2 == 0 && n > 2 || n <= 0);
question
Clunker Motors Inc. is recalling all vehicles from model years 2001-2006. A boolean variable named recalled has been declared . Given a variable modelYear write a statement that assigns true to recalled if the value of modelYear falls within the recall range and assigns false otherwise. Do not use an if statement in this exercise!
answer
recalled=(modelYear>=2001 && modelYear<=2006);
question
Clunker Motors Inc. is recalling all vehicles from model years 2001-2006. A boolean variable named norecall has been declared . Given a variable modelYear write a statement that assigns true to norecall if the value of modelYear does NOT within the recall range and assigns false otherwise. Do not use an if statement in this exercise!
answer
norecall=!(modelYear >= 2001 && modelYear <= 2006);
question
Clunker Motors Inc. is recalling all vehicles from model years 1995-1998 and 2004-2006. A boolean variable named recalled has been declared . Given a variable modelYear write a statement that assigns true to recalled if the value of modelYear falls within the two recall ranges and assigns false otherwise. Do not use an if statement in this exercise!
answer
recalled = (modelYear >= 1995 && modelYear <= 1998) || (modelYear >= 2004 && modelYear <= 2006);
question
Clunker Motors Inc. is recalling all vehicles from model years 1995-1998 and 2004-2006. A boolean variable named recalled has been declared . Given a variable modelYear write a statement that assigns true to norecall if the value of modelYear does NOT fall within the two recall ranges and assigns false otherwise. Do not use an if statement in this exercise!
answer
norecall=!((modelYear>=1995 && modelYear <=1998) || (modelYear>=2004 && modelYear<=2006));
question
Assume that x is a char variable has been declared and already given a value . Write an expression whose value is true if and only if x is NOT a letter.
answer
!(x>='a' && x<='z') && !(x>='A' && x<='Z')
question
Assume that x is a char variable has been declared and already given a value . Write an expression whose value is true if and only if x is a upper-case letter.
answer
(x>='A' && x<='Z')
question
Assume that x is a char variable has been declared and already given a value . Write an expression whose value is true if and only if x is a lower-case letter.
answer
(x>='a' && x<='z')
question
Assume that x is a char variable has been declared and already given a value . Write an expression whose value is true if and only if x is a decimal digit (0-9).
answer
(x>='0' && x<='9')
question
Assume that x is a char variable has been declared and already given a value . Write an expression whose value is true if and only if x is an octal (Base 8) digit (0-7).
answer
(x>=48 && x<=55)
question
Clunker Motors Inc. is recalling all vehicles from model years 2001-2006. Given a variable modelYear write a statement that prints the message "NO RECALL" to standard output if the value of modelYear DOES NOT fall within that range.
answer
if (modelYear > 2006 || modelYear < 2001) System.out.println("NO RECALL");
question
Clunker Motors Inc. is recalling all vehicles from model years 2001-2006. Given a variable modelYear write a statement that prints the message "RECALL" to standard output if the value of modelYear falls within that range.
answer
if (modelYear >= 2001 && modelYear <= 2006) System.out.println("RECALL");
question
Clunker Motors Inc. is recalling all vehicles from model years 1995-1998 and 2004-2006. Given a variable modelYear write a statement that prints the message "RECALL" to standard output if the value of modelYear falls within those two ranges.
answer
if ((modelYear >= 1995 && modelYear <= 1998) || (modelYear >=2004 && modelYear<=2006)) System.out.println("RECALL");
question
3-5) (Find future dates) Write a program that prompts the user to enter an integer for today's day of the week (Sunday is 0, Monday is 1, ..., and Saturday is 6). Also prompt the user to enter the number of days after today for a future day and dis- play the future day of the week.
answer
import java.util.Scanner; public class FindFutureDates { public static void main(String[]args) { Scanner input = new Scanner(System.in); System.out.print("Enter today's day:"); int today = input.nextInt(); System.out.print("Enter the number of days elapsed since today:"); int elapsedDays = input.nextInt(); int futureDay = (today + elapsedDays)%7; System.out.print("Today is "); switch(today) { case 0: System.out.print("Sunday"); break; case 1: System.out.print("Monday"); break; case 2: System.out.print("Tueday"); break; case 3: System.out.print("Wednesay"); break; case 4: System.out.print("Thursday"); break; case 5: System.out.print("Friday"); break; case 6: System.out.print("Saturday"); break; default: System.out.print(" an invalid starting day. Today's day must be 0-6."); } System.out.print(" and the future day is "); switch(futureDay) { case 0: System.out.println("Sunday"); break; case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesay"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; default: System.out.println("Unknown day"); } } }
question
Write an expression using the conditional operator (? :) that compares the values of the variables x and y. The result (that is the value ) of this expression should be the value of the larger of the two variables .
answer
(x < y ? y : x)
question
Write an expression using the conditional operator (? :) that compares the value of the variable x to 5 and results in: x if x is greater than or equal to 5 -x if x is less than 5
answer
(x >= 5) ? x: -x
question
Four int variables , x1, x2, y1, and y2, have been declared and been given values . Write an expression whose value is the difference between the larger of x1 and x2 and the smaller of y1 and y2.
answer
(x1 < x2 ? x2 : x1) - (y1 < y2 ? y1 : y2)
question
Assume that month is an int variable whose value is 1 or 2 or 3 or 5 ... or 11 or 12. Write an expression whose value is "jan" or "feb" or "mar" or "apr" or "may" or "jun" or "jul" or "aug" or "sep" or "oct" or "nov" or "dec" based on the value of month. (So, if the value of month were 4 then the value of the expression would be "apr".).
answer
(month==1)?"jan":(month==2)?"feb": (month==3)?"mar": (month==4)?"apr": (month==5)?"may":(month==6)?"jun": (month==7)?"jul":(month==8)?"aug": (month==9)?"sep": (month==10)?"oct": (month==11)?"nov": (month==12)?"dec":null
question
Assume that credits is an int variable whose value is 0 or positive. Write an expression whose value is "freshman" or "sophomore" or "junior" or "senior" based on the value of credits. In particular: if the value of credits is less than 30 the expression 's value is "freshman"; 30-59 would be a "sophomore", 60-89 would be "junior" and 90 or more would be a "senior".
answer
(credits < 30) ? "freshman" : (credits >= 30 && credits < 60) ?"sophomore" : (credits >= 60 && credits < 90) ? "junior" : "senior"