Java Exam 2

¡Supera tus tareas y exámenes ahora con Quizwiz!

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.

!((x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z'))

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).

( x >= '0' && x <= '9')

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 (that is, positive or zero) or y is negative.

( x >= 0) || (y < 0)

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 alphanumeric, that is either a letter or a decimal digit.

(( x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') || (x >= '0' && x <= '9'))

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).

((c != ' ') && (c != '\n') && (c != '\t'))

Given the char variable c, write an expression that is true if and only if the value of c is not the space character.

(c != ' ')

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.

(c == '\n')

Write an expression that evaluates to true if the value of variable lastName is greater than the string Dexter.

(lastName.compareTo("Dexter")>0)

Write an expression that evaluates to true if and only if the variables profits and losses are exactly equal.

(profits == losses)

Write an expression that evaluates to true if the value of the string variable s1 is greater than the value of string variable s2.

(s1.compareTo(s2) > 0)

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.

(temperature > 90) && (humidity < 10)

Write an expression that evaluates to true if the integer variable x contains an even value, and false if it contains an odd value.

(x % 2 == 0)

Write an expression that evaluates to true if and only if the value of the integer variable x is equal to zero.

(x == 0)

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.

(x >= 'A' && x <= 'Z')

Write an expression that evaluates to true if the value x is greater than or equal to y.

(x >= y)

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.

(yearsWithCompany < 5) && (department != 99)

Write a literal representing the false value.

False

Declare an array reference variable, week, and initialize it to an array containing the strings "mon", "tue", "wed", "thu", "fri", "sat", "sun" (in that order).

String [] week = { "mon", "tue", "wed", "thu", "fri", "sat", "sun"};

Given that the array monthSales of integers has already been declared and that its elements contain sales data for the 12 months of the year in order (i.e., January, February, etc.), write a statement that writes to standard output the element corresponding to October. Do not write anything else out to standard output.

System.out.println (monthSales [9]);

Write a literal representing the true value.

True

Assume that an array named a containing exactly 5 integers has been declared and initialized. Write a single statement that adds 10 to the value stored in the first element of the array.

a[0] = a[0] + 10;

Given that an array of ints named a with 30 elements has been declared, assign 5 to its last element.

a[29] = 5;

Given an array a, declared to contain 34 elements, write an expression that refers to the last element of the array.

a[33]

Assume that an array of ints named a that contains exactly five elements has been declared and initialized. In addition, an int variable j has also been declared and initialized to a value somewhere between 0 and 3. Write a single statement that assigns a new value to element of the array indexed by j. This new value should be equal to twice the value stored in the next element of the array (i.e. the element after the element indexed by j.

a[j] = 2* a[j+1];

An array of ints named a has been declared with 12 elements. The integer variable k holds a value between 2 and 8. Assign 22 to the element just before a[k].

a[k-1] = 22;

Declare a variable hasPassedTest, and initialize it to true.

boolean hasPassedTest = true;

Given a String variable response that has already been declared, write some code that repeatedly reads a value from standard input into response until at last a Y or y or N or n has been entered. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.

do { response = stdin.next(); } while (response != "Y" || response != "y" || response != "N" || response != "n");

Given an int variable n that has already been declared and initialized to a positive value, use a do...while loop to print a single line consisting of n asterisks. Use no variables other than n.

do { System.out.print('*'); n--; } while (n > 0);

Given an int variable n that has already been declared, write some code that repeatedly reads a value into n until at last a number between 1 and 10 (inclusive) has been entered. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input.

do { n = stdin.nextInt(); } while (n < 1 || n > 10);

Declare an array named taxRates of five elements of type double and initialize the elements (starting with the first) to the values 0.10, 0.15, 0.21, 0.28, 0.31, respectively.

double taxRates[] = {0.10, 0.15, 0.21, 0.28, 0.31};

Given an int variable n that has already been declared and initialized to a positive value, and another int variable j that has already been declared, use a for loop to print a single line consisting of n asterisks. Thus if n contains 5, five asterisks will be printed. Use no variables other than n and j.

for ( j = 0; j < n; j++) { System.out.print("*"); }

Write a for loop that prints the integers 0 through 39, separated by spaces.

for (int n = 0; n < 40; n++) { System.out.print( n + " "); }

Write a for loop that prints in ascending order all the positive integers less than 200 that are divisible by both 2 and 3, separated by spaces.

for (int n = 6; n <= 200; n = n + 6) { System.out.print(n + " "); }

Given an int variable k that has already been declared, use a for loop to print a single line consisting of 97 asterisks. Use no variables other than k.

for (k = 0; k < 97; k++) { System.out.print("*"); }

Given the integer variables x and y, write a fragment of code that assigns the larger of x and y to another integer variable max.

if ( x > y) max = x; else max = y;

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.

if ((modelYear >= 1995 && modelYear <= 1998)|| (modelYear >= 2004 && modelYear <= 2006)) System.out.println("RECALL");

Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999-2002 as well all vehicles in its Guzzler line from model years 2004-2007. A boolean variable named recalled has been declared. Given a variable modelYear and a String modelName write a statement that assigns true to recalled if the values of modelYear and modelName match the recall details and assigns false otherwise.

if ((modelYear >= 1999 && modelYear <= 2002 && modelName == "Extravagant") || (modelYear >= 2004 && modelYear <= 2007 && modelName == "Guzzler")) { recalled = true; } else { recalled = false; }z

Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999-2002. A boolean variable named recalled has been declared. Given a variable modelYear and a String modelName write a statement that assigns true to recalled if the values of modelYear and modelName match the recall details and assigns false otherwise.

if ((modelYear >= 1999) && (modelYear <= 2002) && (modelName.equals("Extravagant"))) recalled = true; else recalled = false;

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.

if (age >= 65) seniorCitizens = seniorCitizens + 1; else nonSeniors = nonSeniors + 1;

Write a conditional that assigns 10,000 to the variable bonus if the value of the variable goodsSold is greater than 500,000.

if (goodsSold > 500000) bonus = 10000;

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.

if (gpa > 3.5) { deansList = deansList + 1; System.out.println(studentName); }

Given the String variables name1 and name2, write a fragment of code that assigns the larger of the two to the variable first (assume that all three are already declared and that name1 and name2 have been assigned values). (NOTE: "larger" here means alphabetically larger, not "longer". Thus, "mouse" is larger than "elephant" because "mouse" comes later in the dictionary than "elephant"!)

if (name1.compareTo(name2) > 0) { first = name1; } else { first = name2; }

Write a conditional that decreases the variable shelfLife by 4 if the variable outsideTemperature is greater than 90.

if (outsideTemperature > 90) shelfLife = shelfLife - 4;

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.

if (soldYesterday > soldToday) salesTrend = - 1; else salesTrend = + 1;

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.

if (temperature > 98.6) fever = true; else fever = false;

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.

if (workedOvertime == true) pay = pay * 1.5;

4.5: Average and ExtremesWrite a program to read a list of nonnegative integers and to displaythe largest integer, the smallest integer, and the average of all theintegers. The user indicates the end of the input by entering anegative sentinel value that is not used in finding the largest,smallest, and average values. The average should be a value of typedouble so that it is computed with a fractional part. Input Notes:The input is simply a sequence of positive integers, separated by white space andterminated by -1. SAMPLE RUN #1: java LargeSmallAverage Interactive SessionThis program allows you to enter a list of positive integers(terminated by a -1) then displays the largest value,smallest value, and average of the list of numbers,not including the final (negative) value that ends the list.Enter a positive integer, or -1 to quit:-1 You did not enter any positive integers.

import java.util.Scanner; public class LargeSmallAverage { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int input, largest, smallest, count = 0, total = 0; double average; System.out.println("This program allows you to enter a list of positive integers\n" + "(terminated by a -1) then displays the largest value,\n" + "smallest value, and average of the list of numbers,\n" + "not including the final (negative) value that ends the list.\n" + "Enter a positive integer, or -1 to quit: "); input = keyboard.nextInt(); smallest = input; largest = input; if (input == -1) { System.out.println("You did not enter any positive integers."); } while (input > 0) { if (smallest > input) { smallest = input; } if (largest < input) { largest = input; } total = total + input; count ++; input = keyboard.nextInt(); } average = total / count; System.out.println("The smallest integer is: " + smallest); System.out.println("The largest integer is: " + largest); System.out.println("The average is: " + average); } }

Write a program that allows the user to convert a temperature givenin degrees from either Celsius to Fahrenheit or Fahrenheit to Celsius.Use the following formulas:Degrees_C = 5(Degrees_F− 32)/9andDegrees_F = (9(Degrees_C)/5) + 32) Prompt the user to enter a temperature and either a C or c for Celsiusor an F or f for Fahrenheit. Convert the temperature to Fahrenheit ifCelsius is entered, or to Celsius if Fahrenheit is entered. Displaythe result in a readable format. If anything other than C, c, F,or f is entered, print an error message and stop. SAMPLE RUN #1: java TemperatureConversionSelection Interactive SessionEnter a temperature in degrees (for example 29.6):32 Enter 'F' (or 'f') for Fahrenheit or 'C' (or 'c') for Celsius:F 32.0 degrees F = 0.0 degrees Celsius.

import java.util.Scanner; public class TemperatureConversionSelection { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String tempName; double tempType, Degrees_C, Degrees_F; System.out.println("Enter a temperature in degrees (for example 29.6): "); tempType = keyboard.nextDouble(); tempName = keyboard.nextLine(); System.out.println("Enter 'F' (or 'f') for Fahrenheit or 'C' (or 'c') for Celsius: "); tempName = keyboard.nextLine(); if (tempName.equalsIgnoreCase("f")) { Degrees_C = 5 * (tempType - 32) /9 ; System.out.println(tempType + " degrees F = " + Degrees_C + " degrees Celsius."); } else { Degrees_F = (9 * (tempType / 5) + 32); System.out.println(tempType + " degrees C = " + Degrees_F + " degrees Fahrenheit."); } } }

In a single statement: declare, create and initialize an array named a of ten elements of type int with the values of the elements (starting with the first) set to 10, 20, ..., 100 respectively.

int a[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

Declare and instantiate an array named scores of twenty-five elements of type int.

int scores[] = new int [25];

Write an expression that evaluates to true if and only if value of the boolean variable isAMember is false.

isAMember == false

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.

isEmpty || numberOfCredits == 3

Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a do...while loop to compute the sum of the cubes of the first n whole numbers, and store this value in total. Use no variables other than n, k, and total.

k = 1; total = 0; do { total = total + k * k * k; k++; } while (k <= n);

Given an int variable k that has already been declared, use a while loop to print a single line consisting of 88 asterisks. Use no variables other than k.

k = 1; while (k <= 88) { System.out.println('*'); k++; } System.out.println();

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!

norecall = !(modelYear >= 2001 && modelYear <= 2006);

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!

norecall =!((modelYear >= 1995 && modelYear <= 1998) || (modelYear >= 2004 && modelYear <= 2006));

Write an expression that evaluates to true if and only if the string variable s equals the string "end".

s.equals("end")

Given an array of ints named x and an int variable named total that has already been declared, write some code that places the sum of all the elements of the array x into total. Declare any variables that you need.

total = 0; for (int i = 0; i < x.length; i++) { total = total + x[i]; }

Given an array temps of doubles, containing temperature data, compute the average temperature. Store the average in a variable called avgTemp. Besides temps and avgTemp, you may use only two other variables -- an int variable k and a double variable named total, which have been declared.

total = 0; for (k = 0; k < temps.length; k++) { total = total + temps[k]; } avgTemp = total/temps.length;

Given int variables k and total that have already been declared, use a do...while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in total. Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into total. Use no variables other than k and total.

total = 0; k=1; do { total += k * k; k ++; } while (k<=50);

Given an int variable n that has already been declared and initialized to a positive value, use a while loop to print a single line consisting of n asterisks. Use no variables other than n.

while (n > 0) { System.out.print('*'); n--; } System.out.println();

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.)

widthOfBox % widthOfBook != 0)

Assume that the array arr has been declared. Write a statement that assigns the next to last element of the array to the variable x, which has already been declared.

x= arr[arr.length-2];


Conjuntos de estudio relacionados

CIT226 Win Server Management Exam Chapters 1 - 3

View Set

FILIPINO - PANGUNGUSAP NA WALANG PAKSA

View Set

IB Biology HL - Unit 3: Cellular Biology

View Set

Multiple Choice Questions on Restriction enzymes

View Set

Simulatanéité, Postériorité, Antériorité

View Set

Fundamentals Practice Test A with NGN

View Set