Write a Static Method Named Longestname That Reads Names
Edifice Java Programs
Lab iv: Ch. 4: If/Else, Scanner, Cumulative Algorithms
Except where otherwise noted, the contents of this certificate are Copyright 2012 Stuart Reges and Marty Stepp.
lab document created by Marty Stepp and Stuart Reges
Today's lab
Goals for today:
- use
if/elsestatements to select between alternate code paths - use
Scannerto read user input - use
Strings to represent and manipulate text data - practice cumulative algorithms for complex computations
- Where you see this icon, you can click it to check the problem in Practise-Information technology!
if/else Statements
An if/else statement lets your program choose between 2 or more options.
if (examination) { argument(southward); } else { argument(s); } Example:
if (gpa >= ii.0) { System.out.println("Welcome to Mars Academy!"); } else { Organization.out.println("Please apply again shortly."); } Exercise : if/else mystery
Consider the following Coffee lawmaking. Make full in the boxes with the output produced by each of the method calls.
public static void mystery(int northward) { System.out.print(northward + " "); if (due north > 10) { n = n / ii; } else { due north = n + vii; } if (n * 2 < 25) { n = n + x; } Organization.out.println(n); } |
|
Do : if/else mystery
Consider the following Java code.
public static void ifElseMystery(int a, int b) { if (a < b) { a = a * 2; } if (a > b) { a = a - 10; } else { b++; } Arrangement.out.println(a + " " + b); } Fill up in the boxes with the output produced by each of the method calls.
ifElseMystery(ten, 3); | 0 iii | |
ifElseMystery(6, six); | 6 7 | |
ifElseMystery(3, iv); | -four four | |
ifElseMystery(4, twenty); | viii 21 |
if/else factoring
- Information technology's piece of cake to introduce redundancy in the branches of an
if/else. For instance:if (x < xxx) { a = two; x++; System.out.println("CSE 142 TAs are awesome! " + x); } else { a = 2; System.out.println("CSE 142 TAs are awesome! " + x); } - The code tin exist factored out to go: (discover that the
elsewent away!)a = 2; if (x < xxx) { x++; } Arrangement.out.println("CSE 142 TAs are awesome! " + x);
Exercise : if/else Factoring
- Download the following programme
FactorExample.java to your auto and open up it with jGrasp. - The plan's method is redundant. Cistron the method, restructuring the lawmaking to eliminate unnecessary statements while retaining the same behavior.
- Insert some test calls of the method in
chiefand run information technology to make sure it works properly.
Exercise : numUnique
Write a method named numUnique that accepts three integers every bit parameters and that returns the number of unique integers among the three. For case, the call numUnique(18, iii, iv) should return iii because the parameters have 3 different values. Past contrast, the call numUnique(6, vii, 6) would return 2 because there are only 2 unique numbers among the three parameters: half-dozen and 7.
- (Try solving this problem in Practice-It by clicking the icon to a higher place.)
Exercise : AgeCheck
- Re-create/paste and save the following programme in jGRASP, then see the instructions on the next slide.
public class AgeCheck { public static void primary(String[] args) { int myAge = 19; // I am 19; let me run across if I tin drive message(myAge); } // Displays message almost driving to user based on given age public static void bulletin(int historic period) { if (myAge >= 16) { System.out.println("I'm old enough to drive!"); } if (myAge <= 16) { Organisation.out.println("Not old enough nonetheless... :*("); } } }
Exercise - things to set up
- The plan has a few syntax errors. Fix them until it compiles.
- The lawmaking has a logic problem. (For some value(s), it prints the wrong answer.) Find any such problems and gear up them. (You may need to run the program a few times and endeavor different values to see which ones fail.)
- The plan uses
ifandelsein a impuissant manner. Improve the manner of the code.
Do - answer
- The following is a corrected version of the program:
public class AgeCheck { public static void main(String[] args) { int myAge = xix; // I am 19; permit me see if I can drive message(myAge); } // Displays a message about driving to user based on given age public static void bulletin(int age) { if (age >= 16) { System.out.println("I'chiliad old plenty to drive!"); } else { Arrangement.out.println("Not erstwhile enough yet... :*("); } } }
Exercise : AgeCheck2
- Now supplant your previous
AgeCheckprogram'southmessagemethod with:// Peradventure prints some message(s) to the user based on the given age public static void message(int historic period) { if (historic period >= 21) { Arrangement.out.println("I tin legally purchase alcohol!"); } else if (age >= 17) { System.out.println("I can buy a ticket to an R-rated movie."); } else if (age >= xvi) { System.out.println("I can go my driver'south license!"); } } - For some historic period(s), the bulletin(southward) printed are not authentic. (In some cases, information technology should impress no messages; in some cases, i message; and in others, many messages.) Improve the usage of
ifsouthward andelsedue south in this method to conduct properly.
Do : Syntax errors
- The post-obit Java program has 7 errors. Can you find all of them?
i two 3 4 5 half-dozen 7 eight nine 10 eleven 12 13 14 15 xvi 17 18
public grade IfOops { public static void master(Cord[] args) { int a = seven, b = 42; minimum(a, b); if {smaller = a} { System.out.println("a is the smallest!"); } } public static void minimum(int a, int b) { // returns which int is smaller if (a < b) { int smaller = a; } else (a => b) { int smaller = b; } render int smaller; } } - Copy and paste the code into jGrasp and come across if y'all can ready the errors.
Do - answer
- line five:
ifstatement should use()parentheses, not{}brackets - line five:
=should be== - line five:
smalleris out of scope here - line 10:
voidshould beint - line 13:
=>should be>=(or better yet, noifexam is needed) - line 16: should non write variable's type of
intwhen returning it - line 16:
int smalleris out of scope here (declare outsideifor return direct)
Exercise - Corrected version
-
public class IfOops { public static void master(String[] args) { int a = seven, b = 42; int smaller = minimum(a, b); if (smaller == a) { System.out.println("a is the smallest!"); } } public staticvoidint minimum(int a, int b) { // returns which int is smaller int smaller; if (a < b) {intsmaller = a; } elseif (a >= b){intsmaller = b; } returnintsmaller; } }
Exercise : seeMovie
You lot're thinking about going with your friends to a movie. Write a Coffee method seeMovie that accepts two parameters: the cost of a ticket in dollars, and the rating number of stars the moving picture received out of 5. The method should print how interested you lot are (very, sort-of, or not). Employ the following criteria:
- You lot like bargains. Any flick that costs less than $5.00 is one that you want to come across very much.
- Yous dislike expensive movies. You are not interested in seeing any movie that costs $12.00 or more, unless it got 5 stars (and fifty-fifty and so, you are just sort-of interested).
- You like quality. You are very interested in seeing 5-star movies that cost under $12.00.
- You are sort-of interested in seeing movies costing betwixt $5.00 - $11.99 that likewise got between ii-4 stars inclusive.
- You are not interested in seeing any other movies not described previously.
User input and Scanner
| Method name | Clarification |
|---|---|
nextInt() | reads and returns the next token every bit an int, if possible |
nextDouble() | reads and returns the side by side token as double, if possible |
next() | reads and returns a single give-and-take as a String |
nextLine() | reads and returns an entire line as a Cord |
Example:
import java.util.*; // so you can use Scanner ... Scanner console = new Scanner(System.in); Organisation.out.print("How former are you? "); // prompt int age = panel.nextInt(); System.out.println("Y'all typed " + historic period); Do : DevryAdmit
Write a consummate programme DevryAdmit with the beliefs shown below. Apply the Scanner to read user input for a pupil'south form point boilerplate and SAT exam score. A GPA beneath 1.viii will cause the student to exist rejected; an SAT score below 900 will also cause a rejection. Otherwise the student is accepted.
Devry Academy admission plan What is your GPA? iii.2 What is your SAT score? 1280 You lot were accepted!
Check your reply using Exercise-It from the check-mark icon above.
Exercise : ProcessName
Copy/paste and save
ProcessName.coffee in jGRASP, then become to the next slide.
import java.util.*; // for Scanner public class ProcessName { public static void main(Cord[] args) { Scanner console = new Scanner(Organization.in); Arrangement.out.print("Type your proper name: "); // your lawmaking goes here Organisation.out.println("Your name is: " + name); } } continued on the adjacent slide ...
Exercise - lawmaking to add
- Add code to the program then that it reads the user'south kickoff and final proper name (read an entire line as a single string), and so prints the last proper name followed by a comma and the first initial. (Presume that the user types a valid proper name.) Example:
Type your name: Jessica Miller Your proper name is: Miller, J. - Discover that the program reads an unabridged line of user input, not merely i word.
- Attempt solving this problem in Practice-It! using the link above.
Exercise : Syntax errors
- The following Java programme has 11 errors. Can y'all observe them all?
1 2 3 four 5 6 7 viii ix 10 eleven 12 13 14 15 xvi 17 18
public class StringOops { public static void main(Cord[] args) { Scanner panel = new Scanner(Arrangement.in); Organisation.out.print("Type your proper noun: "); Cord name = console.nextString(); process(proper noun); } public static void process(string "name") { if (proper noun == Whitaker) { System.out.println("You must exist really awesome."); } replace("a", "due east"); toUppercase(proper name); name.substring(0, 3); System.out.println(proper name + " has " + proper name.length + " letters"); } } - Copy and paste the code into jGrasp and see if you can set up the errors.
Practise - respond
- line 5:
nextStringshould benext - line ix:
stringshould beString - line ix:
nameshould not be in quotes - line 10:
Whitakershould exist in quotes - line 10: cannot compare strings with
==; must apply.equals - line thirteen: cannot telephone call
replacewithout specifying a string object (name) - line fourteen:
toUppercaseshould betoUpperCase - line 14:
proper noun.should come beforetoUpperCase, non passed as a parameter to it - line 14: must say
proper noun =to shop the result oftoUpperCase - line 15: must say
name =to store the result ofsubstring - line xvi: must use parentheses
()when callinglength
Practise - Corrected version
public course StringOops { public static void master(String[] args) { Scanner panel = new Scanner(System.in); System.out.print("Blazon your name: "); String name = console.next(); process(name); } public static void process(String "name") { if (name.equals("Whitaker")) { System.out.println("You lot must exist really awesome."); } name = name.replace("a", "e"); proper name = name.toUpperCase(); name = proper name.substring(0, three); System.out.println(name + " has " + proper noun.length() + " letters"); } } Cumulative algorithms
- A cumulative algorithm is one where you lot incrementally accumulate a larger value by repeatedly adding, multiplying, etc., and storing the result into a variable over and over.
- Primal aspect of a cumulative algorithm: A loop, and a variable declared outside the loop whose value is modified inside the loop.
- Case: Cumulative algorithm to sum the numbers one-100:
int sum = 0; for (int i = 1; i <= 100; i++) { sum = sum + i; } System.out.println(sum); - Some of the post-obit issues ask yous to write cumulative algorithms.
Exercise : repl
- Write a method named
replthat accepts aStringand a number of repetitions every bit parameters and returns theStringconcatenated that many times. For example, the callrepl("hello", 3)returns"hellohellohello". If the number of repetitions is 0 or less, an empty string is returned. - Endeavor solving this problem in Practice-Information technology! using the link above.
- (Hint: This is best solved with a cumulative algorithm. Commencement with an empty string and build it upwardly piece past slice.)
Practice : longestName
Write a method named longestName that reads names typed by the user and prints the longest proper name (the proper name that contains the almost characters) in the format shown beneath. Your method should accept a panel Scanner and an integer due north as parameters and should and then prompt for n names.
A sample execution of the call longestName(panel, 4) might look like the following:
name #i? roy proper name #2? DANE proper name #three? sTeFaNiE proper name #4? Erik Stefanie'due south name is longest
Effort to solve this problem in Exercise-It: click on the bank check-marking above!
Exercise : swapPairs
- Write a method named
swapPairsthat accepts aCordas a parameter and returns thatStringwith each pair of adjacent letters reversed. If theStringhas an odd number of messages, the last letter is unchanged. For example, the phone callswapPairs("forget")should return"ofgrte"and the callswapPairs("hello there")should render"ehll ohtree". - Try solving this problem in Do-It! using the link above.
Exercise : jGRASP Debugger
We are going to practice using the jGRASP debugger with Hailstone.java. This program computes a sequence of integers called a hailstone sequence. (This is related to an unsolved problem in mathematics known as the Collatz Conjecture.)
continued on the next slide...
Exercise - Values of value
- For this practice you will trace the starting time telephone call:
printHailstoneMaxMin(7, 10); - Set a breakpoint
that will allow you to decide the outset several distinct values of the variable valueequally the loop executes.
| # | value |
|---|---|
| kickoff value | 7 |
| second value | 22 |
| third value | eleven |
| fourth value | 34 |
| fifth value | 17 |
| sixth value | 52 |
continued on the next slide...
Exercise - Values of min
- Now you will trace the second telephone call:
printHailstoneMaxMin(vii, 20); - Clear your previous breakpoint by clicking on it a 2d fourth dimension, and so set a new breakpoint for the second method phone call, and resume execution.
- Use your new breakpoint to determine the offset several singled-out values of
minduring the second telephone call.
| # | min |
|---|---|
| get-go value | 7 |
| second value | v |
| third value | 4 |
| fourth value | ii |
| fifth value | 1 |
Practice : hopscotch
Write a method named hopscotch that accepts an integer parameter for a number of "hops" and prints a hopscotch board of that many hops.
For example, the call hopscotch(three); would produce the post-obit output:
i 2 3 four 5 6 7 8 9 10
Try to solve this problem in Practice-It: click on the check-mark to a higher place!
If you lot finish them all...
If you finish all the exercises, try out our Practice-Information technology web tool. Information technology lets you solve Java problems from our Edifice Java Programs textbook.
You lot tin view an exercise, type a solution, and submit it to come across if y'all have solved it correctly.
Choose some problems from the book and try to solve them!
Source: https://www.buildingjavaprograms.com/labs/2012/lab4.shtml
0 Response to "Write a Static Method Named Longestname That Reads Names"
Postar um comentário