[英]How to use writer with user input using scanner
我正在嘗試通過獲取用戶輸入來創建文件。 例如,用戶輸入套數並將其寫入文件,然后再寫入兩個用戶輸入。 但是它不顯示任何文件。 另外還有其他疑問,如何在文件中記錄隨機數?
我編寫代碼的目的是,當用戶選擇2套和用戶想要的套數時。 例如,如果用戶選擇4和6,它將隨機分別生成4個數字和6個數字。 我知道如何使用隨機,但只是不知道如何實現此目的以編寫文件。
這些是我應該得到的樣本輸出
2
5
23 789 900 4000 4
10
10002 50930 2345 30 20 1 0 45 5 8000
從代碼:
public static void main(String[] args) throws IOException {
Random rnd = new Random();
File file = new File("C://Users//Hyeon Jin Ryu//nums.txt");
FileWriter w = new FileWriter(file);
Scanner in = new Scanner(System.in);
System.out.println("Please enter numbers of sets: ");
int a = in.nextInt();
System.out.println("Please enter the size of two each sets");
int firstSet = in.nextInt();
int secondSet = in.nextInt();
int t = rnd.nextInt(firstSet);
int k = rnd.nextInt(secondSet);
w.write(a);
w.write(t);
w.write(k);
in.close();
w.flush();
w.close();
}
您發布的代碼不會輸出與您提供的示例輸出相近的任何內容。 您應該真正注意所調用的方法的實際作用。
FileWriter.write(int)
按照文檔中的說明寫入一個字符 。 否則,您應該使用字符串。 寫一個字符。 給定整數值的16個低位包含在要寫入的字符中。 16個高位被忽略。
您需要使用w.write(String.valueOf(t))
將整數解析為一個字符串,但是它仍然不會輸出多個數字,因為您需要先循環代碼。
以下代碼不會生成X數量的數字,而只是從用戶那里獲取一個數字firstSet
並將其設置為它將生成的最高隨機數,這也將在文檔或任何IDE中顯示:
int firstSet = in.nextInt(); // if user enters 6 int t = rnd.nextInt(firstSet); // generate random number from 0-6
因此,即使您確實解析了a
, t
和k
值,然后使用您提供的相同輸入(2、5、10),它也會:
245
。 您想向用戶詢問集合的數量,將其存儲為變量,並創建一個循環,循環的次數與變量中的值一樣多,並生成X數量的集合和Y數量的隨機數。 如果有2套大小分別為5和10的代碼,則您的代碼將需要分別循環5和10次以生成5和10隨機數,並重復整個過程2次。
以下代碼產生您要描述的結果。 請注意rnd.nextInt()
如何被2500綁定,第二個for循環如何運行與用戶提供的集合大小一樣多的次數,然后在嵌套的for循環中再次為提供的集合數量運行所有內容。
它還將FileWriter的try-with-resources用於處理代碼中的異常,而不是將其傳遞回JVM以使其崩潰,其次用於自動關閉FileWriter流。
public static void main(String[] args) {
Random rnd = new Random();
File file = new File("nums.txt");
try (FileWriter w = new FileWriter(file)) {
Scanner in = new Scanner(System.in);
StringBuilder setResult = new StringBuilder();
System.out.println("Please enter the number of sets: ");
int n = in.nextInt();
System.out.println("Please enter the size of each set: ");
for (int j = 0; j < n; j++) {
int setSize = in.nextInt();
for (int k = 0; k < setSize; k++) {
int randomNum = rnd.nextInt(2500);
setResult.append(randomNum).append(" ");
}
setResult.append("\n");
}
w.write(setResult.toString());
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
生成的文件寫得很好,並包含:
699 494 1611 1521 2042
2478 500 177 1602 348 231 1191
842 421 93 1229 1804 802 1845 2245 836
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.