Computer Science Courses
Related sites
Lab 4 |
Get more experience in using String classes and arrays,and learn how to process a text using String's methods like split()
(use of another class suitable for such role,java.util.StringTokenizer
, is discouraged due toits deprecated status).
Given the array:
int num[] = {1,2,3,6,8,10,12,14,15,17,19,21};
Write a program that inspects each element of the array and does thefollowing:
If the number is divisible by 2 (num % 2 == 0) then print out "The number is divisible by 2".
If the number is divisible by 3 (num % 3 == 0) then print out "The number is divisible by 3".
If the number is divisible by 5 (num % 5 == 0) then print out "The number is divisible by 5".
Then modify the program so that this time the numbers are read in from the command line, ie, if your program is called ListNonPrimes then you will enter a command like:
% java ListNonPrimes 1 2 3 4 5 6 9 12 15 18 19
Additional: A Unix/Linux redirection facility, when the standard input can beread from a file, and the standard output (or, standard error channel) can bewritten to a file (either overwriting content in an already existing file, orappending new content destined to the standard output), can be very useful ifyou need to run the same program many times, and want to have an easier opportunity to control what is going into the program as a command-line input(to edit a file from which an input is redirected is simpler than edit thecommand-line every time; more importantly, it is easier when you run the sameprogram multiple times using a shell script).
To discover the redirection facility, first changethe code in ListNonPrimes.java
so it reads in the integers fromthe standard input at the program request:
% java ListNonPrimes Type in integers: 1 2 3 4 5 6 9 12 15 18 19
(just as above — all the numbers at once, blue means the user typing). Then make the programto read in the numbers (Scanner.nextLine()
method is most suitable), examine the numbers one-by-one, and print the same output as above.The change in the program should be minimal: instead of using args
array of strings, use String.split
to obtain an array of strings, by splitting the string returned by Scanner; the rest is then processed as before.
Typing the same input into a program when you run it multiple times isawkward. Therefore, learn how to explore the shell (command-line) redirectingfacilities. First,copy the command-line arguments into a plain text file —call it data.in
, and run your program as follows:
then you should see the same outcome. The standard output/error redirection is achieved with the% java ListNonPrimes < data.in
>
operator — the output is writteninto a file (anew if the file already exists), or, if used with the "append"redirection >>
, the output is added to file if italready exists (the latter is particularly useful for logging informationwhich a long running program, like an OS, or a server, continuouslygenerates to the standard output/error). Try this:and examine the result; try the double-redirection, too.% java ListNonPrimes < data.in > data.out
Write a program which reads in a string of ten characters or less and copies each character in the string to an array of characters:
char[] charArray = new char[10];
Note: You may find the charAt() method of String objectsto be useful. You probably use it as follows:
String s = "hello"; char firstChar=s.charAt(0);
What happens if you enter more than ten characters? Can you guardagainst this possibility using an if branch?Try to rewrite your program to quit with a warning message if more than ten characters are entered.
Write a program which will prompt a user toinput their full name. Then write this name back out again with thesurname first followed by a comma and then the first two names:
For example, the program would respond to the input:
John Stuart Average
by typing
Average, John Stuart
You can assume that the user will input 3 names.
There are two ways of writing this program.
You can just read in a string and then search that string for spaces (a single space," "
, or multiple spaces) which separate the names. This will involve a lot of counting and careful referencing to make sure that you split up the string properly. It is very good practice.
A better way is to use java.util.Scanner
class (see examples from the lecture , and discover more applications of this very useful class by reading the textbook, and/or API documentation). Here you need to create a Scanner instance and attach it to the standard input (similar to the example , a version of , discussed in lectures, in which java.io.StreamInput
was used):
String input = new Scanner(System.in).nextLine(); String[] names = input.split("\\s+");
java.lang.String
and java.util.Scanner
are two very important classes, and it pays to practice the methods the provide to process various text data. You will find it much easier to learn effective use of standard API, and then use them constantly in your code, then to descent to a low level of programming and reinvent the wheel again and again.
Practice the use of Scanner with non-default settings for token separators (aka, delimiters), when the read-in text is split into tokens not against the whitespace delimiter, but against a different string, or a pattern. Write a short program which reads in a text consisting of words and numbers in which that latter were meant to mark the line count, but for some reason the formatting had got messed up, and now the entire text is one very long line with numbers and words mixed up. Try to make Scanner to split the lines of text and restore the original format. As example, use the file (you can assume that the only numbers which occur in this text are the line number markers).
Delimiters can be reset many times during the life of the scanner object; can you think of a problem, where the possibility to adjust the delimiter based on an already read in data be useful.
Lab 4 |
Updated: Sun 12 Jun 2016 17:27:37 AEST • Responsible Officer: JavaScript must be enabled to display this email address. • Page Contact:
+61 2 6125 5111
The Australian National University, Canberra
CRICOS Provider : 00120C ABN : 52 234 063 906