java program read and print to text file using Scanner - java

I am trying to read a text file, and then display the output in another file.
I can only read using Scanner.
input.txt
3005045 7
3245436 0
7543536 3
8684383 -1
output.txt should be like
ID Number of Bags Total Cost
** ************** **********
customer pays 20.50 per bag if the bag is 4 or less.
and pays 15.50 per bag if the bag greater than 4.
but if it's 0 or negative number this message should appeared "Error : Wrong Number of Bags"
I did this program, but it works only once(reads one line only)
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Bags {
public static void main(String []args) throws IOException {
FileInputStream fileinput = new FileInputStream("input.txt");
FileOutputStream fileoutput = new FileOutputStream("output.txt");
Scanner infile = new Scanner(fileinput);
PrintWriter pw = new PrintWriter(fileoutput);
double total = 0, line = 0;
int bags = 0, ID = 0, count = 0;
pw.println("ID\t\tNumber of Bags\t\t\tTotal Cost");
for(int i = bags; i >= 0; i++, count++){
ID = infile.nextInt();
i = infile.nextInt();
if (i <= 0){
pw.println(ID + "\tError: Wrong Number of Bags\t\t\t");
break;
}
else if (i <= 4){
total = (80.50)*i;
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
break;
}
else {
total = ((80.50)*4)+((75.50)*(i-4));
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
break;
}
}
infile.close();
pw.close();
}
}

You don't need that for loop over there. Also, you want to read line by line. Here is quick fix of your code:
public class Bags {
public static void main(String[] args) throws IOException {
FileInputStream fileinput = new FileInputStream("input.txt");
FileOutputStream fileoutput = new FileOutputStream("output.txt");
Scanner infile = new Scanner(fileinput);
PrintWriter pw = new PrintWriter(fileoutput);
double total = 0, line = 0;
int bags = 0, ID = 0, count = 0;
pw.println("ID\t\tNumber of Bags\t\t\tTotal Cost");
while(infile.hasNext()){
ID = infile.nextInt();
int i = infile.nextInt();
if (i <= 0) {
pw.println(ID + "\n\t\tError: Wrong Number of Bags\t\t\t");
} else if (i <= 4) {
total = (80.50) * i;
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
} else {
total = ((80.50) * 4) + ((75.50) * (i - 4));
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
}
}
infile.close();
pw.close();
}
}
Output.txt
ID Number of Bags Total Cost
3005045 7 548.503245436
Error: Wrong Number of Bags
7543536 3 241.508684383
Error: Wrong Number of Bags

You should not use i to save "number of bags". See the line i = infile.nextInt();. Use another variable, then you should be fine. Also, you should keep reading until end of file, so you probably wouldn't be able to write a for (int i = 0; i < n; i++)-style of loop.

There is no surprise that loop can iterates only one time. In each case you have break.
Also in this case you shouldn't be using for loop, and especially not the way you are using it now. Just take a look at it, your loop would end only when this condition i >= 0 would be false, which means i would have to be negative, but even when i would become -1 like last number from your input it would still be incremented at the end of iteration thanks to i++ so you would end up with 0 >= 0 condition which is true, so loop would try to iterate again)
Instead use
while(scanner.hasNextInt())
This way you will make sure that you will read int from file only when there will be next one to read. Just use your predefined bugs variable instead of i.
Another thing is that you are not including line separators in your printf formats. Add %n at the end of each one of them, and don't use \t but specify space you want each number to hold like
pw.printf("%d %9d %40.2f%n",...);

Related

How to keep track of the sum of each of the three columns Java

My Question is how to get my program to add each column separately and then find the average afterwards. E.g. 33+42+11 /3 expressed in Java.
Hope that clarifies the question.
I have also linked the numbers and columns below
import java.util.Arrays;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
public class Assignment
{
public static void main(String[] args)
throws IOException
{
FileInputStream control = null;
Scanner scanner = null;
if (args.length == 0) {
System.out.println("file name expected");
System.exit(0);
}
System.out.println("Opening file " + args[0]);
control = new FileInputStream(args[0]);
System.out.println("Opening of file " + args[0] + " successful");
scanner = new Scanner(control);
long sum = 0;
int count = 0;
if (!scanner.hasNext()) {
System.out.println("No integers");
System.exit(0);
}
while (scanner.hasNext()) {
long number = scanner.nextInt();
sum += number;
count++;
}
long average = sum / count;
System.out.println(average);
control.close();
}
}
This is the columns. Not too sure about how to make it start adding from 127 down to 10 and same for the other two columns
127 33 22
2147483647 42 59
10 11 55
I think I was able to interpret the question.
Here is a working solution - note that you need to scan for one line at a time with one scanner, and then scan each of those lines to break it up into columns. I then stored each of those sums and counts in an array, as you mentioned you wanted to use arrays. However, I just made those arrays hold up to 10 counts, and didn't do any sizing checks on those - those types of issues seemed outside the scope of the original question.
https://repl.it/repls/TintedNarrowRectangle
import java.util.Scanner;
public class Main {
public static void main(String[] args){
String fakeFileInput = " 127 33 22\n2147483647 42 59\n10 11 55";
Scanner scanner = new Scanner(fakeFileInput);
if (!scanner.hasNext()) {
System.out.println("No integers");
System.exit(0);
}
long[] sums = new long[10];
int[] counts = new int[10];
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Scanner innerScan = new Scanner(line);
int current = 0;
while (innerScan.hasNextInt()) {
int number = innerScan.nextInt();
sums[current] += number;
counts[current] += 1;
current++;
}
}
for (int i = 0; i < sums.length; i++) {
System.out.println((1.0*sums[i])/counts[i] + " average for " + i + " column");
}
}
}
I am just providing a 3 * 3 grid solution and my goal is to keep each column summation. My final output would be like {(127+2147483647+ 10), (33+42+11), (22+59+55)}
For that, you just need to maintain another array. For example, you will keep each column summation in sum[] array.
Since you have only 3 columns, you just need sum[] size 3.
int[] sum = new int[3]
After allocation, you can reset sum arrays each index value 0.
for (int i = 0; i < 3; i++) {
sum[i]=0
}
Now the only thing left is taking each row input value. Since you have only 3 columns in each row and totally of 3 raws. You can follow below code snippet.
for (int i=0;i<3;i++){
for(int j=0;j<3;j++){
int number = scanner.nextInt();
sum[i] = sum[i] + number;
}
}
Now you can use sum[] array for your final result. Each sum[] index holds on each column summation.

Best way to read CSV file and store (array, 2darray?) and print to screen in tabular format?

The thing i'm hoping to do is read a csv file with 6 rows and 6 columns in it using Java. I then need to print out each row and allow the user to select 1 option. Here is what I have, I know my code chooses 1 and prints it, but I don't know how to change it from printing one random row, to printing all 6 rows. Probably in an ArrayList or 2dArray?
package theContest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;
public class theContest {
// The main() method
public static void main(String[] args) throws FileNotFoundException {
//
String fileName = "contest.csv";
File file = new File(fileName);
if (!file.isFile()) {
System.err.println("Cannot open file: " + fileName + ".");
System.exit(0);
}
//
int numContest = 0;
Scanner input = new Scanner(file);
while (input.hasNext()) {
input.nextLine();
numContest++;
}
input.close();
System.out.println("Total of " + numContest + " contestants.");
//
int winner = 0;
Random random = new Random();
winner = random.nextInt(numContest) + 1;
System.out.println("The winner is contestant number " + winner + ".");
//
String winnerDetails = "";
input = new Scanner(file);
for (int lineCount = 0; lineCount < winner; lineCount++) {
winnerDetails = input.nextLine();
}
input.close();
System.out.println("Winner is: " + winnerDetails);
//
String id = "";
String name = "";
String seats = "";
String trans = "";
String rate = "";
String price = "";
input = new Scanner(winnerDetails);
input.useDelimiter(",");
id = input.next();
name = input.next();
seats = input.next();
trans = input.next();
rate = input.next();
price = input.next();
input.close();
System.out.println("Details are:");
System.out.printf("%-5s : %s\n", "ID", id);
System.out.printf("%-5s : %s\n", "Name", name);
System.out.printf("%-5s : %s\n", "Seating", seats};
System.out.printf("%-5s : %s\n", "Transfer", trans};
System.out.printf("%-5s : %s\n", "Rate", rate};
System.out.printf("%-5s : %s\n", "Price", price};
}
}
Here:
for (int lineCount = 0; lineCount < winner; lineCount++) {
winnerDetails = input.nextLine();
}
Your file has N rows. The above code iterates all lines, and stores the result in a single variable. In each iteration, you overwrite what you put there before. So, what your code does is: it reads N lines, and throws away everything prior the last row.
In other words: if you have 6 lines, and you want to print all of them ... then that all your processing needs to be "part" of a loop, too.
For example, you could turn winnerDetails into an array of String, and then put each line in its own slot. Then you loop over the array, and print each slot.
And as you already know about ArrayList, best use that then. That also means: you need to read the file only once. Open the file, read each line, and push that into an ArrayList. Afterwards, you can do whatever you want with that list.
And note: that is actually the point you should start with. Dont solve your whole problem at once. Slice it into smaller parts. Like: reading data from CSV ... has nothing to do with later processing the lines and printing those. You can write code that just takes an ArrayList, processes those and prints stuff. Which you can ... test on its own, as you can hardcode such lists in your code.

I don't think that my array is storing and data

I am new to java and I am taking a college course right now. I was just curious what I am missing to give myself an output because right now the console is blank.
public static void main(String[] args) throws IOException {
double avgScore;
int highestScore, count = 0;
String highScoringStudent;
String names[] = null;
int scores[] = null;
File myFile = new File("Student_Data.txt");
Scanner inFile = new Scanner(myFile);
inFile.nextLine();
while(inFile.hasNext()) {
for(int i = 0; i > 0; i++) {
names[i] = inFile.next();
scores[i] = inFile.nextInt();
count++;
}
}
System.out.print("Name Score");
System.out.print(names[count] + " " + scores[count]);
}
First of all, I really wouldn't suggest to place a for inside a while loop, especially in this case (because it doesn't work). Here are the problems:
1) Your for loop starts with i = 0, and finishes right away, because !(i > 0) (i is not > 0) - so you are right, no data will be stored in the array!
2) Inside your for loop, you are reading a string, then an int one by one. After you have read them, you should move to the next string and integer to store in the next position of names and score.
3) You are not increasing i: so (if the for was working), you would just keep assigning different values to the array, at the same position (basically resetting the value of a variable every time).
This would be the best code that would work for your case:
int i = 0;
while(inFile.hasNext()) {
names[i] = inFile.next();
scores[i] = inFile.nextInt();
count++;
i++;
}
Hope this helped! :)

Why doesn't my program read my file that was created using the same program?

I'm trying to create a program that makes a file that randomly generates numbers and I want the program to read those numbers off of the file and analyze it. If the randomly generated number doesn't equal 0, the program should keep generating numbers, but if it does equal 0, then the program will stop. However, it seems that my program is not reading those numbers.
I tried putting the outFile.close(); and inFile.close(); in a couple different places to see if that would fix anything, but it seems that didn't work out. I tried tracing my code with pen and paper, but I couldn't find anything wrong. Perhaps it could be my placement of outFile.close(); and inFile.close();, but I couldn't find anything wrong with it.
import java.util.*;
import java.io.*;
public class squirrel {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(new File("squirrel.txt"));
Scanner inFile = new Scanner(new File("squirrel.txt"));
Random rand = new Random();
int squirrelNum;
int foxSquirrel = 0;
int squirrelsSeen = 0;
int trials = 0;
System.out.println("Welcome to the Fox Squirrel Simulator\n");
System.out.println("How many trials should be simulated?");
System.out.println("Enter a value greater than 1000: ");
trials = in.nextInt();
while(trials <= 1000)
{
System.out.println("Please try again. Enter a value greater than 1000: ");
trials = in.nextInt();
}
for(int i = 0; i <= trials; i ++)
{
squirrelNum = rand.nextInt(10);
outFile.println(squirrelNum);
while(inFile.hasNextInt())
{
int token = inFile.nextInt();
while(token != 0)
{
squirrelsSeen ++;
}
if(token == 0)
{
foxSquirrel ++;
squirrelsSeen ++;
}
outFile.close();
}
System.out.println("squirrelsSeen: " + squirrelsSeen);
System.out.println("foxSquirrel: " + foxSquirrel);
}
inFile.close();
System.out.println("\nsimulating trials now... one moment please...\n");
System.out.println("The results!");
System.out.println("The average number of squirrels until spotting a Fox Squirrel at the city park is: " + (((double)foxSquirrel / squirrelsSeen) * 100));
}
}
And here is how it is done using Scanner.
File file = new File("squirrel.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
And it is like you said. You put the .close() inside your while loop in your code. Try putting it outside.
new PrintWriter(new File("squirrel.txt")) immediately erases the file. From the documentation:
If the file exists then it will be truncated to zero size; otherwise, a new file will be created.
It is not possible to read and write the same file simultaneously. (Actually there are some cases were it’s possible, but they don’t apply here.)
Do not create your PrintWriter until you have finished reading from the file and have called inFile.close(). Or, write to a different file, then when you’re done, rename it to match the original file.

For loop for printing to file loads forever and file blank even though closed?

I am trying to write code that simulated the Monte-Carlo method for more than 1000 trials by choosing a random number out of 10 and until the number is 10 then a counter for (number of squirrels observed) will be increased each time until the random number is 10; this counter will then be printed to a file. However this is done with a For loop with nested loops within in but the program seems to load forever once at this For loop and the file remains blank even though the close() is used.
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;
import java.util.Random;
public class AnimalPopulation
{
public static void main(String[] args) throws IOException
{
//declare and initialize variables
Random randsquirrel = new Random();
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(new File ("squirreldata.txt"));
// User input
System.out.println("Welcome to the Fox Squirrel Simulator");
System.out.println("\n");
System.out.println("How many trials should be simulated?");
System.out.println("Enter a value greater than 1000:");
int trialcounter = in.nextInt();
// Input does not match requirements
while (trialcounter <= 1000)
{
System.out.print("\n\n Please try again. Enter a number greater than 1000.");
System.out.println();
System.out.println("How many trials should be simulated?");
System.out.println("Enter a value greater than 1000:");
trialcounter = in.nextInt();
}
System.out.println("\nsimulating trials now... one moment please ...");
// Experiment with ratio of 1/10 fox squirrels
int randomsquirrel = 0;
int totalsquirrels = 0;
for (int i = 1; i <= trialcounter; i++)
{
randomsquirrel = randsquirrel.nextInt(10)+1;
while (randomsquirrel != 10)
{
totalsquirrels++;
}
if (randomsquirrel == 10);
{
totalsquirrels++;
}
outFile.println(totalsquirrels);
}
outFile.close();
// Read file and print result
File readfile = new File ("squirreldata.txt");
Scanner readFile2 = new Scanner(readfile);
Double trialtotalsquirrels = 0.0;
while(readFile2.hasNextLine())
{
String token = readFile2.nextLine();
int totalsquirrels2 = Integer.parseInt(token);
trialtotalsquirrels += totalsquirrels2;
}
readFile2.close();
System.out.println();
System.out.println("The results!");
System.out.println("The average number of squirrels observed until\n spotting a Fox Squirrel at the city part is: " + trialtotalsquirrels/trialcounter);
}
}
Can you tell me what's wrong here?
randomsquirrel = randsquirrel.nextInt()+1;
while (randomsquirrel != 10)
{
totalsquirrels++;
}
While loops has 3 parts the while key word, the (condition), and the {lines to run}
while (condition) {
//lines to run.
}
First the condition is checked if it is turn it will perform all the lines to run.
After all the lines are done it checks the condition again. If the condition is still true it will run all the lines again. It will keep on running the lines forever until the condition becomes false or hits a break.
You use incorrect while because you will never change value in while loop and this cause a infinite loop. The correct way:
public static void main(String[] args) throws IOException
{
SecureRandom randsquirrel = new SecureRandom(); // it is better
// rest of your code
int randomsquirrel = 0;
int totalsquirrels = 0;
for (int i = 1; i <= trialcounter; i++)
{
randomsquirrel = randsquirrel.nextInt(10)+1;
while (randomsquirrel != 10)
{
randomsquirrel = randsquirrel.nextInt(10) + 1:
totalsquirrels++;
if (randomsquirrel == 10);
break;
}
}
// rest of your code
}

Categories

Resources