I'm trying to get a txt file with only the alphabet and numbers writted. In the txt file there are also the non alphabet characters.
public class WordChanger2 {
static int input = 2; /// input line length
public static ArrayList<Character> str; /// a list containing characters.
public static PrintWriter output;
public void saveToFile(int size,int lineSize){
if(size == lineSize){
String s = "";
for (Character str1 : str) {
s+=str1;
}
output.println(s);
return;
}
for(char i = '0';i<='z';i++){ //from number 0 to lower z
str.add(i);
saveToFile(size+1,lineSize);
str.remove(str.size()-1);
System.out.println(str); //showing the Characters on console
}
}
public static void main(String[] args) throws FileNotFoundException {
int lineSize = input;
output = new PrintWriter("E:\\output.txt"); /// file path
str = new ArrayList<Character>();
WordChanger2 c = new WordChanger2();
c.saveToFile(0 ,lineSize);
output.close();
System.out.println("Done! check the Txt file on your E: drive");
}
}
Trying to get this:
00 \n01 \n02 \n03 \n04 \n05 \n06 \n07 \n08 \n09 \n0A \n0B \n0C \n0D \n0E \n0F \n0G \n0H \n0I \n0J \n0K \n0L \n0M \n0N \n0O \n0P \n0Q \n0R \n0S \n0T \n0U \n0V \n0W \n0X \n0Y \n0Z \n0a \n0b \n0c \n0d \n0e \n0f \n0g \n0h \n0i \n0j \n0k \n0l \n0m \n0n \n0o \n0p \n0q \n0r \n0s \n0t \n0u \n0v \n0w \n0x \n0y \n0z
Use Character#IsLetterOrDigit(char)
method in the for
loop It's quite explicit.
for(char i = '0';i<='z';i++){ //from number 0 to lower z
if (Character.IsLetterOrDigit(i) {
str.add(i);
saveToFile(size+1,lineSize);
str.remove(str.size()-1);
System.out.println(str); //showing the Characters on console
}
}
Use more loops:
for(char i = '0';i<='9';i++){ //from number 0 to 9
//do something
}
for(char i = 'A';i<='Z';i++){ //from letter A to Z
//do something
}
for(char i = 'a';i<='z';i++){ //from letter a to z
//do something
}
This could be improved to avoid to much code duplication
Create a String containing each letters and digits in the correct order and loop on this string to build the ouptut
String table = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (int i=0; i<table.size(); i++) {
str.add(table.charAt(i));
...
}
Side note: I think using recursive call to do what you are trying to is a bit overkill. Why not build a single string, appending characters in the loop and when the loop ends, write it where ever you want?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.