我必須制作一個文本檔案,我應該在其中放置 100 個隨機字符,其中每個偶數位置應該是一個小寫字母,每個奇數位置應該是一個大寫字母。此外,所有字母都應該由空白欄位(空格)分隔。我只成功地制作了 100 個隨機字串列,但我不知道如何做剩下的。
public class Main {
public static char getRandomCharacter(char c1, char c2) {
return (char) (c1 Math.random() * (c2 - c1 1));
}
public static char[] createArray() {
char[] character = new char[100];
for (int i = 0; i < character.length; i ) {
character[i] = getRandomCharacter('a', 'z');
}
for (int i = 0; i < character.length; i ) {
System.out.println(character[i]);
}
return character;
}
public static void main(String[] args) {
createArray();
}
}
我將不勝感激。
編輯:這是一個經過編輯的版本。但是,輸出并沒有太大的不同b j r m r b k i...
public class Main {
public static char getRandomCharacter(char c1, char c2) {
return (char) (c1 Math.random() * (c2 - c1 1));
}
public static char[] createArray() {
char[] character = new char[100];
for (int i = 0; i < character.length; i ) {
character[i] = getRandomCharacter('a', 'z');
}
for (int i = 0; i < character.length; i ) {
System.out.println(character[i]);
}
return character;
}
public static void main(String[] args) {
char[] arr = createArray();
StringBuilder text = new StringBuilder();
for (int i = 0; i < arr.length; i ) {
int pos = i 1;
if (pos % 2 != 0) {
String s = "" arr[i];
text.append(s.toUpperCase());
} else {
text.append(arr[i] " ");
}
}
String content = text.toString().trim();
}
}
uj5u.com熱心網友回復:
碼點
WJS的答案看起來是正確的。但是,不幸的是,這種char型別是遺留的。作為 16 位值,該char型別在物理上無法表示大多數字符。所以我建議養成使用代碼點整數而不是char.
IntSupplier對于IntStream代碼點
另外,我碰巧注意到IntStream.generate采用IntSupplier. 我們可以撰寫自己的該介面實作,IntSupplier在回傳大寫字母的代碼點編號和回傳小寫字母的代碼點之間交替。
在我們的實作中,我們定義了兩個物件的列舉,以表示大寫和小寫。
我們的實作有一個建構式采用這兩個列舉物件中的任何一個。傳遞的引數表示要生成的第一個字母的大小寫。
package work.basil.example.rando;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.IntSupplier;
public class SupplierOfCodePointForBasicLatinLetterInAlternatingCase
implements IntSupplier
{
public enum LetterCase { UPPERCASE, LOWERCASE }
private LetterCase currentCase;
public SupplierOfCodePointForBasicLatinLetterInAlternatingCase ( final LetterCase startingCase )
{
this.currentCase = startingCase;
}
@Override
public int getAsInt ( )
{
int codePoint =
switch ( this.currentCase )
{
case UPPERCASE -> ThreadLocalRandom.current().nextInt( 65 , 91 ); // ( inclusive , exclusive )
case LOWERCASE -> ThreadLocalRandom.current().nextInt( 97 , 123 );
};
this.currentCase =
switch ( this.currentCase )
{
case UPPERCASE -> LetterCase.LOWERCASE;
case LOWERCASE -> LetterCase.UPPERCASE;
};
return codePoint;
}
}
當我們呼叫自定義的IntStream時,我們傳遞了要生成的代碼點數量的限制。
最后,我們將所有生成的代碼點收集到一個StringBuilder我們構建最終結果String物件的地方。
IntStream streamOfCodePoints = IntStream.generate( new SupplierOfCodePointForBasicLatinLetterInAlternatingCase( SupplierOfCodePointForBasicLatinLetterInAlternatingCase.LetterCase.UPPERCASE ) );
String result =
streamOfCodePoints
.limit( 100 )
.collect( StringBuilder :: new , StringBuilder :: appendCodePoint , StringBuilder :: append )
.toString();
ZtAxIqWfEhOeHdSgOpMyPuJwLuSwJqHzUwSlLeQnFoFcAaMfOxMiBnVuZxOpCvPuLiZhBmIrGaBqZzIyOoUhAdFmXgArVwWqBoWr
添加空間
您的要求指定每個生成的字母用空格分隔。
在某處為 SPACE 字符的代碼點 32 定義一個常量。
private static final int SPACE = 32; // ASCII & Unicode code point for SPACE character is 32 decimal.
然后改變我們的.collect行以使用擴展語法。我們使用 lambda 代替方法參考。在那個 lambda 中,我們呼叫StringBuilder#appendCodePoint了兩次。在第一次呼叫中,我們附加了生成代碼點。在第二個呼叫中,我們附加了空格字符的代碼點。
為了在最后消除空間,我們修剪。
IntStream streamOfCodePoints = IntStream.generate( new SupplierOfCodePointForBasicLatinLetterInAlternatingCase( SupplierOfCodePointForBasicLatinLetterInAlternatingCase.LetterCase.UPPERCASE ) );
String result =
streamOfCodePoints
.limit( 100 )
.collect(
StringBuilder :: new ,
( stringBuilder , codePoint ) -> stringBuilder.appendCodePoint( codePoint ).appendCodePoint( App.SPACE ) ,
StringBuilder :: append
)
.toString()
.trim() ;
X t D j J g J m Y c J a E e H m U c H b U a R t J g R n G r V s P e B z D k G f H e Z r W t U l U f C z R j F z G k Z f A y I z N i L g Q y Q w D w D w P s F y E n J n I i R b B u H x U m B g K w C k
如果您想將 SPACE 保留在末尾,請放棄對String#trim.
uj5u.com熱心網友回復:
這是使用 ASCII 字符流的替代方法。在 ASCII 表中,a-z是相鄰的A-Z。d因此,對于來自的任何值0 to 25,(char)(d 'a')將是一個小寫字母,而 (char)(d 'A') 將是一個大寫字母。
- 創建一個
Random實體。 0 to 100流式傳輸來自for100字符的整數。- 檢查奇偶性
i并將“a”或“A”添加到值d - 映射到字串并使用空格作為分隔符連接。
Random r = new Random();
String str = IntStream.range(0,100).mapToObj(
i -> {
int d = r.nextInt(26);
return String.valueOf((char)(i % 2 == 0 ? d 'a' : d 'A'));
}).collect(Collectors.joining(" "));
System.out.println(str);
列印類似的東西
j H o C y X h H k A y F z J b D x A z R t Y w O d A a F q F t R n A i B k Y g F
y X c O r I h E k K t R n L a S d C s T m S z Y z H a V y N o R t S y I t E l W
q X l E v S h D r C y N h O o C l D u X
要寫入檔案,請使用try with resources并捕獲 IO 錯誤。
String file = "f:/myOutputFile.txt";
try (FileWriter output = new FileWriter(new File(file))) {
output.write(str);
} catch (IOException ioe) {
ioe.printStackTrace();
}
以下是如何使用簡單的回圈來完成它。
- 將 a 初始化
StringBuilder為偶數的第 0 個位置的小寫字母。這也允許在末尾添加空格以避免尾隨空格。 - 然后迭代 from
1 to 100以獲取其他99字符。 - 首先附加空格,然后附加適當的字符,如上一個示例中所做的那樣。
- 然后你可以寫成
StringBuilder一個字串,如上圖所示。
StringBuilder sb =
new StringBuilder().append((char) (r.nextInt(26) 'a'));
for (int i = 1; i < 100; i ) {
int d = r.nextInt(26);
sb.append(" ")
.append((char) (i % 2 == 0 ? d 'a' : d 'A'));
}
uj5u.com熱心網友回復:
string在您的情況下,創建第一個然后將其放入txt檔案中會更容易。
您可以簡單地遍歷隨機陣列并檢查奇數/偶數位置。在相應的奇偶位置使用Character.toUpperCaseor并附加到字串。Character.toLowercase
使用StringBuilder這樣您就不必每次都創建新的 String 物件。
char[] arr = createArray();
StringBuilder text = new StringBuilder();
//iterate thoruh the arr
for (int i = 0; i < arr.length; i ) {
int pos = i 1;
if(pos%2!=0){ // check whether current postion is odd or even
text.append(Character.toUpperCase(arr[i]) " ");// if position is odd then convert it to uppercase
}else{
text.append(arr[i] " "); // if position is even then convert it toLowercase if needed (if arr contents both upper case and lower case)
}
}
String content = text.toString().trim(); // trimin to remove any extra space in last or first of the string.
寫入檔案
String path = "D:/a.txt";
Files.write( Paths.get(path), content.getBytes());
編輯 1:我不確定為什么這Character.toUpperCase不起作用。您可以嘗試以下轉換,缺點是String將為每個偶數位置創建一個物件。
String s = "" arr[i];
text.append(s.toUpperCase() " ");
編輯2:您可以正常使用String
String text = "";
for (int i = 0; i < arr.length; i ) {
int pos = i 1;
if (pos % 2 != 0) {
String s = "" arr[i];
text =text s.toUpperCase() " ";
} else {
text= text (arr[i] " ");
}
}
String content = text.toString().trim();
System.out.println(content);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483059.html
上一篇:請幫助我獲得我想要的輸出
