-1
輸入文件DATA1.txt將包含7行,每行都有一個描述每種類型糖果數量的正整數。輸出文件OUT1.txt將包含與輸入的數字相同的星號。 即: 輸入DATA1.TXT會顯示:如何根據用戶輸入創建輸入和輸出文件?
12
8
10
5
20
3
7
輸出OUT1.txt會顯示:
12: ************
8: ********
10: **********
5: *****
20: ********************
3: ***
7: *******
當我運行我的代碼,它僅創建一個文件,該文件是OUT1.txt但它有數字而不是星星。我怎麼會有一個DATA1.txt呢?我不太明白這一點,因爲我沒有了解輸入或輸出文件。任何幫助將不勝感激。我會在我的代碼中修改什麼?
import javax.swing.*;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class CandyLand{
public static void main(String str[]){
int num1,num2,num3,num4,num5,num6,num7;
String input1 = JOptionPane.showInputDialog("Please, enter the number of candies in the first pile");
num1 = Integer.parseInt(input1);
String input2 = JOptionPane.showInputDialog("Please, enter the number of candies in the second pile");
num2 = Integer.parseInt(input2);
String input3 = JOptionPane.showInputDialog("Please, enter the number of candies in the third pile");
num3 = Integer.parseInt(input3);
String input4 = JOptionPane.showInputDialog("Please, enter the number of candies in the fourth pile");
num4 = Integer.parseInt(input4);
String input5 = JOptionPane.showInputDialog("Please, enter the number of candies in the fifth pile");
num5 = Integer.parseInt(input5);
String input6 = JOptionPane.showInputDialog("Please, enter the number of candies in the sixth pile");
num6 = Integer.parseInt(input6);
String input7 = JOptionPane.showInputDialog("Please, enter the number of candies in the seventh pile");
num7 = Integer.parseInt(input7);
String fileName = JOptionPane.showInputDialog("Please, enter the name of the file");
try{
DataOutput f = new DataOutputStream(new FileOutputStream(fileName +".txt"));
f.writeBytes(String.valueOf(num1));
f.writeBytes("\r\n");
f.writeBytes(String.valueOf(num2));
f.writeBytes("\r\n");
f.writeBytes(String.valueOf(num3));
f.writeBytes("\r\n");
f.writeBytes(String.valueOf(num4));
f.writeBytes("\r\n");
f.writeBytes(String.valueOf(num5));
f.writeBytes("\r\n");
f.writeBytes(String.valueOf(num6));
f.writeBytes("\r\n");
f.writeBytes(String.valueOf(num7));
}
catch(Exception e){
String msg = e.toString();
System.out.println(msg);
}
Scanner file = null;
ArrayList<Integer> list = new ArrayList<Integer>();
try {
file = new Scanner(new File("OUT1.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(file.hasNext()){
if (file.hasNextInt()) list.add(file.nextInt());
else file.next();
}
for (Integer j: list){
System.out.print(j + ": ");
for(int i=1; i<=j; i++){
System.out.print("* ");
}
System.out.println("");
}
}
}
我找到了一種方法,就好像他們進入OUT1在那裏我要求他們輸入文件名,因爲我無法找到另一種方式做到做它。 – SamB
您是否更改了上述兩個代碼段,掃描程序並用DataOutput替換了打印件?你在命名你的文件是什麼? – MC10
如果我有一個名爲DATA1.txt的文件,裏面有數字,那麼我怎樣才能將這些數字放入一個名爲OUT1.txt的文件中,旁邊的數字旁邊是星星。沒有用戶輸入數字。我注意到我不需要用戶輸入 – SamB