簡體   English   中英

Java-如何在不使用!@#$%^&*()的情況下從0打印到z?> <“:{} |字母,僅包括字母和數字

[英]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 

解決方案1:

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
    }
}

解決方案2:

使用更多循環:

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
}

可以對此進行改進,以避免過多的代碼重復

解決方案3 :(由Andy Turner提供)

創建一個包含每個字母和數字的正確順序的字符串,並在此字符串上循環以構建輸出

String table = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (int i=0; i<table.size(); i++) {
    str.add(table.charAt(i));
    ...
}

旁注:我認為使用遞歸調用執行您要嘗試的操作有點過分。 為什么不構建單個字符串,在循環中添加字符,然后在循環結束時,將其寫入所需的任何位置?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM