More
on Strings
Converting
Strings to Char Arrays
A String's characters can be easily stored in a char array:
toCharArray() method
Example:
String str = "Mary";
char[] myChars = str.toCharArray();
for(int i = 0; i < myChars.length; i++)
System.out.println(myChars[i]);
Output:
M
a
r
y
Parsing
Strings to Numeric Types
- Convert Strings to type int or double with
Double.parseDouble(), Integer.parseInt()
Example:
String str1 = "3.5";
String str2 = "14";
double num1 = Double.parseDouble(str1);
int num2 = Integer.parseInt(str2);
System.out.println("sum of nums: " + (num1 + num2));
Output:
sum of nums: 17.5
Command Line
Arguments
- Header for main method: public static void
main(String[] args)
- main method takes an array of type String as its
arguments
- These arguments for main() are called "command
line arguments"
Example:
public class TryCommand
{
public static void main(String[] args)
{
// print the sum of the 2 integer
command line arguments
System.out.println("Sum: " +
(Integer.parseInt(args[0]) + Integer.parseInt(args[1])));
}
}
Sample Run: Compiling and Excuting
from the command line
javac TryCommand.java
java TryCommand 3 5
Output:
Sum: 8
Reading
Text from a File
- Associate a File object with your text file
- The File class is in the java.io package
- Many useful methods from class File:
- exists(): returns true or false - indicates
whether or not the file or directory represented by the File object
exists or not
- canRead(): returns true or false - indicates
whether or not the associated file is readable
- canWrite(): indicates whether or not the
associated file is writeable
- isDirectory(): returns true if File object
represents a directory
- isFile()
- getAbsolutePath(): returns complete path of file
or directory
- getName(): returns the name of the associated
file
- lastModified(): returns time the file was last
modified (as a long) - use the Date class to make this time
user-friendly
- delete(): deletes this file, and returns true if
the delete operation succeeds
Example:
File myFile = new File("sample.txt");
Scanner scan = new Scanner(myFile);
// print first token in file
System.out.println(scan.next());