Home Answers Viewqa Java-Beginners Writing a Program to calculate Circumference of planets reading from a file and writing to new file.

 
 


Sean Braxton
Writing a Program to calculate Circumference of planets reading from a file and writing to new file.
1 Answer(s)      2 years and a month ago
Posted in : Java Beginners

Hello, I would like to know how to write a program to read data from a file. Then use the numerical data within to then calculate the circumference of the planets. I then have to output the data into a new file.

The text file is Sun,860000 Mercury,4000 Venus,8000 Earth,8400 Mars,2500 Jupiter,135000 Saturn,100000 Uranus,75000 Neptune,70000 Pluto,2750

the integers represent the diameter. I have most of the code, but I am stumped when it comes to reading the file and writing to a new file. My code is as follows



package SBLab08;
import java.io.*;
import java.util.*;
import java.math.*;

/**
 *
 * @author ConfibulatoryMadness
 */
public class Main {


public static void main(String[] args) throws IOException {

    Scanner input = new Scanner(System.in);
    int loop = 0;
    while(loop==0){
    System.out.print("\nPlease enter the name of the input file - ");
    String Input_File = input.nextLine();
    System.out.print("\nPlease specify the name of the output file - ");
    String Output_File = input.nextLine();

    if(Input_File.equalsIgnoreCase(Output_File)){
        System.out.print("\nThe output file must be different than the input one.");
    }else{ loop=1;}
    Scanner IF = new Scanner(new File(Input_File));
    while( IF.hasNext() ){
        String Seperator = (",");
        String lineFromFile = IF.nextLine();
        String[] partsOfLine = lineFromFile.split( "," ); // "," should be defined as a constant

    // Use partsOfLine[ 0 ] for the name.
    // Calculated the circumference as Math.PI * Integer.parseInt( lineFromFile[ 1 ] );
    // Both 0 and 1 can be defined as constants
    // Be sure NOT to calculate circumference twice because you need it for both the 
    // console and file I/O.

    // Perform file I/O and console I/O here.
    }          
    java.io.File New_Planet_Info = new java.io.File(Output_File);
    PrintWriter output = new PrintWriter(Output_File);
    System.out.print(IF);
    }

}

} Where I have the comments in my code is an area where I could use the most help. Please Help.I need to also output to the user the new data included with the original data. and for 3.14 can i just use pi since I imported the math package? My output needs to look like this:

NAME DIAMETER CIRCUMFERENCE Sun 860000 2701770 Mercury 4000 12566 Venus 8000 25133 Earth 8400 26389 Mars 2500 7854 Jupiter 135000 424115 Saturn 100000 314159 Uranus 75000 235619 Neptune 70000 219911 Pluto 2750 8639

I wish this thing would display my text just like it is, it almost looks like a table. My teacher is really anal on detail.Basically I have to call the file into the scanner/reader, extract the numerical data, calculate the circumference then save it to another file. Then output the newly saved file to the user. I made this post previously but I am concerned that the user who had gave their answer can't see that I am commenting on it.

Thank You Confibulatory Madness

View Answers

April 16, 2011 at 1:03 PM


import java.io.*;
import java.util.*;
import java.math.*;

public class Main{
    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in);
        System.out.print("\nPlease enter the name of the input file - ");
        String Input_File = input.nextLine();
        System.out.print("\nPlease specify the name of the output file - ");
        String Output_File = input.nextLine();
        BufferedWriter bw=new BufferedWriter(new FileWriter(new File(Output_File),true));
    BufferedReader br = new BufferedReader(new FileReader(new File(Input_File)));
    String strLine;
    ArrayList list=new ArrayList();
    while((strLine = br.readLine()) != null){
    list.add(strLine);
    }

    Iterator itr;
    for (itr=list.iterator(); itr.hasNext(); ){
    String str=itr.next().toString();  
    String [] splitSt =str.split(",");
    String planet="",diameter="";
    for (int i = 0 ; i < splitSt.length ; i++) {
    planet=splitSt[0];
    diameter=splitSt[1];
    }
    double r=Double.parseDouble(diameter)/2;
    double circumference=2*Math.PI*r;
    long cir=Math.round(circumference);
    bw.write(planet+"\t "+diameter+"\t "+Long.toString(cir));
    bw.newLine();
     }
    bw.close();
        }   
}









Related Pages:
Writing a Program to calculate Circumference of planets reading from a file and writing to new file.
Writing a Program to calculate Circumference of planets reading from a file... to then calculate the circumference of the planets. I then have to output the data into a new... stumped when it comes to reading the file and writing to a new file. My code
Writing a Program to calculate Circumference of planets reading from a file and writing to new file.
Writing a Program to calculate Circumference of planets reading from a file... to then calculate the circumference of the planets. I then have to output the data into a new... it comes to reading the file and writing to a new file. My code is as follows
Writing and Reading A File
Writing and Reading A File  Hello, I've been trying to learn writing and reading data from file for our assignment, but just stuck on how to proceed...(ActionEvent ae){ File file=new File("Employee.txt"); FileInputStream fis = null
reading multiple files from a directory and writing them into a single file
reading multiple files from a directory and writing them into a single file... this: /*this program reads multiple files * from a single directory. */ package elite.tech.com... static void main(String[]args) throws IOException{ File Folder = new
writing and appending to a file
writing and appending to a file  My input file includes data from... and values and writes into an existing file for 'male'. How can I do the same for females and write into a different 'female string' in the same program? Sorry If I
Reading and Writing files - Java Beginners
Reading and Writing files  Hello, please help me to Develop a simple... from a file. After welcoming the users, ask them for their name and save it to the file. Use the ClassLoader and Properties classes to load the file. You will need
java program for writing xml file - Java Beginners
java program for writing xml file  Good morning i want to write values from my database(one table)into one xml file. Like i have 3 coloumns in my..."); // create string from xml tree StringWriter sw = new
Having a hard time writing program to calculate test scores..........
Having a hard time writing program to calculate test scores.......... ... the data from the file and store the data into an array. To do this, you will have to have your program open the data file, count the number of elements in the file
File Writing - Java Beginners
File Writing  Hi... I need a syntax or logic or program by which we can write into the desired shell of the Excel file from console window...  Hi friend, I am sending you a link. This is will help you. Please
Reading And Writing Excel File
reading and writing excel file   ... words, we can say that it is used to read the excel file. After reading the excel... file and write it into other excel file by this way. You can add new cell
Writing a file using servlets - JSP-Servlet
Writing a file using servlets  I'm using a servlet to read an input from a jsp file and write into a .txt file in my computer. The code is good until reading the data and creating a file in my space. but it is not writing
Need help writing a console program
will replace all sequences of 2 spaces with 1 space. The program will read a file...Need help writing a console program  I need help cant seems to figure it out! Write a program that consists of three classes. The first class
problem of writing to a local file ( JApplet ) - Applet
problem of writing to a local file ( JApplet )  Dear All, I want to program a guestbook using java applets but now I have problem of writing to a file from JApplet. it is working without any problem if i run the program using
Writing xml file - Java Beginners
from xml tree StringWriter sw = new StringWriter... = sw.toString(); File file = new File("c:/newxml.xml...Writing xml file  Thank you for the quick response The values which
File saving and Writing
File saving and Writing   Hello Rose india..... I have a doubt... a "file create option" it will be ".csv" file and i want to write the data from arraylist into .csv file and i want to save that file so it will ask for "save
writing a text into text file at particular line number
writing a text into text file at particular line number   Hi, thanks..... after line number four my text will display in text file using java program  ... = ""; int lineNo; try { File f=new File("c
writing a text into text file at particular line number
writing a text into text file at particular line number   Hi, thanks..... after line number four my text will display in text file using java program  ... = ""; int lineNo; try { File f=new File("c
accessing data from a json file writing javascript or using jQuery
accessing data from a json file writing javascript or using jQuery  I... page is built from this json file, but I can't figure out how to code... correctly accessing the attributes in the json file. Nothing is working. I'm new
Writing and reading from/to a serialized file through Hash Table in Java
Writing and reading from/to a serialized file through Hash Table in Java... illustrates you how to read and write from/to a serialized file through the hash table.... Following program has the facility if the specified serialized file does not exist
Writing Actions
Writing Actions The Action is responsible for controlling of data flow within... from this method. You can write your own method, for this you have to specify the method name in Action mapping in struts.xml file. To get model reference
Writing Calculator Stateless Session Bean
' bean. Writing JSP and Web/Ear component Our JSP file access the session bean...Writing Calculator Stateless Session Bean... to build ear file. We will deploy our application using WebLogic console
counting the values in input file and and writing the output to a file
counting the values in input file and and writing the output to a file  Can any one please correct this code. This is to read a file and later...-code/16483-counting-values-input-file-writing-output-file.html this code
writing program - Java Beginners
writing program  WAP to input Name of Cricketer, Number of matches, total runs scored for 250 players from the user and print data in descending...)) throw new ClassCastException("Error"); int averageRuns = ((ShowData
Writing Log Records to a Log File
Writing Log Records to a Log File       This section demonstrates for writing log records to a log file. Logger provides different types of level like: warning, info
Reading a text file in java
in java.io.* package for reading and writing to a file in Java. To learn more about reading text file in Java see the tutorial Read File in Java. Thanks...Reading a text file in java  What is the code for Reading a text file
Writing for the Purpose of Reading
Writing for the Purpose of Reading   ... of such an operation can vary from browser to browser. - The texts should be organized... disoriented. - The advantage of web writing is that a greater number of lists
without writing web.xml file we can write servlet program
without writing web.xml file we can write servlet program  Sir Morning... Sir I have one Question "without writing web.xml file we can write servlet program". if yes which way? if no why? but without use Annotation........ Plz
writing a text into text file at particular line number
writing a text into text file at particular line number   Hi, thanks for quick response, I want to insert text at some particular line number.. after line number four my text will display in text file using java program
Writing a GUI program - Java Beginners
Writing a GUI program  Hello everyone! I'm trying to write a program... if that number is prime or not. When the second button is pressed the program has to calculate the prime factors of the given number. I figure out the whole
Reading string from file timed
Reading string from file timed  So I want to make a file reader/ buffered reader that reads a new line of the textfile, lets say every 30 second. Like it reads the first line, waiting 30 seconds, read the next line and so one
Java File Writing Example
Java File Writing Example To write some data on the file you need to first... BufferedWriter(fileWriter); bufferedWriter.write("Adding New Information to the File... the file name from the user, When file exists, then it opens, and take the file
i written the program in the files but in adding whole file is writing once again - Java Beginners
i written the program in the files but in adding whole file is writing once again  Very Urgent: Write a small record management application file... From Database Id Name Last Name Delete
Reading file into bytearrayoutputstream
input stream and byte output stream. This is and good example of reading file... we have used the class InputStream for reading the file content into byte... FileOutputStream class writes the data into a new file. The fileOutputStream.write
writing document (.doc) file from java with format such as font type, font style
writing document (.doc) file from java with format such as font type, font... = new File("C:/sample.doc"); POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file)); HWPFDocument doc = new HWPFDocument(fs); Range range
Image writing over URLConnection
. The problem is that when writing by ImageIO on URL what will the name of the file...Image writing over URLConnection  Hello, I am trying to write... problems trying to write an image I have succeeded in writing to the local HD using
How to access the image file from project folder itself while writing to pdf using itext?
How to access the image file from project folder itself while writing to pdf using itext?  I am writing a pdf using itext where i add a image... it to pick it up from the project folder itself.Because later i deploy the project
External file reading in jsp
External file reading in jsp  i have written a jsp page(ReadExt.jsp) in my application which reads a text file content from a system... file. It uses BufferedReader class to read that particular file. <%@ page
External file reading in jsp
External file reading in jsp  i have written a jsp page(ReadExt.jsp) in my application which reads a text file content from a system...; The given code reads the given file. It uses BufferedReader class to read
writing programs - Java Beginners
writing programs  1.write a program to display odd numbers from 1-50. 2.And Write a program to find the facorial of a number  Hi... factorial{ public static void main(String []args){ Scanner input=new Scanner
Write a program to calculate factorial of any given number
; This Java programming tutorial will teach you the methods for writing program to calculate factorial of any given number. First of all define a class... Factorial Examples - Java Factorial Example to calculate factorial of any
Reading XML from a File
Reading XML from a File       This Example shows you how to Load Properties from the XML file via... to create new DOM parsers. Some of the methods used for reading XML from
Java example for Reading file into byte array
Get Byte Array from File Reading a File...Java example for Reading file into byte array. You can then process the byte... in Java for reading file into byte array. Sometimes it becomes necessary
initialise array by reading from file - Java Beginners
initialise array by reading from file  Hello, I wnat to know how i would initialise an array by reading a text file, which contains a simple pattern...(new InputStreamReader(in)); String strLine; //Read File Line By Line
How to write content of one file to another file and calculate checksum for accuracy.
to another file. And calculate the value of checksum at writing time with the help of CheckedOutputStream class. After it we will read the content of new file... : 1792016811  value of checksum Affter reading new file : 1792016811
Web Writing
Web Writing       The art of writing for the web is far removed from writing for the print world... content. - Reading speed from the computer screen is 25% less than the paper
reading data from excel file and plotting graph
reading data from excel file and plotting graph  I am doing a project...); try { ChartUtilities.saveChartAsJPEG(new File("C... at the same time from one excel file using different columns..how can i do that? waiting
svg file reading and display
svg file reading and display  i want a sample program for reading and displaying the content of a svg file
Reading binary file into byte array in Java
Example code of reading binary file into byte array in Java This example shows you how to read a binary file into byte array from Java program. This type... of the Java program that reads the binary file into byte array: import java.io.
jar file not reading input from serial port
jar file not reading input from serial port  i used a coding for getting data from serial port. JOptionbox with "port not found" message is shown when i execute thru jar file. but when i execute thru netbeans, data is received
jar file not reading input from serial port
jar file not reading input from serial port  i used a coding for getting data from serial port. JOptionbox with "port not found" message is shown when i execute thru jar file. but when i execute thru netbeans, data is received

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.