2015-07-14 2 views
0

Хорошо, я пытаюсь добавить новую строку каждые три буквы. Цель состоит в том, чтобы иметь 20 рядов рандомизированных заглавных букв. С 3 заглавными буквами в строке.Добавление новой строки Каждые три цифры

Я рандомизировал числа, а затем преобразовал их в строку. Затем выводится строка. У меня есть 60 случайных заглавных букв в одной прямой строке, но я не могу понять, как добавить новые строки, поскольку каждая буква рандомизирована. Я не могу сказать java, что искать, как раньше. Я попытался использовать оператор if и добавить «/ n» в конце, но он просто стал грязным и трудным. И команды оператора я не мог понять, как применять все три буквы.

Вот код, который я до сих пор под «wrightRandomCodesToFile»

package mp05; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.util.Random; 
import java.util.Scanner; 

public class Main { 
    private static final int PRODUCT_COUNT = 20; 
    private static final int CHARACTERS_PER_CODE = 3; 
    private static int charA; 
    private static int preChars; 
    private static String preLetters; 

    public static void main(String[] args) { 
     /* (1) Generate three character alphabetic prefix codes. */ 
     writeRandomCodesToFile("prefix.txt", 'A', 'Z', 
           CHARACTERS_PER_CODE, PRODUCT_COUNT); 
     // when you hit run, there is 3 numbers. six digits though. 

     /* (2) Generate three character alphabetic suffix codes. */ 
     writeRandomCodesToFile("suffix.txt", 'A', 'Z', 
           CHARACTERS_PER_CODE, PRODUCT_COUNT); 

     /* (3) Generate three character numeric inline codes. */ 
     writeRandomCodesToFile("inline.txt", '0', '9', 
           CHARACTERS_PER_CODE, PRODUCT_COUNT); 

     /* (4) Merge the two alphabetic and one numeric code to produce the 
     * final product code. */ 
     mergeProductCodesToFile("prefix.txt", "inline.txt", "suffix.txt", 
           "productCode.txt"); 
    }// end main() 


    /* (1),(2),(3) Generate the alphanumeric codes. These are three aphanumeric 
    * character combinations generated randomly with each character in the 
    * range A-Z | 0-9. Thus you will have codes from AAA-ZZZ | 000-999. 
    * 
    * Write numberOfCodesToGenerate codes to the specified file. 
    */ 
    public static void writeRandomCodesToFile(String codeFile, 
               char fromChar, char toChar, 
               int numberOfCharactersPerCode, 
               int numberOfCodesToGenerate) { 
     Random rnd = new Random(); 
     charA = 65; 
     for (int i = 1; i <= 20; i++) { 
      try (
       PrintWriter fout = new PrintWriter(new File("prefix.txt")); //Creates File 
      ) { 
       preChars = charA + rnd.nextInt(26); 
       preLetters = String.valueOf((char) preChars); 
       System.out.print(preLetters);  

      } catch (FileNotFoundException e) { 
       System.err.println(e.getMessage()); 
      } 
     } 
    }// end writeRandomCodesToFile() 

    /* (4) Merge the two alphabetic and one numeric code to produce the final 
    * product code. The final product code will consist of <prefix><inline><suffix>. 
    * Each code will be in the range AAA000AAA-ZZZ999ZZZ. 
    * 
    * Merge by using a prefix, an inline and a suffix code from their corresponding 
    * files. Each individual code (pre, in, post) is used exactly once, and all values are used. 
    * 
    * Write these final product codes to the file specified in productFile. 
    */ 
    public static void mergeProductCodesToFile(String prefixFile, 
               String inlineFile, 
               String suffixFile, 
               String productFile) { 


    }// end mergeProductCodesToFile() 
}// end Main 
+0

Пожалуйста, поставьте код в актуальный вопрос, а не с помощью внешнего веб-сайта. – UnknownOctopus

+0

Может ли вывод быть смешанным буквенно-цифровым, например «A2B», или они должны быть буквами * или * всеми номерами? – Bohemian

+0

Они должны быть заглавными буквами. Я рандомизировал числа, а затем преобразовал числа в соответствующую букву. –

ответ

2

Игнорирование свой контекст и отвечая на вопрос, как в названии:

Учитывая длинную строку, чтобы вставить новую строку каждый 3 символы:

str = str.replaceAll("...", "$0\n"); 
+1

ваше регулярное выражение всегда меня впечатляет. Отличный ответ. – Shahzeb

+0

Я пробовал то, что вы сказали, но, похоже, это не сработало. Это то, что я сделал: 'preChars = charA + rnd.nextInt (26); preLetters = String.valueOf ((char) (preChars)); str = preLetters.replaceAll ("...", "$ 0 \ n"); System.out.print (str); ' И выход вышел таким же. –

+0

@SpencerBochantin Works здесь 'public static void main (String ... args) { \t \t String str =" abcdefghijklmnopqrstuvwxyz "; \t \t \t \t str = str.replaceAll ("...", "$ 0 \ n"); \t \t System.out.println (str); \t} ' – Shahzeb

0
import java.util.Random; 
import java.io.PrintWriter; 
class test{ 

    public static String randomString(String chars, int length) { 
     Random rand = new Random(); 
     StringBuilder buf = new StringBuilder(); 
     for (int i=0; i<length; i++) { 
      buf.append(chars.charAt(rand.nextInt(chars.length()))); 
     } 
     return buf.toString().replaceAll("...","$0\n"); 
    } 

    public static void main(String[] args) { 
     String myString = randomString("ABCDEFGHIJKLMONQRSTUVWXYZ",60); 

     try { 
      PrintWriter pw = new PrintWriter("fileame.txt"); 
      pw.println(myString); 
      pw.close(); 
     } catch (Exception e) {} 
    } 
} 
Смежные вопросы