[英]Java - How to print from 0 to z without !@#$%^&*()?><":{}| letters, only alphabet and numbers
我正在尝试获取仅包含字母和数字的txt文件。 在txt文件中,还包含非字母字符。
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");
}
}
试图得到这个:
00\n 01\n 02\n 03\n 04\n 05\n 06\n 07\n 08\n 09\n 0A\n 0B\n 0C\n 0D\n 0E\n 0楼\n 0G\n 0小时\n 0I\n 0J\n 0K\n 0升\n 0M\n 0N\n 0O\n 0P\n 0Q\n 0R\n 0S\n 0T\n 0U\n 0伏\n 0W\n 0X\n 0年\n 0Z\n 0a\n 0b\n 0c\n 0天\n 0e\n 0f\n 0克\n 0小时\n 0i\n 0j\n 0k\n 0升\n 0米\n 0n\n 0度\n 0p\n 0q\n 0r\n 0秒\n 0吨\n 0u\n 0v\n 0w\n 0x\n 0年\n 0z
在for
循环中使用Character#IsLetterOrDigit(char)
方法非常明确。
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
}
}
使用更多循环:
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
}
可以对此进行改进,以避免过多的代码重复
创建一个包含每个字母和数字的正确顺序的字符串,并在此字符串上循环以构建输出
String table = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (int i=0; i<table.size(); i++) {
str.add(table.charAt(i));
...
}
旁注:我认为使用递归调用执行您要尝试的操作有点过分。 为什么不构建单个字符串,在循环中添加字符,然后在循环结束时,将其写入所需的任何位置?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.