Introduction to Java Programming

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

For the craps game in the tutorial, the client may want to enter a cash amount to bet for each game. If they bet (e.g., $5) and win, they receive two times their bet ($10); if they lose, the money they bet (e.g., $5) goes to the casino. If you need to add the core logic to allow a player to bet in this way, what pseudocode accurately represents this task?

# Ask the player how much to bet per game # Play the game # If the player won the game add double the bet to the total won # else the player lost so subtract the bet from the total won

For the craps game in the tutorial, if code were implemented to input a bet for a player, what code segment would ensure that a non-negative number bet is received?

// Track if input of bet is valid int betAmount = -1; // Assume invalid input of number until it proves to be correct while(!betAmount < 0) { try { System.out.print("Pass Line Bet : "); betAmount = input.nextInt(); if (betAmount >= 0) playMultipleGames(number,betAmount); else System.out.println("Please enter a non-negative number for your bet."); } catch(InputMismatchcatchion ex) { System.out.println("Not a valid bet. Please enter a number for your bet."); // Clear out input to remove \n input.nextLine(); } } System.out.println(); // Add blank line in output

Which of these is a valid comment in Java?

// this is a valid comment

What would be used to find the remainder of 12 divided by 5 (using integer division), and what would be the result?

12%5, 2

Given the following method: public static double getAverage(double... values) { double sum = 0; int count = 0; for(double number : values) { sum += number; count++; } return sum / count; } What would avg1 be set to after the following statement? double avg1 = getAverage(18, 6, 21.3);

15.1

What would be output at the end of the following code segment? int num = 0; for(int row = 0; row < 4; row++ ) { for(int col = 0; col < 5; col++) { num++; } } System.out.println(num);

20

Suppose you have an array defined in the following way: int myArray[][] = {{16, 719, 7}, {6, 5, 4}, {19, 3, 1}}; What are the correct dimensions of this array?

3 x 3

Consider the necessary tasks involved in changing a flat tire: 1. place new tire and tighten bolts 2. remove the tire 3. loosen bolts and lift car 4. get your tools Place these steps in their logical order.

4, 3, 2, 1

At a minimum, it is a best practice that comments be made for which of the following?

Conditional statements

What should be done if insufficient information is gathered to begin programming?

Continue to ask questions

Which of the following options is a property of Java arrays?

Data items in an array need to be of the same type.

What code segment would properly create an instance of the subclass using the variable myDog and name it Penny with 3 legs and have the color set to White?

Dog myDog = new Dog(3, "Penny","White");

The break statement in a while loop would be used to do what?

Exit the loop.

Assume that the output.txt file contains: First Line Given the following snippet of code: What would output.txt contain?

First Line Second Line Third Line

Within the tutorial casino craps game pseudocode, where should you place the pseudocode that performs the task of "Get if the player won or lost" and how (in pseudocode) should this task be implemented?

In method play, with pseudocodemethod play()...return if the player won or lost

What is the output when the following code is run? char sport = 'y'; char outdoor = 'n'; if(sport == 'n') { if(outdoor == 'n') { System.out.println("No sport."); } } else { if(outdoor == 'n') { System.out.println("Indoor sport."); } else { System.out.println("Outdoor sport."); } }

Indoor sport.

Which pane in the default layout configuration of Replit contains the code editor?

Middle Pane

int tempFahrenheit = 0; if (tempFahrenheit < 32){ System.out.println("Must be freezing!"); } else if (tempFahrenheit > 80) { System.out.println("Getting hot!"); } else { System.out.println("Seems like a nice day!"); }

Must be freezing!

What is wrong with the following code segment if the numbers from 1 to 10 are meant to be output? int num = 0; while (num < 10) num = num + 1; System.out.println(num);

Nothing is printed in the while loop.

__________ a series of statements is called iteration.

Repeating

A myfile.txt has the following lines of text, with each line of text having a new line after it: Roses are red Violets are blue Given the following snippet of code:

Roses are red Violets are blue Sugar is sweet

Which of the following error types would be generated, if a program expected to have a variable set prior to use?

Runtime

Given the following method, what would be returned given the following board state when checking for O? {{" X ", " O ", " O "}, {" - ", " X ", " - "}, {" - ", " - ", " X "}} public static int checkForDiagonalWin(String[][] board, char player) { int diagonalNumber = 0; if(board[1][1].equals(" " + player + " ")) { if(board[0][0].equals(" " + player + " ") && board[2][2].equals(" " + player + " ")) { diagonalNumber = 1; } else if(board[0][2].equals(" " + player + " ") && board[2][0].equals(" " + player + " ")) { diagonalNumber = 2; } } return diagonalNumber; }

Since O is being checked, the diagonal verification would return 0, as neither diagonal has Os in place.

Which of the following would output do re mi to the screen?

String firstString= "do "; String secondString = firstString.concat("re "); String thirdString = secondString.concat("mi "); System.out.println(thirdString);

Which of the following would create a data type that contains the value sophia?

String name = "sophia";

Given the following class, what sets of statements would have the end result of the myStudent instance having the student name as teststudent letterGrade as test as B?

Student myStudent = new Student("student name","X"); myStudent.setStudentName("teststudent"); myStudent.setLetterGrade("B");

static String saySomething(String name) { return "Hi " + name; } static String saySomething(String name, int count) { String greeting = ""; for(int i = 0; i < count; i++) { greeting += "Welcome, " + name + "\n"; } return greeting; } Which of the following would need to be called to result in the output: Hi, Sophia

System.out.println(saySomething("Sophia"));

What code segment could be added to call a method that keeps track of the number of employees managed by Managers, called getNumManaged(), and print this result out for an instance named sophia?

System.out.println(sophia.getNumManaged());

Given the following set of classes, what would need to be fixed to produce the output Password?

The instance cust is not in scope in the method outputPassword(). The cust should be declared globally in CustomerTest to be accessed in the outputPassword() method.

Which of the following happens in a program if there is an error that is not handled by a try/catch statement to catch that exception specifically?

The program will terminate and raise an error

What is the issue? static String saySomething(String name, int count) { String greeting = ""; for(int i = 0; i < count; i++) { greeting += "Welcome, " + name + "\n"; } return name; }

The return statement.

Given the following lines of code, which of the following is the result of a user entering 8 when prompted? int wholeNumber = input.nextInt(); System.out.println("Your number is " + wholeNumber + ".");

The string "Your number is 8." is output to the screen.

With the tic-tac-toe game, why was the for loop used to get the player inputs?

There was a definite set of selections for the board.

What would be the result of the following code being executed? class Main { public static void main(String[] args) { System.out.println(I am learning Java); } }

There would be an error due to the missing double quotes around the string value I am learning Java.

Why does a programmer add comments (//) when coding an algorithm?

Used to explain how the program works or functions. These lines are ignored by the compiler during runtime.

Have you completed your Java Journal?

Yes

A user that inputs 1 and 2 into the following code will result in what output?

['-', '-', '-'] ['-, '-', 'X'] ['-', '-', '-']

What would be the result of the following code snippet? int[] ages = {50, 40, 30, 20, 10}; Arrays.sort(ages); int[] agesOther = Arrays.copyOfRange(ages, 0, ages.length-2); System.out.println(Arrays.toString(agesOther));

[10, 20, 30]

A branch in an algorithm can be a good marker to indicate __________ when developing a program.

a potential pattern

Which of the following encapsulates a program's data and its operations?

an object

Subclasses inherit __________ and __________ from their base class.

attributes and methods

String[] letters = {"z", "d", "b", "g", "a", "y"}; Arrays.sort(letters); System.out.println(letters[1]);

b

What is the primitive data type that is typically used to store single letters, digits, and symbols?

char

If you created the following interface: interface Language { void getName(String name); } What would be a class that implements the interface correctly?

class ProgrammingLanguage implements Language { public void getName(String name) { System.out.println("Programming Language: " + name); } }

For the Employee Class Program in the Company Employee Program tutorial, imagine you need to add in a way to update the salary based on an input of "upd" and the employee ID. What code segment would need to be added to the while loop in the main method to implement this?

else if(cmd.toLowerCase().equals("upd")) { System.out.print("Employee ID to update: "); int emplId = input.nextInt(); input.nextLine(); updateEmployees(csvFile, emplId); }

Using the boolean operator A && B, if A = true and B = false, what would the result be?

false

Which of the following import statements would allow the user to get access to the Scanner object?

import java.util.Scanner;

Which of these programs would produce the output 13test?

int num1 = 5; int num2 = 8; char val = 'A'; String word = "test"; System.out.println(num1 + num2 + word);

Which of these is the output of the following program?

int tempFahrenheit = 0; if (tempFahrenheit < 32){ System.out.println("Must be freezing!"); } else if (tempFahrenheit > 80) { System.out.println("Getting hot!"); } else { System.out.println("Seems like a nice day!"); }

Apply what you have learned in Unit 1 about data types, operands, functions, and conditions in simple Java programs to answer the following question: This Java snippet checks whether a number is even or odd. Which method would make the most sense for line 2? 1 Scanner input = new Scanner(System.in); 2 int age = input.______; 3 if (age _____ == 0){ 4 System.out.println("Your age is even."); 5 } else { 6 System.out.println(________); 7 }

nextInt()

What needs to go into <increment/decrement> for the code to output: 1 3 5 7 9

num +=2

What needs to go into the blank for the enhanced for loop to output: 2 * 2 = 4 4 * 4 = 16 6 * 6 = 36 int[] numbers = {2, 4, 6}; for(int number : numbers) { System.out.println(number + " * " + number + " = " + _________); }

number * number

What is the term used to bundle the structure and design of code when implementing object-oriented programming?

objects

What are the actual variable names specified to pass values into a method when we define a method?

parameter

What type of operation is used to perform tasks on data including calculations?

processing

Assume that the Dog class extends the Animal class. If you create a Dog subclass of Animal in which favoriteTreat is also a String, which constructor accurately does this?

public Dog(int legs, String name, String favoriteTreat) { super(legs, name); this.favoriteTreat=favoriteTreat; }

Which of the following methods can be added to the UserAccount class in the tutorial to access the username?

public String getUsername() { return username; }

What does the toString() method need to look like to result in the following output: UserName: userPassword: Java

public String toString() { String state = "UserName: " + userName + "\n"; state += "Password: " + password + "\n"; return state; }

Given the name of the following method, what would be the most accurate return statement in terms of the return variable or expression?

sum

A file was created under the /home/runner/IntrotoJava/ folder named myFile.txt. Assume that you have a File object named testFile pointed to the file. Which method would identify if the file can be changed?

testFile.canWrite()

The __________ is a collection that stores key-value pairs.

HashMap

The constructor is used to initialize what components of an instance of an object?

Its attributes

For the casino craps game, why is the number of games as the input needed?

The other input required for playing and processing the game is a roll from the dice, which is randomly generated by the program.

What is the data type in Java that consists of a true or false value?

boolean

What is the result of this code? ArrayList<String> flowers = new ArrayList<>(); flowers.add("daisy"); flowers.add("rose"); flowers.add("orchid"); System.out.println(flowers.get(0)); System.out.println(flowers.get(1)); System.out.println(flowers.get(2));

daisy rose orchid

The two challenges in this unit will be focused on __________ and __________ an algorithm.

planning, coding

For the subpublic class Contractor of the base public class Person example provided in the tutorial, what if you need to keep track of the project for each contractor. What code segment could be used to properly initialize and add methods to set and get this value?

public class Contractor extends Person { private int contractorId; private double wage; private String project; public Contractor(String firstName,String lastName,String jobTitle,double wage,int contractorId,String project) { super(firstName,lastName,jobTitle); this.contractorId = contractorId; this.wage = wage; this.project = project; } public String getProject() { return "Project: " + project; } public void setProject(String project) { this.project = project; } }

How would you use composition in a Person class to indicate that a person has a job and set the role to a Programmer?

public class Person { private Job job; public Person() { this.job=new Job(); job.setRole("Programmer"); } }


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

Cisco Final pt. 2 (41 questions - one third)

View Set

Accounting 231 - Ch. 11 LearnSmart

View Set

Science- Topic One and Two: Characteristics of Fluids and Flow Rate and Viscosity

View Set

AVID Editing Essentials Review Questions & Answers Lesson 1-10

View Set

Chapter 3: Number Systems and Code

View Set

Chapter 55: Care of Patients with Stomach Disorders

View Set

Disability Income and Related Insurance

View Set