如何在控制台中每行打印特定数量的字符?

时间:2016-10-02 17:30:08

标签: java

我正在尝试在控制台中每行打印80个字符。我每行可以打印80个字符,但是当我在字符串中剩下少于80个字符时,它们不会打印出来。我怎么能补救这个?

public void output(String plainText, String cipherText, String iv, String key, String filename) {
        System.out.println("CBC Vigenere by ");
        System.out.println("Plaintext file name: " + filename);
        System.out.println("Vigenere Keyword: " + key);
        System.out.println("Initialization vector: " + iv + "\n");
        //This is the code for printing 80 char per line
        System.out.println("Clear Text: \n");
        int j = 0;
        String output = "";
        for (int i = 0; i < plainText.length(); i++) {
            j++;
            output = output + plainText.charAt(i);
            if (j == 80) {
                System.out.println(output);
                output = "";
                j=0;
            }else{
               //an attempt to print the remaining characters 
               // System.out.println(output);
            }


        }
        //same process as above.
        System.out.println(" \n Cipher Text:\n ");
        j = 0;
        output = "";
        for (int i = 0; i < cipherText.length(); i++) {
            j++;
            output = output + cipherText.charAt(i);
            if (j == 80) {
                System.out.println(output);
                output = "";
                j = 0;

            } else if ((cipherText.length() - i) <= 80) {
                if (j == 80) {
                    if (j == (cipherText.length() - i)) {
                        //if (j == 80) {
                        System.out.println(output);
                        output = "";
                        j = 0;
                        System.out.println((output));

                        j = 0;
                    }
                }
            }
        }
        System.out.println("\n\nNumber of characters in clean plaintext file:  " + (plainText.length() - padding));
        System.out.println("Block Size: " + key.length());
        System.out.println("Number of pad Characters added: " + padding);

    }

输出:

 Clear Text:

csthesciencethatdealswiththetheoryandmethodsofprocessinginformationindigitalcomp
utersthedesignofcomputerhardwareandsoftwareandtheapplicationsofcomputersitthedev
elopmentimplementationandmaintenanceofcomputerhardwareandsoftwaresystemstoorgani
zeandcommunicateinformationelectronicallyabbreviationitcomputersaremanmadetoolst
hataidusinsolvingotherproblemsabiologististryingtofigureouthowlifeworksphysicist
sandchemistsaretryingtofigureouthowitemsreactinouruniversemathematiciansaretryin
gtofigureoutrulesformanmadesystemsanyresearchproblemthatmayimproveacomputerscapa
bilityofhelpingsolveaproblemoranyresearchproblemthatshedslightaboutanewwaytodoso
methingwithacomputerispartofcsmostexcitingresearchmedicalapplicationsexpertsyste
msfordiagnosisremotesurgerynanodeviceswithcomputingpowertodelivermedicineetcwene
edhelptryingtocreateacomprehensiveemraccessibletotherightpeopleonlycarsthatcandr
ivethemselvesseemslikethebestwayweknowhowtosolvelotsofproblemsisbythrowinglotsof
computingpowerattheminsteadoflookingforelegantsolutionsthisdoesntsoundexcitingbu
titwillbeexcitingwhentheresultsareachievediewatsoncsstudentstendtofindjobswheret
heyprogramatleastsomeintheprocesstheyaresolvingproblemschallengesitsimpossibleto
teachallthenewlanguagestoysultimatelywejustneedtoteachourstudentshowtothinksotha
ttheycanpickupnewthingsontheirownourbiggestchallengeisgettingthemtobuyintothatet

 Cipher Text:

qiqxbxknvieuejlkvwcpbtquevshswdsbyitsndorkbkwxswngygxwrkgfsbqvxwmsgiatpheilbuxnu
ovzuyvmhwtvjiedrmnfkglrkfsddglexlsvsqfqjxiiqcbcqnyjvblktkjfeeaqklehghsfsutuiftqw
bpwmpyjzytumfgqbqjqzluspcjjzdaovvqeczpilbicjnibqzbcjavhqrqmdmhtgegjgjscscoxnkvel
kxrsbcwwpyjoswsihdtzrtyunqhczoipglabjjbcgkotmfovvwkseieszmvovataazltsolwviveqxpy
dgdosztziuhqztoobkbzmyixdgvsosvbkxctpjokdkdjizcncjozbbznupuepihytkwguytvhbgrphoi
nqhbqqbkqkqkxjikgqvlimdzsntmeifjtfwvwhphntudutoppoqjfmqlpxifiutoappzehyhfgqhondi
qjlwakbjmfngliduchxgqokirtcththfafhamzxzihgruoskadlxlmsnlvqljihejqqaluhwhifioqky
sokekkfxtjlgabnbiukgrdpzxsimdlkgpfaflnjxxuvqdjodosvtuiftemtahbokjmjudggknqnmxiwe
pqpfearegfundjwgxhigxgtorpmcvcoynzyehuhkbyzkywfvokhwrmauscozgppxpnkijunryqyqdqdc
wciygjvrimdmsmqyjujgiigwrvwqdlywjzyjjjmzmovkohpiedramexdxzhlzbbnzhkszcoxzjztcfwr
hcvonlnksamomkvjgrgdnnihegpvaqzgbsmmkuteeedulnworpfbdrqgqdbzxsiochhroqnrbzbjiesd
hgshgtztkmmylywkpkhaymybjkukuobuegvbqfebhcccxvzhrdrdmqipdyvkokdklqlfjbmrgfybybto
ckvhwildyateedleltwnlikjvrfnrgmcdsxgjchozamigjffxhxxssrtfjeuzgybybtdnoythjhzbnjp
jfjjycqlbxfhuijdwhkteusgqspuhvgdeplzzpksvdkpnxnxisrsqtreczczclwwwsiictspapdeodze
nqsnqjdikcrdjpqpqpljwzqaemalvvgvfwtiyqwcvynbcwptnpvigcfmtulnwijuikikxetasahjzvzr
zdgnuvmomdxyicakuyvgishtczbbtciwpxaqfuqlrlrgcsmthuscbrwtutuvehyixxsbsxsmhhyhtihq
hrvdanhidymqnnhzkayqseralbznomjqdmelmbzpkpkzyhqabvohdhqtqufpsqgczdumvsknkjkyrzca

我错过了字符串中的最后20个字符。添加它们的实用方法是什么?字符串大小会有所不同,因此它的大小并不总是相同。

3 个答案:

答案 0 :(得分:1)

如果output循环完成后for不为空,请将其打印出来。

答案 1 :(得分:0)

试试这个。

for (int i = 0, size = cipherText.length(); i < size; i += 80)
    System.out.println(cipherText.substring(i, Math.min(i + 80, size)));

答案 2 :(得分:0)

由于您连接了这么多字符串,因此您的代码效率极低。我建议将它分成长度为80的子串,然后打印出来。

final int lineLength = 80;
final int numLines = Math.ceil(plainText.length / lineLength);
String[] lines = new String[num_lines];
int charend;
for(int i=0, charini=0; i < numLines; i++) {
    charend = Math.min(charini + 80, plainText.lenght());
    lines[i] = plainText.substring(charini,charend);
    charini += lineLength;
}

// The print function
for(int i=0; i<lines.length; i++) {
    System.out.println(lines[i]);
}

另外,我建议您将代码拆分为方法,而不是将其复制两次。