Java Program for Reading a String in Loops

Affiliate six  Loops and Strings

Computers are oft used to automate repetitive tasks, such equally searching for text in documents. Repeating tasks without making errors is something that computers do well and people do poorly.

In this chapter, you'll larn how to use while and for loops to add repetition to your code. We'll also take a first expect at String methods and solve some interesting problems.

vi.i  The while Statement

Using a while statement, we tin echo the same code multiple times:

int n = 3; while (n > 0) { System.out.println(n); n = due north - 1; } System.out.println("Blastoff!");

Reading the code in English sounds like this: "Starting time with n set to three. While northward is greater than 0, print the value of north, and reduce the value of north by 1. When you get to 0, impress Blastoff!"

The output is shown here:

The catamenia of execution for a while statement is as follows:

  1. Evaluate the status in parentheses, yielding true or simulated .
  2. If the condition is false , skip the following statements in braces.
  3. If the condition is true , execute the statements and become dorsum to pace 1.

This type of period is called a loop, considering the last step "loops dorsum around" to the first. Figure six.i shows this idea using a flowchart.

Figure 6.one: Flow of execution for a while loop.

The body of the loop should change the value of one or more variables so that, eventually, the condition becomes faux and the loop terminates. Otherwise, the loop volition echo forever, which is chosen an space loop:

int n = three; while (n > 0) { System.out.println(due north); // n never changes }

This example will impress the number 3 forever, or at to the lowest degree until you stop the programme. An endless source of amusement for computer scientists is the ascertainment that the directions on shampoo, "Lather, rinse, repeat," are an infinite loop.

In the commencement example, we can show that the loop terminates when north is positive. Only in general, it is not so easy to tell whether a loop terminates. For example, this loop continues until n is 1 (which makes the condition false ):

while (due north != one) { Organization.out.println(northward); if (n % ii == 0) { // north is even n = northward / 2; } else { // north is odd n = 3 * n + ane; } }

Each fourth dimension through the loop, the program displays the value of due north and and then checks whether information technology is even or odd. If it is even, the value of n is divided past ii. If it is odd, the value is replaced by threenorthward+1. For example, if the starting value is 3, the resulting sequence is 3, 10, v, 16, 8, 4, 2, 1.

Since n sometimes increases and sometimes decreases, there is no obvious proof that n will e'er accomplish 1 and that the programme will e'er stop. For some values of n, such as the powers of two, we tin can prove that it terminates. The previous example ends with such a sequence, starting when due north is 16 (or ii4).

The hard question is whether this programme terminates for all values of north. So far, no one has been able to show it or disprove it! For more information, see https://en.wikipedia.org/wiki/Collatz_conjecture.

6.ii  Increment and Decrement

Hither is another while loop example; this 1 displays the numbers one to 5:

int i = ane; while (i <= v) { Organisation.out.println(i); i++; // add 1 to i }

Assignments like i = i + 1 don't oft appear in loops, considering Java provides a more than concise way to add together and subtract by one. Specifically, ++ is the increment operator; information technology has the same event every bit i = i + one. And -- is the decrement operator; information technology has the same outcome every bit i = i - 1.

If yous desire to increase or decrement a variable past an amount other than 1, y'all can use += and -=. For example, i += 2 increments i by 2:

int i = two; while (i <= 8) { System.out.impress(i + ", "); i += 2; // add ii to i } System.out.println("Who do nosotros appreciate?");

And the output is as follows:

2, 4, 6, 8, Who do nosotros appreciate?

six.3  The for Statement

The loops nosotros accept written then far have three parts in common. They outset past initializing a variable, they have a condition that depends on that variable, and they do something within the loop to update that variable.

Running the same code multiple times is called iteration. Information technology'south and then common that at that place is some other statement, the for loop, that expresses it more concisely. For example, we can rewrite the 2-4-6-eight loop this fashion:

for (int i = 2; i <= viii; i += 2) { System.out.print(i + ", "); } Organisation.out.println("Who do we appreciate?");

for loops have 3 components in parentheses, separated past semicolons: the initializer, the status, and the update:

  1. The initializer runs one time at the very beginning of the loop. Information technology is equivalent to the line before the while statement.
  2. The condition is checked each time through the loop. If information technology is false , the loop ends. Otherwise, the trunk of the loop is executed (again).
  3. At the end of each iteration, the update runs, and we get back to footstep 2.

The for loop is often easier to read because information technology puts all the loop-related statements at the elevation of the loop. Doing then allows you to focus on the statements inside the loop torso. Effigy 6.two illustrates for loops with a flowchart.

Figure 6.2: Flow of execution for a for loop.

There is another difference between for loops and while loops: if you declare a variable in the initializer, it exists only within the for loop. For example:

for (int n = three; north > 0; n--) { System.out.println(n); } System.out.println("northward is now " + n); // compiler fault

The last line tries to display northward (for no reason other than demonstration), merely it won't piece of work. If you need to utilize a loop variable outside the loop, you have to declare it outside the loop, like this:

int due north; for (n = 3; n > 0; n--) { System.out.println(n); } System.out.println("n is at present " + n);

Notice that the for statement does non say int northward = 3. Rather, it simply initializes the existing variable north.

six.4  Nested Loops

Like conditional statements, loops can be nested one within the other. Nested loops permit you to iterate over two variables. For instance, nosotros can generate a "multiplication table" like this:

for (int x = ane; x <= 10; x++) { for (int y = 1; y <= 10; y++) { Arrangement.out.printf("%4d", x * y); } System.out.println(); }

Variables like x and y are called loop variables, because they control the execution of a loop. In this example, the start loop ( for 10) is known as the "outer loop", and the second loop ( for y) is known as the "inner loop".

Each loop repeats its corresponding statements 10 times. The outer loop iterates from i to x just once, but the inner loop iterates from 1 to x each of those 10 times. As a result, the printf method is invoked 100 times.

The format specifier %4d displays the value of x * y padded with spaces and then information technology'southward iv characters wide. Doing so causes the output to align vertically, regardless of how many digits the numbers have:

ane two 3 four 5 6 7 8 9 10 2 4 6 8 ten 12 14 16 18 20 three half-dozen 9 12 15 18 21 24 27 30 4 viii 12 16 20 24 28 32 36 40 5 10 15 xx 25 30 35 40 45 50 half dozen 12 xviii 24 xxx 36 42 48 54 lx 7 14 21 28 35 42 49 56 63 lxx 8 16 24 32 40 48 56 64 72 fourscore 9 xviii 27 36 45 54 63 72 81 90 10 xx 30 twoscore 50 60 70 80 xc 100

Information technology'south important to realize that the output is displayed row by row. The inner loop displays a unmarried row of output, followed by a newline. The outer loop iterates over the rows themselves. Another manner to read nested loops, like the ones in this example, is: "For each row x, and for each column y, …"

6.v  Characters

Some of the most interesting problems in information science involve searching and manipulating text. In the next few sections, we'll hash out how to employ loops to strings. Although the examples are short, the techniques piece of work the same whether you have one give-and-take or one million words.

Strings provide a method named charAt. It returns a char , a data type that stores an individual graphic symbol (every bit opposed to strings of them):

String fruit = "assistant"; char letter = fruit.charAt(0);

The argument 0 means that we want the character at index 0. Cord indexes range from 0 to n−1, where n is the length of the cord. So the character assigned to letter is 'b' :

Characters piece of work similar the other data types you have seen. You can compare them using relational operators:

if (letter == 'A') { System.out.println("It's an A!"); }

Grapheme literals, like 'A' , appear in single quotes. Unlike string literals, which appear in double quotes, grapheme literals can contain just a single character. Escape sequences, like '\t' , are legal because they represent a unmarried character.

The increment and decrement operators too piece of work with characters. So this loop displays the messages of the alphabet:

System.out.print("Roman alphabet: "); for (char c = 'A'; c <= 'Z'; c++) { System.out.impress(c); } System.out.println();

The output is shown here:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Java uses Unicode to represent characters, then strings can shop text in other alphabets similar Cyrillic and Greek, and non-alphabetic languages like Chinese. You can read more about it at the Unicode website (https://unicode.org/).

In Unicode, each character is represented past a "lawmaking betoken", which you can think of as an integer. The code points for majuscule Greek messages run from 913 to 937, then we tin can display the Greek alphabet like this:

Organisation.out.print("Greek alphabet: "); for (int i = 913; i <= 937; i++) { System.out.impress((char) i); } Organisation.out.println();

This instance uses a type cast to catechumen each integer (in the range) to the corresponding character. Try running the code and see what happens.

6.half-dozen  Which Loop to Utilize

for and while loops have the aforementioned capabilities; whatsoever for loop can exist rewritten as a while loop, and vice versa. For instance, we could take printed letters of the alphabet by using a while loop:

System.out.impress("Roman alphabet: "); char c = 'A'; while (c <= 'Z') { Arrangement.out.print(c); c++; } Arrangement.out.println();

You might wonder when to use one or the other. Information technology depends on whether you know how many times the loop volition repeat.

A for loop is "definite", which means we know, at the beginning of the loop, how many times it will repeat. In the alphabet instance, nosotros know it volition run 26 times. In that case, it's better to use a for loop, which puts all of the loop control code on one line.

A while loop is "indefinite", which ways nosotros don't know how many times information technology will echo. For example, when validating user input as in Section 5.nine, information technology's incommunicable to know how many times the user will enter a incorrect value. In this case, a while loop is more appropriate:

System.out.print("Enter a number: "); while (!in.hasNextDouble()) { Cord word = in.next(); System.err.println(discussion + " is not a number"); System.out.print("Enter a number: "); } double number = in.nextDouble();

It's easier to read the Scanner method calls when they're non all on one line of code.

half-dozen.7  String Iteration

Strings provide a method called length that returns the number of characters in the string. The post-obit loop iterates the characters in fruit and displays them, one on each line:

for (int i = 0; i < fruit.length(); i++) { char letter = fruit.charAt(i); Arrangement.out.println(letter); }

Because length is a method, you have to invoke information technology with parentheses (at that place are no arguments). When i is equal to the length of the string, the condition becomes faux and the loop terminates.

To find the final letter of the alphabet of a string, you might be tempted to do something like the post-obit:

int length = fruit.length(); char last = fruit.charAt(length); // wrong!

This code compiles and runs, only invoking the charAt method throws a StringIndexOutOfBoundsException. The trouble is that there is no sixth alphabetic character in "assistant" . Since we started counting at 0, the half-dozen letters are indexed from 0 to 5. To get the last grapheme, you have to decrease 1 from length:

int length = fruit.length(); char last = fruit.charAt(length - one); // correct

Many string algorithms involve reading 1 string and edifice another. For instance, to contrary a string, we can concatenate one character at a time:

public static String opposite(String s) { String r = ""; for (int i = southward.length() - 1; i >= 0; i--) { r += s.charAt(i); } return r; }

The initial value of r is "" , which is an empty cord. The loop iterates the indexes of s in reverse order. Each time through the loop, the += operator appends the next graphic symbol to r. When the loop exits, r contains the characters from southward in reverse order. Then the result of reverse("banana") is "ananab" .

6.8  The indexOf Method

To search for a specific character in a string, you could write a for loop and employ charAt as in the previous section. Yet, the String grade already provides a method for doing just that:

Cord fruit = "banana"; int index = fruit.indexOf('a'); // returns 1

This example finds the index of 'a' in the cord. But the letter of the alphabet appears three times, so information technology'south not obvious what indexOf might do. Co-ordinate to the documentation, it returns the index of the first appearance.

To find subsequent appearances, y'all tin employ another version of indexOf, which takes a second argument that indicates where in the string to offset looking:

int alphabetize = fruit.indexOf('a', ii); // returns 3

To visualize how indexOf and other String methods work, it helps to draw a picture like Figure half dozen.iii. The previous code starts at index 2 (the start 'northward' ) and finds the side by side 'a' , which is at index 3.

Figure 6.3: Memory diagram for a String of 6 characters.

If the character happens to appear at the starting index, the starting index is the answer. Then fruit.indexOf('a', 5) returns v. If the grapheme does not announced in the cord, indexOf returns -1. Since indexes cannot be negative, this value indicates the character was not found.

Yous can also use indexOf to search for an entire string, not just a single character. For instance, the expression fruit.indexOf("nan") returns 2.

half-dozen.nine  Substrings

In improver to searching strings, we often need to extract parts of strings. The substring method returns a new string that copies letters from an existing string, given a pair of indexes:

  • fruit.substring(0, 3) returns "ban"
  • fruit.substring(ii, 5) returns "nan"
  • fruit.substring(vi, 6) returns ""

Observe that the grapheme indicated past the 2nd index is not included. Defining substring this way simplifies some mutual operations. For instance, to select a substring with length len, starting at index i, yous could write fruit.substring(i, i + len).

Like most cord methods, substring is overloaded. That is, there are other versions of substring that have different parameters. If it'south invoked with one argument, it returns the letters from that index to the end:

  • fruit.substring(0) returns "assistant"
  • fruit.substring(2) returns "nana"
  • fruit.substring(six) returns ""

The commencement instance returns a copy of the entire cord. The 2d example returns all but the offset 2 characters. As the last instance shows, substring returns the empty string if the statement is the length of the string.

Nosotros could also use fruit.substring(two, fruit.length() - 1) to get the result "nana" . But calling substring with ane argument is more convenient when you desire the end of the cord.

6.ten  String Comparing

When comparing strings, information technology might be tempting to employ the == and != operators. Only that will almost never piece of work. The post-obit code compiles and runs, simply information technology always displays Bye! regardless what the user types.

System.out.print("Play over again? "); Cord answer = in.nextLine(); if (answer == "yep") { // wrong! Organisation.out.println("Let's go!"); } else { Organization.out.println("Good day!"); }

The problem is that the == operator checks whether the ii operands refer to the same object. Fifty-fifty if the reply is "yeah" , it will refer to a dissimilar object in memory than the literal string "aye" in the code. Yous'll learn more than almost objects and references in the next chapter.

The correct way to compare strings is with the equals method, like this:

if (answer.equals("yeah")) { Organisation.out.println("Let's go!"); }

This example invokes equals on reply and passes "yes" as an argument. The equals method returns true if the strings contain the aforementioned characters; otherwise, it returns false .

If two strings differ, we can utilize compareTo to run into which comes offset in alphabetical society:

String name1 = "Alan Turing"; String name2 = "Ada Lovelace"; int diff = name1.compareTo(name2); if (diff < 0) { System.out.println("name1 comes before name2."); } else if (unequal > 0) { Organisation.out.println("name2 comes earlier name1."); } else { System.out.println("The names are the same."); }

The return value from compareTo is the difference between the starting time characters in the strings that are not the same. In the preceding code, compareTo returns positive 8, because the 2d letter of "Ada" comes before the second letter of "Alan" past eight letters.

If the kickoff cord (the one on which the method is invoked) comes before in the alphabet, the difference is negative. If it comes later in the alphabet, the difference is positive. If the strings are equal, their departure is goose egg.

Both equals and compareTo are case-sensitive. In Unicode, uppercase letters come up before lowercase letters. So "Ada" comes earlier "ada" .

6.xi  String Formatting

In Section 3.5, we learned how to use System.out.printf to display formatted output. Sometimes programs need to create strings that are formatted a certain way, only not display them immediately (or ever). For instance, the post-obit method returns a fourth dimension string in 12-hour format:

public static String timeString(int hour, int infinitesimal) { Cord ampm; if (hour < 12) { ampm = "AM"; if (hour == 0) { hour = 12; // midnight } } else { ampm = "PM"; hour = hour - 12; } return String.format("%02d:%02d %s", hour, minute, ampm); }

Cord.format takes the same arguments equally Organisation.out.printf: a format specifier followed by a sequence of values. The main difference is that Arrangement.out.printf displays the outcome on the screen. String.format creates a new cord but does not display anything.

In this example, the format specifier %02d means "two-digit integer padded with zeros", then timeString(19, v) returns the string "07:05 PM" . Every bit an exercise, try writing two nested for loops (in main) that invoke timeString and display all possible times over a 24-hour period.

Be certain to skim through the documentation for String. Knowing what other methods are there will assist you avoid reinventing the wheel. The easiest style to find documentation for Java classes is to do a spider web search for "Java" and the name of the class.

half-dozen.12  Vocabulary

loop:
A statement that executes a sequence of statements repeatedly.
loop torso:
The statements inside the loop.
infinite loop:
A loop whose status is e'er true.
increase:
Increase the value of a variable.
decrement:
Decrease the value of a variable.
iteration:
Executing a sequence of statements repeatedly.
loop variable:
A variable that is initialized, tested, and updated in gild to control a loop.
index:
An integer variable or value used to bespeak a character in a string.
Unicode:
An international standard for representing characters in near of the earth's languages.
empty cord:
The string "" , which contains no characters and has a length of nix.
overloaded:
2 or more methods with the same proper name but different parameters.

half dozen.13  Exercises

The code for this affiliate is in the ch06 directory of ThinkJavaCode2. See page ?? for instructions on how to download the repository. Before you start the exercises, nosotros recommend that you compile and run the examples.

If yous have not already read Appendix A.vi, at present might be a good fourth dimension. Information technology describes the DrJava debugger, which is a useful tool for visualizing the flow of execution through loops.

Exercise ane

Consider the post-obit methods (main and loop):

  1. Describe a tabular array that shows the value of the variables i and n during the execution of loop. The table should contain one cavalcade for each variable and one line for each iteration.
  2. What is the output of this program?
  3. Can you evidence that this loop terminates for any positive value of n?

public static void main(Cord[] args) { loop(x); } public static void loop(int n) { int i = n; while (i > 1) { System.out.println(i); if (i % two == 0) { i = i / two; } else { i = i + ane; } } }

Exercise two

Permit'due south say you are given a number, a , and you desire to find its square root. I way to practise that is to starting time with a rough judge about the answer, x 0 , and then meliorate the guess by using this formula:

For case, if we want to detect the foursquare root of 9, and we start with x 0 = 6, then x 1 = (6 + 9/6) / 2 = 3.75, which is closer. Nosotros can repeat the procedure, using ten 1 to calculate x two , and so on. In this case, 10 2 = 3.075 and x 3 = 3.00091. And so the repetition converges quickly on the correct answer.

Write a method chosen squareRoot that takes a double and returns an approximation of the square root of the parameter, using this technique. You should not use Math.sqrt.

Every bit your initial judge, you should use a/2. Your method should iterate until it gets two consecutive estimates that differ past less than 0.0001. You can utilise Math.abs to calculate the absolute value of the difference.

Exercise iii

I way to evaluate exp(−x two) is to use the space series expansion:

exp(−x 2) = 1 −x 2 +x four/2 −x 6/6 + …

The i th term in this serial is (−1) i x iii / i!. Write a method named gauss that takes x and north every bit arguments and returns the sum of the commencement n terms of the series. You should not use factorial or pow.

Do iv

A discussion is said to exist "abecedarian" if the letters in the word appear in alphabetical lodge. For example, the post-obit are all six-alphabetic character English abecedarian words:

abdest, acknow, acorsy, adempt, adipsy, agnosy, befist, behint, beknow, bijoux, biopsy, cestuy, chintz, deflux, dehors, dehort, deinos, diluvy, dimpsy

Write a method chosen isAbecedarian that takes a String and returns a boolean indicating whether the give-and-take is abecedarian.

Exercise 5

A word is said to be a "doubloon" if every alphabetic character that appears in the discussion appears exactly twice. Here are some example doubloons constitute in the lexicon:

Abba, Anna, appall, appearer, appeases, arraigning, beriberi, bilabial, boob, Caucasus, coco, Dada, deed, Emmett, Hannah, horseshoer, intestines, Isis, mama, Mimi, murmur, noon, Otto, papa, peep, reappear, redder, sees, Shanghaiings, Toto

Write a method called isDoubloon that takes a string and checks whether it is a doubloon. To ignore case, invoke the toLowerCase method earlier checking.

Do vi

In Scrabble 1 each player has a prepare of tiles with messages on them. The object of the game is to employ those letters to spell words. The scoring system is complex, but longer words are normally worth more than shorter words.

Imagine you are given your set of tiles as a string, like "quijibo" , and you are given some other string to test, like "jib" .

Write a method called canSpell that takes two strings and checks whether the set of tiles tin can spell the give-and-take. Y'all might have more than 1 tile with the same letter, simply you lot can use each tile just in one case.


1

Scrabble is a registered trademark owned in the The states and Canada past Hasbro Inc., and in the rest of the globe past J. W. Spear & Sons Limited of Maidenhead, Berkshire, England, a subsidiary of Mattel Inc.

andersonthembeen.blogspot.com

Source: https://books.trinket.io/thinkjava2/chapter6.html

0 Response to "Java Program for Reading a String in Loops"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel