Help please, while loop and tokenizer and reading files - java

I need help, obviously. Our assignment is to retrieve a file and categorize it and display it in another file. Last name first name then grade. I am having trouble with getting a loop going because of the error "java.util.NoSuchElementException" This only happens when I change the currently existing while I loop I have. I also have a problem of displaying the result. The result I display is all in one line, which I can't let happen. We are not allowed to use arraylist, just Bufferedreader, scanner, and what i already have. Here is my code so far:
import java.util.;
import java.util.StringTokenizer;
import java.io.;
import javax.swing.*;
import java.text.DecimalFormat;
/*************************************
Program Name: Grade
Name: Dennis Liang
Due Date: 3/31/11
Program Description: Write a program
which reads from a file a list of
students with their Grade. Also display
last name, first name, then grade.
************************************/
import java.util.*;
import java.util.StringTokenizer;
import java.io.*;
import javax.swing.*;
import java.text.DecimalFormat;
class Grade {
public static void main(String [] args)throws IOException {
//declaring
String line = "";
StringTokenizer st;
String delim = " \t\n\r,-";
String token;
String firstname;
String lastname;
String grade;
String S69andbelow="Students with 69 or below\n";
String S70to79 ="Students with 70 to 79\n";
String S80to89= "Students with 80 to 89\n";
String S90to100= "Students with 90 to 100\n";
int gradeint;
double gradeavg = 0;
int count = 0;
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
FileInputStream finput = new FileInputStream(inputFile);
FileOutputStream foutput = new FileOutputStream(outputFile);
FileReader reader = new FileReader(inputFile);
BufferedReader in = new BufferedReader(reader);
Scanner std = new Scanner(new File("input.txt"));
Scanner scanner = new Scanner(inputFile);
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
Scanner scan = new Scanner(S69andbelow);
//reading linev
line = scanner.nextLine();
st = new StringTokenizer(line, delim);
//avoiding selected characters
try {
while(st.hasMoreTokens()) {
firstname = st.nextToken();
lastname = st.nextToken();
grade = st.nextToken();
//storing tokens into their properties
gradeint = Integer.parseInt(grade);
//converting token to int
gradeavg = gradeavg + gradeint;
//calculating avg
count++;
//recording number of entries
if (gradeint <=69) {
S69andbelow = S69andbelow + lastname + " "
+ firstname + " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 70 && gradeint <= 79) {
S70to79 = S70to79 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 80 && gradeint <=89) {
S80to89 = S80to89 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else {
S90to100 = S90to100 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
}//end while
System.out.println(S69andbelow + "\n" + S70to79 + "\n"
+ S80to89 + "\n" + S90to100);
//caterorizing the grades
gradeavg = gradeavg / count;
//calculating average
DecimalFormat df = new DecimalFormat("#0.00");
out.write("The average grade is: "
+ df.format(gradeavg));
System.out.println("The average grade is: "
+ df.format(gradeavg));
Writer output = null;
output = new BufferedWriter(new FileWriter(outputFile));
// scanner.nextLine(S69andbelow);
//output.write(S69andbelow + "\n" + S70to79 + "\n"
// + S80to89 + "\n" + S90to100);
// output.close();
}
catch( Exception e ) {
System.out.println(e.toString() );
}
// Close the stream
try {
if(std != null )
std.close( );
}
catch( Exception e ) {
System.out.println(e.toString());
}
}
}
my input file looks like this:
Bill Clinton 85 (enter)
Al Gore 100 (enter)
George Bush 95 (enter)
Hillery Clinton 83(enter)
John McCain 72(enter)
Danna Green 87(enter)
Steve Delaney 76(enter)
John Smith(enter)
Beth Bills 60(enter)
It would help to point things out just in case I don't follow you all the way through.

An easy way of finding a problem in this would be to comment out most of the code and find out each step at a time. So start with being able to read the file. Then print to the screen. Then print the organized data to the screen. Finally print the organized data to the file.
This should be a fairly simple

Related

How do I read data from file (with specific condition) and display the information on the screen

vaccination.txt
Can someone help me with my codes? I have a problem displaying the information on the screen. I need to display the info based on the question requirement below:
Display all information about those born in Selangor who received the booster dose (dose 3) on screen. The person born in Selangor is represented by two digits there are 10 after the six digits that represent the birth date from the identification (ic) number.
I also have a problem writing the data into the relevant files. I tried the same method (by using the print writer) as what I have done before, but it doesn't work here and Idk why. Do help me
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String\[\] args) {
File inFile = new File ("vaccination.txt");
File comorbid = new File ("comorbid.txt");
File nonComorbid = new File ("non_comorbid.txt");
try {
//read data from file
Scanner sc = new Scanner (inFile);
//write data into file
PrintWriter pw = new PrintWriter(comorbid);
PrintWriter pw2 = new PrintWriter (nonComorbid);
String vaccinePlace = " ", ICnum = " ", category = " ", vaccineType = " ";
int doseNum = 0;
pw.println("Matric Name Part Gender");
pw.println("--------------------------------------------------------------------");
pw2.println("Matric Name Part Gender");
pw2.println("--------------------------------------------------------------------");
while(sc.hasNext()) //check line by line
{
String data = sc.nextLine();
StringTokenizer st = new StringTokenizer(data, ":");
vaccinePlace = st.nextToken();
ICnum = st.nextToken();
category = st.nextToken();
vaccineType = st.nextToken();
doseNum = Integer.parseInt(st.nextToken());
//display information on screen
if (doseNum == 3)
{
if (ICnum.substring(6,8).equalsIgnoreCase("10"))
{
System.out.println("Vaccine place: " + vaccinePlace);
System.out.println("IC number: " + ICnum);
System.out.println("Category: " + category);
System.out.println("Vaccine type: " + vaccineType);
System.out.println("Dose number: " + doseNum);
}
}
//write and store information into comorbid.txt and nonComorbid file
if (category.equalsIgnoreCase("comorbid")) {
pw.println(vaccinePlace + " " + ICnum + " " + vaccineType + " " + doseNum);
}
if (category.equalsIgnoreCase("non-comorbid")) {
pw.println(vaccinePlace + " " + ICnum + " " + vaccineType + " " + doseNum);
}
} //end loop
sc.close();
pw.close();
pw2.close();
}
catch (FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}

How can I pull elements from a file when needed?

I am trying to write a program to create player objects and save them to a file(Which I have done).
The problem I am trying to resolve is, I want to be able to pull the players out of the file when needed. So if I want to get the information for just player 1 or player n, with just their details is there a way I can pull it from the file if needed?
Any help or ideas would be greatly appreciated.
Thanks very much for your help in advance.
package p;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Runner {
public static final Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("output.txt", true);
PlayerData player = null;
List<PlayerData> players = new ArrayList<>();
System.out.println("How many players do you want to register? : ");
int num = input.nextInt();
while (true) {
System.out.println("Plz enter Name : ");
String name = input.next();
writer.write("Name: " + name + System.lineSeparator());
System.out.println("Plz enter age : ");
String age = input.next();
writer.write("Age: " + age + System.lineSeparator());
System.out.println("Plz enter Player_id : ");
String player_id = input.next();
writer.write("Player_id: " + player_id + System.lineSeparator());
System.out.println("Plz enter agent_id : ");
String agent_id = input.next();
writer.write("Agent_id:" + agent_id + System.lineSeparator());
System.out.println("Plz enter status : ");
String status = input.next();
writer.write("Status: " + status + System.lineSeparator());
System.out.println("Plz enter position : ");
String position = input.next();
writer.write("Position: " + position + System.lineSeparator());
System.out.println("Plz enter valuation : ");
Double valuation = input.nextDouble();
writer.write("Value: " + valuation + System.lineSeparator());
writer.write("\n " + System.lineSeparator());
System.out.println("\n");
player = new PlayerData(name, age, player_id, agent_id, valuation, status, position);
players.add(player);
System.out.println("Information Entered: \n" + player + "\n" + "Name : " + name + "\n" + "Age: " + age
+ "Player id: " + player_id + "\n" + "Agent id: " + agent_id + "\n" + "Player Value: " + valuation
+ "\n" + "Player Status:" + status + "\n" + "Player position:" + position + "\n");
writer.close();
if (players.size() == num)
break;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("output.txt")));
String line = " ";
System.out.println("Current Players on the transfer List \n");
while ((line = reader.readLine()) != null) {
System.out.println(line);
} // while
reader.close();// close reader
}
}
Maybe something along the lines of this, first while loop should get you to a place where the player name matches your input name , next while will get the next 7 lines into the playerinfo list.
public FileReader fr = new FileReader("path/to/your/file");
public BufferedReader br = new BufferedReader(fr);
String playerName = "John";
String line;
List<String> playerInfo = new ArrayList<String>();
while((line = br.readLine()) != null){
if (line.contains(playerName))
{
int numLines = 7;
playerInfo.add(line);
while((line = br.readLine()) != null && numLines >= 1){
playerInfo.add(line);
numLines --;
break;
}
break;
}
}
You might try using Java Object Serialization:
Java Object Serialization (Oracle)
I guess regardless of whether you use your current method or Object Serialization, you could save each player to a different file.

While loop overwriting other inputs

Whenever I put inputs into this loop, no matter how many it will only write my final input to the file
Here's the code:
import java.util.Scanner;
import java.io.IOException;
import java.io.*;
class lista {
public static void main(String[] args) throws IOException {
Scanner n = new Scanner(System.in);
int x = 0;
File productList = new File("productList.txt");
FileWriter fr = new FileWriter("productList.txt", true);
/// While Loop Start
while (x == 0) {
System.out.println("Enter the product:");
String product = n.nextLine();
System.out.println("");
System.out.println("Enter the price:");
String price = n.nextLine();
System.out.println("");
System.out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
String type = n.nextLine();
System.out.println("");
System.out.println(product + " - " + "$" + price + " (" + type + ")" + "\n\n");
try {
fr.write((product + " - " + "$" + price + " (" + type + ")" + "\n\n"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Type \"0\" if you would like to stop, type \"1\" if you would like to continue.");
int y = n.nextInt();
n.nextLine();
if (y == 1) {
x = 0;
} else {
x = 1;
fr.close();
}
}
/// While Loop Ends
}
}
I can input something like,
1,1,1,1
2,2,2,1
3,3,3,0
, and it will only print:
3 - $3 (3)
Thanks.
This is a possible duplicate of Trouble with filewriter overwriting files instead of appending to the end.
However you seem to have found the solution yourself already (the true parameter when creating the FileWriter). This should append to the file instead of overwriting it. If this does not work, then you might have a problem with the file or the OS. In any case, your code is not fundamentally wrong and should work.
Some suggestions for readability and ease of use on the code itself (just minor details).
Scanner in = new Scanner(System.in);
PrintStream out = System.out;
try (FileWriter writer = new FileWriter("productList.txt", true)) {
INPUT_LOOP:
while (true) {
out.println("Enter the product:");
String product = in.nextLine();
out.println();
out.println("Enter the price:");
String price = in.nextLine();
out.println();
out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
String type = in.nextLine();
out.println();
String entry = product + " - " + "$" + price + " (" + type + ")" + "\n\n";
out.println(entry);
writer.append(entry);
out.println("Type \"exit\" if you would like to stop, any other input will continue.");
if (in.nextLine().trim().toLowerCase().equals("exit")) {
break INPUT_LOOP;
}
}
} catch (IOException e) {
e.printStackTrace();
}

code works but it keeps giving me the error: InputMismatchException and

I'm trying to work on a java program that takes prices from a text file, allows people to enter in the quantity of what they want, and print it out into another text file.
sample code
import java.io.*;
import java.lang.Math;
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.*;
// work on invoice
public class lab2_notes{
public static void main(String[] args)throws IOException {
Scanner fileIn = null;
try
{
// Attempt to open the file
// file should be in working directory
fileIn = new Scanner(new FileInputStream("prices.txt"));
}
catch (FileNotFoundException e)
{
// If the file could not be found, this code is executed
// and then the program exits
System.out.println("File not found.");
// Shut the entire operation down
System.exit(0);
}
//convert file items to strings and numbers
String food_one;
double price_one;
String food_two;
double price_two;
String food_three;
double price_three;
//give strings and numbers varibles
food_one = fileIn.nextLine();
//fileIn.nextLine();
price_one = fileIn.nextDouble();
fileIn.nextLine();
food_two = fileIn.nextLine();
//fileIn.nextLine();
price_two = fileIn.nextDouble();
//fileIn.nextLine();
food_three = fileIn.nextLine();
//fileIn.nextLine();
price_three = fileIn.nextDouble();
//give input varibles for user to enter in how much food they want
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = keyboard.nextLine( );
System.out.println("Enter your zip code: ");
int zip = keyboard.nextInt( );
System.out.println(food_one + " " + price_one);
int quanity_one = keyboard.nextInt( );
System.out.println(food_two + " " + price_two);
int quanity_two = keyboard.nextInt( );
System.out.println(food_two + " " + price_two);
int quanity_three = keyboard.nextInt( );
//use methods to work the code out
double pr_one = total_for_items(quanity_one, price_one);
double pr_two = total_for_items(quanity_two, price_two);
double pr_three = total_for_items(quanity_three, price_three);
double sub_total = (pr_one + pr_two + pr_three);
double taxation = tax(sub_total);
double final_total = grand_total(sub_total, taxation);
String invoice = Invoice(name, zip);
//convert to deciminal class
DecimalFormat df = new DecimalFormat("$#,###,##.##");
String con_sub = df.format(sub_total);
String con_tax = df.format(taxation);
String con_final = df.format(final_total);
String con_one = df.format(pr_one);
String con_two = df.format(pr_two);
String con_three = df.format(pr_three);
//print out recept on screen
System.out.println("Invoice Number: " + invoice);
System.out.println("Item Quantity Price Total");
System.out.println("======================================");
System.out.printf(food_one + " " + con_one + " " + price_one + " " + pr_one);
System.out.println(food_two + " " + con_two + " " + price_two + " " + pr_two);
System.out.println(food_three + " " + con_three + " " + price_three + " " + pr_three);
System.out.println("======================================");
System.out.println("Subtotal: " + con_sub);
System.out.println("6.25% sales tax: " + con_tax);
System.out.println("Total: " + con_final);
String a = "Invoice Number: " + invoice + "\n";
String b = "Item Quantity Price Total" + "\n";
String c = food_one + " " + con_one + " " + price_one + " " + pr_one + "\n";
String d = food_two + " " + con_two + " " + price_two + " " + pr_two + "\n";
String e = food_three + " " + con_three + " " + price_three + " " + pr_three + "\n";
String f = "======================================";
String g = "Subtotal: " + con_sub + "\n";
String h = "Total: " + con_final + "\n";
//print recept on a self-created text file
PrintWriter recept = new PrintWriter("recept.txt", "UTF-8");
recept.println(a + b + c + d + e + f + g + h);
recept.println();
recept.close();
fileIn.close();
}
public static double total_for_items(double qone, double price){
double total_one = qone * price;
return total_one;
}
public static double tax(double total){
double tax_amt = total * Math.pow(6.25, -2);
return tax_amt;
}
public static double grand_total(double total, double tax){
double g_total = total + tax;
return g_total;
}
public static String Invoice(String name, int zip_code){
String part_one = name;
int part_two = zip_code;
Scanner pileIn = null;
try
{
// Attempt to open the file
// file should be in working directory
pileIn = new Scanner(new FileInputStream(part_one));
}
catch (FileNotFoundException e)
{
// If the file could not be found, this code is executed
// and then the program exits
System.out.println("File not found.");
// Shut the entire operation down
System.exit(0);
}
String Fname;
String Lname;
Fname = pileIn.nextLine();
pileIn.nextLine();
Lname = pileIn.nextLine();
//first part of name
String fnone = Fname.valueOf(Fname.charAt(1));
String fntwo = Fname.valueOf(Fname.charAt(2));
//second part of name
String lnone = Lname.valueOf(Lname.charAt(1));
String lntwo = Lname.valueOf(Lname.charAt(1));
//convert letters to uppercase
String con_fone_let = fnone.toUpperCase();
String con_ftwo_let = fntwo.toUpperCase();
String con_lnone_let = lnone.toUpperCase();
String con_lntwo_let = lntwo.toUpperCase();
String invoice_result = con_fone_let + con_ftwo_let + con_lnone_let + con_lntwo_let + zip_code;
return invoice_result;
}
}
However every time I start it, this error message pops up:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at lab2_notes.main(lab2_notes.java:46)
I'm new to coding with java and have been screwing with line 46 for hour now trying to figure it out.
what am I doing wrong?
Thanks, HG
Take input food_one to price three like this:
food_one = fileIn.nextLine();
price_one = fileIn.nextDouble();
fileIn.nextLine();
food_two = fileIn.nextLine();
price_two = fileIn.nextDouble();
fileIn.nextLine();
food_three = fileIn.nextLine();
price_three = fileIn.nextDouble();
It should work.
I changed the format in which you are storing the food and price (in prices.txt) to the following (with food and price separated by a delimiter, in this case a colon)
Pizz:20.10
Burger:10.30
Coffee:5.99
I changed the code to the following and now it is working. Hope this helps
// give strings and numbers varibles
String[] foodPrice = fileIn.nextLine().split(":");
food_one = foodPrice[0];
price_one = Double.parseDouble(foodPrice[1]);
foodPrice = fileIn.nextLine().split(":");
food_two = foodPrice[0];
price_two = Double.parseDouble(foodPrice[1]);
foodPrice = fileIn.nextLine().split(":");
food_three = foodPrice[0];
// fileIn.nextLine();
price_three = Double.parseDouble(foodPrice[1]);
Forgot to comment out fileIn.nextLine(); around like 46
your trying to put the name of a food into a nextDouble()
//give strings and numbers varibles
food_one = fileIn.nextLine();
//fileIn.nextLine();
price_one = fileIn.nextDouble();
fileIn.nextLine();
food_two = fileIn.nextLine();
//fileIn.nextLine();
price_two = fileIn.nextDouble();
//fileIn.nextLine();
food_three = fileIn.nextLine();
//fileIn.nextLine();
price_three = fileIn.nextDouble();
Should be:
//give strings and numbers varibles
food_one = fileIn.nextLine();
//fileIn.nextLine();
price_one = fileIn.nextDouble();
//fileIn.nextLine();
food_two = fileIn.nextLine();
//fileIn.nextLine();
price_two = fileIn.nextDouble();
//fileIn.nextLine();
food_three = fileIn.nextLine();
//fileIn.nextLine();
price_three = fileIn.nextDouble();

Finding median word length of text file with multiple lines

I have a text file, and I want to find the middle word of the whole file and print the number of characters it has. I can do this for one line:
System.out.println("'" + str[tok / 2] + "'");
But I don't know how to point to a certain line. Here is all of my code:
import java.io.*;
import java.text.*;
import java.util.*;
public class AmendClassify {
public static void main(String[] args) {
try {
System.out.println("Please enter the file name:");
Scanner sc = new Scanner(System.in);
String file = sc.next();
file = file + ".txt";
Scanner s = new Scanner(new FileReader(file));
System.out.println("You are scanning '" + file + "'");
PrintWriter output = new PrintWriter(new FileOutputStream("output.txt"));
double lineNum = 0;
double wordCount = 0;
double charCount = 0;
int tok = 0;
String str[] = null;
DecimalFormat df = new DecimalFormat("#.#");
String line = null;
while (s.hasNextLine()) {
line = s.nextLine();
lineNum++;
str = line.split((" "));
tok = str.length;
for (int i = 0; i < str.length; i++) {
if (str[i].length() > 0) {
wordCount++;
}
}
charCount += (line.length());
}
double density = (charCount / wordCount);
System.out.println("'" + str[tok / 2] + "'"); // middle word of the 1st/last line
gap();
System.out.println("Number of lines: " + lineNum);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters: " + charCount);
gap();
System.out.println("The DENSITY of the text is: " + df.format(density));
System.out.println();
int critical;
System.out.println("Do you want to alter the critical value(Y/N)");
String answer = sc.next();
if (answer.equals("y") || answer.equals("Y")) {
System.out.println("Please enter a value: ");
critical = sc.nextInt();
} else {
critical = 6;
}
//So...
if (density > critical) {
System.out.println("NAME: '" + file + "'" + ", DENSITY: " + df.format(density) + ", TYPE: " + "Heavy");
} else {
System.out.println("NAME: '" + file + "'" + ", DENSITY: " + df.format(density) + ", TYPE: " + "Light");
}
System.out.print("--FINISHED--");
s.close();
output.close();
sc.close();
} //end of try
catch (FileNotFoundException e) {
System.out.println("Please enter a valid file name");
}
} // end of main
public static void gap() {
System.out.println("------------------------------");
}
}
A text file I have used to test is
Hello my name is Harry. This line contains 83 characters, 15 words, and 1 line(s).
This is the second line.
This is the third line.
This is the fourth line.
Since this looks like a homework assignment I'd recommend reading the entire file into a String and then removing all new-line characters with replaceAll() if need be (depending how you read the entire file into a String). You then would effectively have a single line ... so your existing code would work (taking into account that the middle word would actually be the word to the left of the middle if the file has an even number of words).
Note that this is not an optimal solution though. Don't use it at work.

Categories