File Handling
import java.util.Scanner;
import java.io.FileReader;
import java.io.PrintWriter;
public class files {
public static void main (String[] args) throws FileNotFoundException {
String line, parts[];
int x;
Scanner infile = new Scanner(new FileReader("inputfile.txt"));
PrintWriter outfile = new PrintWriter("outputfile.txt");
while(infile.hasNext()) {
line = infile.nextLine();
parts = line.split(":");
for (x = 0; x < parts.length; x++)
outfile.println(parts[x]);
}
outfile.close();
infile.close();
}
}
Sample input file
thing1:thing2:thing3:thing4:thing5:thing6:thing7:thing8 piece1:piece2:piece4:piece6:piece9:piece12
Converting Strings and Numbers (SSN Style)
public class Ssn {
public static void main (String[] args) {
String ssn = "023050089", stringssn;
int s, f, m, l;
s = Integer.parseInt(ssn);
f = s / 1000000; // 123
s = s % 1000000; // 456789
m = s / 10000; // 45
l = s % 10000; // 6789
System.out.println("f = " + f);
System.out.println("m = " + m);
System.out.println("l = " + l);
System.out.printf("%03d-%02d-%04d%n", f, m ,l);
stringssn = String.format("%03d-%02d-%04d%n", f, m ,l);
System.out.printf(stringssn);
}
}
Example 2: SSN formatting using integers.
public class Ssn2 {
public static void main (String[] args) {
// 023050089
String ssn = "023050089", stringssn;
String f, m, l;
f = ssn.substring(0,3);
m = ssn.substring(3,5);
l = ssn.substring(5);
System.out.println("f = " + f);
System.out.println("m = " + m);
System.out.println("l = " + l);
stringssn = f + "-" + m + "-" + l;
System.out.println(stringssn);
}
}
Example 3: SSN formatting using String.
Using split()
public class Split {
public static void main (String[] args) {
String line = "part1:part2:part3:part4:part5";
String[] parts;
int x;
parts = line.split(":");
for (x = 0; x < parts.length; x++)
System.out.println(parts[x]);
}
}
Example 4: Using split()
to break up a string with delimiters.
Random numbers
public class Random {
public static void main (String[] args) {
int x, r;
for (x = 1; x <= 10; x++) {
r = (int)(Math.random() * 54 + 45);
System.out.println(r);
}
}
}
// 45 -> 98
//-45 -45
//---- ----
// 0 53