私は代入に取り組んでおり、コードを完成させましたが、出力の正しい書式設定に問題があります。私はテキストファイルを取って、価格に基づいて製品を分けて、2つの別々のファイルにデータを追加しています。 BufferedWriterでdouble型の形式をドル記号なしの金額(0.00)として表示するにはどうすればよいですか?現在、(0.0)として出力しています。ご協力いただきありがとうございます。JavaでBufferedWriterを使用して二重出力をフォーマットする
マイコード:
//import the io utilities and scanner
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
/**
* class ProductData uses the scanner utility to read a file, FileWriter and
* BufferedWriter to write data from original file to two new files
* based on the product price.
*/
public class ProductData
{
/**
* method main calls the scanner to read a file, uses a while loop
* to scan through the file until done, and uses two if loops
* to determine the price and append the data to two new files.
* @param args
* @throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException
{
//create a scanner, call the file to be read
Scanner reader = new Scanner(new File("products.txt"));
//variables defined
int productID;
String productDescription;
double productPrice;
//while loop to read each line in the file
while (reader.hasNext())
{
//retrieves each item in order using the next feature of the scanner
productID = reader.nextInt();
productDescription = reader.next();
productPrice = reader.nextDouble();
//if loop for price greater than or equal to 50.00
if(productPrice >= 50.00)
{
try
{
// Create file
FileWriter fstream = new FileWriter("WishList.txt",true);
//create BufferedWriter to write data to the file
BufferedWriter out = new BufferedWriter(fstream);
//writes data and blank line to file
out.write(productID + " " + productDescription + " " + productPrice);
out.newLine();
//Close the output stream
out.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
//if loop for price less than 50.00
if(productPrice < 50.00)
{
try
{
// Create file
FileWriter fstream = new FileWriter("GiftIdeas.txt",true);
//creates BufferedWriter to write data to file
BufferedWriter out = new BufferedWriter(fstream);
//writes data and blank line to file
out.write(productID + " " + productDescription + " " + productPrice);
out.newLine();
//Close the output stream
out.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}//ends if loop
}//ends while loop
}//ends method main
}
有用な例を示すために+1 –
+1 Javaの初心者向け – OutputLogic