So my class's lab assingment is to read in a text file with a city's name and some temperatures on one line (with any amount of lines) ex:
Montgomery 15 9.5 17
and print the name and the average of the temperatures. When printing out the name has to be to the left on the line, and the average should be printed with two digits after the decimal point, to the right on the line. I can assume no name is 30+ characters, and that the average can be printed in a field 10 characters wide (including the decimal point).
Here's what I have so far
import java.util.Scanner;
import java.io.*;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Formatter;
public class readFile2
{
public static void main(String[] args) throws IOException
{
FileReader a = new FileReader("places.txt");
StreamTokenizer b = new StreamTokenizer(a);
ArrayList<Double> c = new ArrayList<Double>();
/*System.out.println(
String.format("%-10s:%10s", "ABCD", "ZYXW"));
**I found this to format an output. */
double count = 0;
while(b.nextToken() != b.TT_EOF);
{
if(b.ttype == b.TT_WORD)
{
System.out.print(b.sval);
}
if(b.ttype == b.TT_NUMBER)
{
c.add(b.nval);
count ++;
}
double totaltemp = 0; // I need to figure out how to put
// this inside of an if statement
for(int i = 0; i < c.size(); i++) // that can tell when it reaches
{ // the last number/the end of the line
totaltemp = c.get(i) + totaltemp; //
count++; //
} //
//
System.out.print(totaltemp/count); //
}
}
}
The second part is to modify the program so that the name of a cty may consist of more than one word (e.g., `New York')
I really appreciate any and all help and advice :)
Related
Ok, I'm trying to get the output to look a certain way. Print 10 numbers the new line. For some reason after running through loop 4 it sets i to 0. I'll put the file I'm reading from first. I eventually want to write it to a new file. This is for a class, just one assignment and I'm not asking you guys to do the assignment. (Basically I have to read the file and write to a new file with the name designated in the first file. And only use the number of numbers at the top of the first file.
The txt file contents:
MyOutput.txt 23
20 1 4 5 7
45
1 2 3 4 5 6 7 8 9 77 88 99 23 34
56 66 77 88 99 100 110 120
and the code
...
package reading_with_exceptions;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class inputFilename {
static Scanner kbInput = new Scanner(System.in);
public static void main(String[] args) {
String lines = null;
Scanner inFile = null;
int count = 0;
boolean metCount = false;
// TODO Auto-generated method stub
try {
inFile = new Scanner(new FileReader("src/MyInput.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lines = inFile.nextLine();
lines.trim();
//Now check to see if line is empty
//If not empty get the ouput file name and number of lines from file
if(lines.length()>0) {
String outPutFile = lines.substring(0, lines.indexOf(' '));
String numNumbers = lines.substring((lines.indexOf(' ')+1), (lines.length()-1));
numNumbers.trim();
count = Integer.parseInt(numNumbers);
System.out.print(outPutFile+" ");
System.out.println(count);
}
//
//check if there is another line in the file
int i=0;
while(inFile.hasNextLine() && !metCount) {
lines = inFile.nextLine();
String[] separated = lines.split(" ");
for( i = 0; i<separated.length; i++) {
System.out.print(separated[i]+" ");
if((i+1) % 10 ==0) {
System.out.println("...");
}
//System.out.print(" spot:"+i+" ");
//System.out.println("i:" +i +"count:"+count);
if(i>=count)
metCount = true;
}
}
}
}
...
I've tried stepping though it in Eclipse and still can't resolve the problem. It only happens every other time. First count goes to 4 Second count goes to 10 Third goes to 4 etc.
You're first line of output outputs the count as 23.
The processing stops because you're using the line count as a comparator with your string token count...
Hence the metCount gets set to true in the while loop and the program ends
I've edited the code with some improvements so you can understand this more clearly...
I've extracted some parts to methods so you can have a named method rather than needing comments.
package reading_with_exceptions;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class inputFilename {
static Scanner kbInput = new Scanner(System.in);
public static void main(String[] args) {
Scanner inFile = open("src/MyInput.txt");
/**
* First check you have a first line.
*/
if (!inFile.hasNext()) {
throw new IllegalStateException("File is empty");
}
String header = inFile.nextLine().trim();
/**
* Check first line is not blank
*/
if(isBlank(header)) {
throw new IllegalStateException("First line has no content");
}
/**
* Get filename and total line count from file
*/
String filename = getFilename(header);
int totalLines = getNumberOfLines(header);
/**
* output results to console on one line
*/
System.out.println(filename + " " + totalLines);
/**
* iterate over/process the lines one by one (but not the last line)
* This whole process could be put in a method named processLines(...) with relevant arguments passed.
* The more you nest your code, the harder it becomes to read/debug... and the easier it is for bugs to hide.
* The more your variables have meaningless names (i, j, k) the harder it is to follow.
* Tip: try to use methods and work on small bits of code at a time... much easier to read and understand a
* single, well named function with less steps to it than one large function.
*/
boolean isLastLine = false;
while(inFile.hasNextLine() && !isLastLine) {
String[] separated = inFile.nextLine().split(" ");
for(int tokenCount = 0; tokenCount < separated.length; tokenCount++) {
/**
* print out the token
*/
System.out.print(separated[tokenCount]+" ");
/**
* continue on a new line after every 10th token is printed to the console
*/
newLineAfterTenthTokenInASingleLine(tokenCount);
/**
* here when `tokenCount` passes over the 23rd item (`separated[tokenCount]`),
* `metCount` is set to `true` and the program ends.
* This is probably not what's wanted as you want to compare a `lineCount` to the `totalLines`, not the `tokenCount`
*/
if(tokenCount>=totalLines) { // <<<<<<<<<<<<<<<<< HERE'S THE PROBLEM
isLastLine = true;
}
}
}
}
private static void newLineAfterTenthTokenInASingleLine(int tokenId) {
if((tokenId+1) % 10 == 0) {
continueOnNewLine();
}
}
private static boolean isBlank(String firstLine) {
return firstLine.length()==0;
}
private static Scanner open(String inFile) {
try {
return new Scanner(new FileReader(inFile));
} catch (FileNotFoundException e) {
throw new
}
}
private static void continueOnNewLine() {
System.out.println("...");
}
private static int getNumberOfLines(String header) {
int beginIndex = header.indexOf(' ') + 1;
int endIndex = header.length() - 1;
return Integer.parseInt(header.substring(beginIndex, endIndex).trim());
}
private static String getFilename(String header) {
int beginIndex = 0;
int endIndex = header.indexOf(' ');
return header.substring(beginIndex, endIndex);
}
}
This chapter of the course is teaching us about methods in Java, more specifically returning values. While the rubric called for it to just be able to apply values from a .txt list the 9 planets provided below the program. I wanted to go beyond and make it so that there would be no limit on the amount of celestial bodies this could apply to (as I did with the program that created the .txt as an output). I have a finished program by another student available to me. However, I'd rather try approaching it in another way(Though I must thank Omar because I had no idea you could return arrays from methods).
Currently, as is, the program compiles without any errors in BlueJ. However, It does not run, or even put out any test print statements I put in. It's been running for over an hour on core 2 of my overclocked i5, but nothing. Since the core is being stressed, I assume it's stuck in a loop somehow?
How may I solve this issue?
I really appreciate any advice, and hope to spend more time here in the future.
/**
* 7.04 This program will take gravity and textual data from a .txt
* and will perform calculations with it once I figure out how that may be done.
*
*
* #author ********
* #version (The Date)
*/
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Weight2
{
// write static methods here
// Note: formula for finding weight on a planet: Earth weight divided by Gravity constant times surface gravity
public static String[] getData(int arraylength,int i, int value) {
String [] Gravityscan = new String[arraylength]; //Initiates String Arrays to be used
String [] pregravity = new String[arraylength];
String [] names = new String[arraylength];
String [] prevalues = new String[arraylength];
String [] error = {"error"};
String delims = "[ |\\ ]+"; // Sets Delimiters
File data2 = new File("Gravityoutput.txt"); //Opens data source
Scanner inFile = new Scanner("Gravityoutput.txt");
for(int m = 0; m < arraylength ; m++)
{
Gravityscan[m] = inFile.nextLine(); //String for each line being run
prevalues = Gravityscan[m].split(delims); //Split into two (gravity name)
pregravity[m] = prevalues[0]; //Sorts gravity string to array
names[m]= prevalues[1]; //Sorts name string to array
}
inFile.close();
//if (value == 0){return Integer.toString(arraylength);}
if (value == 1){return pregravity;} //Returns pregravity string for first part of loop below
else if (value == 2){return names;} //Returns names to end of for string below
else {System.out.print("AN ERROR HAS OCCURED IN METHOD GETDATA"); return error;}
}
//public static double calcWeight() {
//}
public static void main(String[] args)throws IOException
{
Scanner in = new Scanner(System.in);//Scanner activated
File data = new File("Gravityoutput.txt"); //Select file to get data from
Scanner inFile = new Scanner("Gravityoutput.txt");
int arraylength = 0; //Works with loop to determine length of data
while (inFile.hasNext())
{
arraylength++;
}
inFile.close(); //Closes file
System.out.print("arraylength is " + arraylength);//Beta testing check
double [] gravities = new double[arraylength]; //Declaring double array for after string conversion
//String[] names = new String[arraylength]; //Declaring array to be used for names
System.out.print("Please enter your mass on Earth in lbs: "); //User input for math
double earthWeight = in.nextDouble();
for(int i=0; i < arraylength; i++)
{
int value = 1;
String[] stringgravity = getData(arraylength, i, value);
gravities[i] = Double.parseDouble(stringgravity[i]);
System.out.print(gravities[i] + " gravity ");
value++;
String[] names = getData(arraylength, i, value);
System.out.println(names[i] + "gravity");
// static method you write Double.parseDouble
}
//double[] weight = calcWeight(earthWeight, gravity); // static method you write
//printResults(names, gravity, weight); // static method you write
} //end main
}//end class
//Below is the data contained by Gravityoutput.txt
3.70 Mercury
8.87 Venus
9.82 Earth
3.70 Mars
24.78 Jupiter
10.44 Saturn
8.86 Uranus
11.13 Neptune
0.61 Pluto
Creating an instance of Scanner with Scanner inFile = new Scanner("Gravityoutput.txt"); does not read input from the file, it reads input from the String "Gravityoutput.txt".
Try Scanner inFile = new Scanner(data); instead.
Oh, and your code is stuck in a loop :
inFile.hasNext() always returns true, since you never read anything from the Scanner.
You can replace it with
while (inFile.hasNext())
{
String str = inFile.next();
arraylength++;
}
so every time i run the program and enter the 2nd choice, it tells me rangecheck error , index0 , size 0.
what i understand from this after research is that the arraylist is empty, how do i use the add function in the 2D arraylist?
|ABCDEFGHIJKLMNOPQRSTUVWX
--+------------------------
01|gggggggggggggggggggggggg
02|gGGGGGGGGGGGGGGGGGGGGGGg
03|gGggggggggggggggggggggGg
04|gGgYYYYYYYYYYYYYYYYYYgGg
05|gGgYggggggggggggggggYgGg
06|gGgYggggggggggggggggYgGg
07|gGgYggYYYYYYYYYYYYggYgGg
08|gGgYggYggggggggggYggYgGg
09|gGgYYYYggggggggggYYYYgGg
10|gGggggggggggggggggggggGg
11|gGGGGGGGGGGGGGGGGGGGGGGg
12|gggggggggggggggggggggggg
package map;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;
import java.util.ArrayList;
public class MapMain
{
public static void main(String [ ] args)
{
Scanner input = new Scanner(System.in);
InputStream is = null;
int i;
char c;
String T;
ArrayList<ArrayList<String>> Contain = new ArrayList<ArrayList<String>>();
for(int L = 0; L < 30; L++)
{
Contain.add(new ArrayList<String>());
}
try{
do{
int a=0;
String Elements;
System.out.print("To load map enter 1\nTo print loded map enter 2\nTo change specific elements press 3 ");
a=input.nextInt();
switch (a){
case 1 :
System.out.print("What is the file dest?");
T=input.nextLine();
is = new FileInputStream(T);
while((i=is.read())!=-1)
{
c=(char)i;
String O = "ankosh";
//Contain.add(Contain.O);
}
break;
case 2:
while(true)
{
String U = Contain.get(16).get(0);
//System.out.print(Contain);
break;
}
break;
case 3:
System.out.print("What do you want to insert?");
Elements=input.nextLine();
//switch (Elements){
//case
}
break;
} while(true);
}catch(Exception e){
// if any I/O error occurs
e.printStackTrace();
}finally{
}
}
}
You created the array of arrays, and the arrays it contains, so far it's ok.
Now, on case 2 you are trying to reach the first element of the 16th array (basically of type String) which is null since you didn't add anything yet to this array.
What you need to do before trying the get(index), is to check that the length of the array is bigger than the index.
In order to add to the array:content.get(16).add(str);.
Is there a way to output to a file with multiple methods? I used this technique in C++:
// create Scanner for input
static Scanner in = new Scanner(System.in);
// Output survey results to a file
public static void main(String[] args) throws Exception
{
// create Formatter for output
Formatter out = new Formatter("numbers.txt");
// store answer
int ans;
// ask 40 students to rate the food at the cafeteria
// 1 is bad, 10 is good
for(int i = 0; i < 40; i++) {
// ensure answer is between 1 and 10
do {
System.out.print("Rate the food at the cafeteria between 1 (horrid) and 10 (excellent): ");
ans = in.nextInt();
} while(ans > 10 || ans < 0);
// end do-while
} // end for
// close file
out.close();
} // end method main
// Output data
public static void output(Formatter out, int num)
{
// enter data in a file
out.format("%d\n", num);
} // end method output
It compiles, runs, creates the file, et cetera; but when I open the file, if is empty. Any suggestions will be appreciated.
The problem with this is that output() writes the file, but you're never calling output(). Thus, the file is never written. You need to insert:
output(out, ans);
after the end of the do-while, but before the end of the for loop.
assignment:
A school that your little cousin attends is selling cookies. If your cousin's class sells more cookies than any other class, the teacher has promised to take the whole class on a picnic. Of course, your cousin volunteered you to keep track of all the sales and determine the winner.
Each class is identified by the teacher's name. Each sales slip has the teacher's name and the number of boxes sold. You decide to create two parallel arrays: one to hold the teacher's names and one to record the number of boxes sold. Here is a sample of the data:
The first number gives the number of classes, and then a teacher's Name is followed by the number of boxes sold
15
Smith
3
Courtney
... so on so forth
My main issue (because i can just duplicate it for the "to-be" parrallel array)
is getting every other line to save into an array for the boxes sold
so array "boxSold"
would look like
[1] 15
[2] 3
package assignment5Package;
import java.util.Scanner;
import java.io.*;
public class assignment5Demo
{
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
//create arrays, variables
Scanner keyboard = new Scanner(System.in);
BufferedReader input = new BufferedReader
(new FileReader ("/Users/lee/Desktop/class/cs 113/Assignment5/cookies.txt"));
System.out.println("How many sale slips are there");
int numSaleSlips = keyboard.nextInt();
int[] soldBox = new int[numSaleSlips];
//______String[] teacherName = new String[numSaleSlips];
int soldBoxIndex;
int teacherNameIndex;
//String soldBoxString; (line 50)
//initializing both strings to 0 and "_"
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
soldBox[soldBoxIndex] = 0;
}
//**for (teacherNameIndex = 0; teacherNameIndex < numSaleSlips; teacherNameIndex++)
//**{
//** teacherName[teacherNameIndex] = "_";
//**}
//reading from the cookies.txt file
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
if (soldBoxIndex % 2 != 0
{
String soldBoxString;
soldBoxString = input.readLine(); //reads in value and assigns/re-assigns
soldBox[numSaleSlips] = (int) Double.parseDouble(soldBoxString); //type-casted to fit variable type, converts to double, stores in array
System.out.println(soldBox[soldBoxIndex]);
}
else
{
System.out.println("Error at " + soldBoxIndex +".");
}
}
}
The following may be a quick-and-dirty solution, but will get the job done:
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
if (soldBoxIndex % 2 != 0
{
String soldBoxString;
soldBoxString = input.readLine(); //reads in value and assigns/re-assigns
soldBox[numSaleSlips] = (int) Double.parseDouble(soldBoxString); //type-casted to fit variable type, converts to double, stores in array
System.out.println(soldBox[soldBoxIndex]);
}
else
{
input.readLine(); //read the following line, but ignore its content, effectivly skipping the line
}
}
You might also need to work the numbers of the for-loop a bit, to accomodate the skipped line.