This question already has an answer here:
Scanner only reads file name and nothing else
(1 answer)
Closed 5 years ago.
This program prompts the store owner for the amount of cash at the beginning and end of the day, and the name of the file. It should check whether the actual amount of cash at the end of the day equals the expected value.
I have a txt file where each line contains three items: The invoice number, the cash amount, and the letter P if the amount was paid or R if it was received. Items are separated by spaces.
I am having trouble with this piece in my code
while (filename.hasNext()) {
invoice.add(filename.nextInt());
cash.add(filename.nextDouble());
PR.add(filename.next());
}
It is a syntax error saying I cannot use .nextInt() .nextDouble() .next() hasNext()
Here is the full source code:
import java.io.*;
import java.util.*;
/**
* Code for P11.11. This program takes in a list of baby names and outputs a list of boys and
* girls names.
*
* #Michael Goedken
*/
public class BalanceTransactions {
public static void main(String[] args) throws FileNotFoundException {
// The following lines ask the user to enter the file name and the balances at the beginning and the end
Scanner in = new Scanner(System.in);
System.out.print("Please enter the file name for input: ");
String filename = in.next();
System.out.print("Please enter the cash amount at the start: ");
double start = in.nextDouble();
System.out.print("Please enter the cash amount at the end: ");
double end = in.nextDouble();
ArrayList<Integer> invoice = new ArrayList<Integer>();
ArrayList<Double> cash = new ArrayList<Double>();
ArrayList<String> PR = new ArrayList<String>();
while (filename.hasNext()) {
invoice.add(filename.nextInt());
cash.add(filename.nextDouble());
PR.add(filename.next());
}
for (int i = 0; i < invoice.size(); i++) {
if (PR.get(i).equals("P")) {
start -= cash.get(i);
}
if (PR.get(i).equals("R")) {
start += cash.get(i);
}
}
if (start == end || (double) Math.round(start * 1000000000) / 1000000000 == end) {
System.out.println("There is the correct amount in the register.");
} else {
Double difference = ((double) Math.round(start * 100000) / 100000) - end;
System.out.println("You are off by: " + difference);
}
}
}
EDIT: I added a new scanner now I get this error
Scanner fileScanner = new Scanner("/Users/MichaelGoedken/Desktop/transactions.txt");
while (fileScanner.hasNext())
{
invoice.add(fileScanner.nextInt());
cash.add(fileScanner.nextDouble());
PR.add(fileScanner.next());
}
ERROR:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at BalanceTransactions.main(BalanceTransactions.java:34)
If you want to scan a file, try to use this constructor:
/**
* Constructs a new Scanner that produces values scanned
* from the specified file. Bytes from the file are converted into
* characters using the specified charset.
*
* #param source A file to be scanned
* #throws FileNotFoundException if source is not found
*/
public Scanner(File source) throws FileNotFoundException {
this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
}
Right now you are using this constructor, it doesn't make any sense, because you pass as a parameter String:
public Scanner(String source) {
this(new StringReader(source), WHITESPACE_PATTERN);
}
Related
I would appreciate knowing how to tackle this type of problems. Thank you in advance.
Here is the question.
The first line of the files contains two integer numbers ;
number-of-records exam-grade
number-of-records : indicates number of the records in the file.
exam-grade : indicates the grade of the exam.
The file follows by students name and their grades.
Sample File: test1.txt
Contains four records, and the exam is out of 80. The file follows by the name and grade of the students:
4 80
Mary 65.5
Jack 43.25
Harry 79.0
Mike 32.5
You have to develop the body of following method:
public static void readWrite(String srcfileName, String dstFileName)
That reads grades of each student from srcFileName, calculates their grade percent, indicates that if student passed or failed, and finally reports the class average, number of the students passed, and number of the students failed the exam and saves the result in dstFileName.
The output file for the previous test file should be:
Mary 81.88 passed
Jack 54.06 passed
Harry 98.75 passed
Mike 40.63 failed
class average:68.83
passed: 3
failed: 1
here is the code I wrote for it,
import java.util.*;
import java.io.*;
public class Lab10Quiz {
public static void main(String[] args) throws FileNotFoundException
{
// Test cases
readWrite("test1.txt", "out1.txt");
readWrite("test2.txt", "out2.txt");
}
/** copies the content of the srcFileName into dstFileName, and add the average of the number to the end of the dstFileName
#param srcFileName : souce file name contains double numbers
#param dstFileName : destination file name
*/
public static void readWrite(String srcFileName, String
dstFileName) throws FileNotFoundException {
// Your code goes here
File output = new File(dstFileName);
PrintWriter outPut = new PrintWriter(output);
double avg = 0;
int count = 0;
double tmp = 0;
Scanner in = new Scanner(new File(srcFileName));
while (in.hasNextDouble()) {
tmp = in.nextDouble();
avg += tmp;
outPut.println(tmp);
count ++;
}
avg = avg / count;
outPut.println("Average = " + avg);
outPut.close();
}
}
This code achieves what you want
double avg = 0;
int failCounter = 0;
String[] keywords = in.nextLine().split(" ");
int studentNumber = Integer.parseInt(keywords[0]);
double examValue = Double.parseDouble(keywords[1]);
for (int i = 0; i < studentNumber; i++) {
keywords = in.nextLine().split(" ");
String studentName = keywords[0];
double studentMark = Double.parseDouble(keywords[1]);
double grade = calculateTotalGrade(studentMark, examValue);
failCounter += (hasFailed(grade) ? 1 : 0);
avg += grade;
outPut.println(String.format("%s \t\t %.2f \t\t %s", studentName, grade, hasFailed(grade) ? "failed" : "passed"));
}
avg = avg / studentNumber;
outPut.println("class average: " + avg);
outPut.println("passed: " + (studentNumber - failCounter));
outPut.println("failed: " + failCounter);
And I extracted some of the logic to below methods.
private static double calculateTotalGrade(double grade, double examValue) {
return grade * 100 / examValue;
}
private static boolean hasFailed(double grade) {
return grade < 50;
}
To answer how to tackle this type of questions:
Look for the simplest way. In this case looping for a finite iterations was easier. So I went with the for loop.
The counter is already given, No need to re-calculate it.
If you are working on a computer, write a little code and test it.
Do more questions like these. (if you go through the first chapters of this book these questions will be easy)
This question already has answers here:
Reached end of file while parsing compilation error
(3 answers)
Closed 3 years ago.
I am getting an error BankInterest(line 93): reached end of file while parsing, anyone know why i am getting this? Here is my code below so you can determine what the problem may be.
Thank you in advance.
import java.nio.file.*;
import java.util.*;
import java.io;
public class BankInterest {
public static void main(String[] args) throws IOException {
/* TASK 1: Declare variables */
String accountType;
double principal;
double rate;
double balance;
int year;
/* Check if the expected command line is provided */
if (args.length < 1) {
/* Display the Usage */
System.out.println("Usage: java BankInterest interestRateFileName");
/* Programs quits with an error code */
System.exit(-1);
}
/* TASK 2: Read interest rates from a file */
try {
Scanner x = new Scanner(Paths.get("commbank.txt"));
System.out.println(x.nextDouble());
} catch (IOException e) {
/* TASK 3: Take user input - Which Account */
Scanner keyboard = new Scanner(System.in);
System.out.println("Which Account: ");
System.out.println("1 - Savings");
System.out.println("2 - Term Deposits");
String line = keyboard.nextLine();
if (line.equals("1")) {
accountType = "Savings";
} else if (line.equals("2")) {
accountType = "Term Deposits";
}
/* TASK 4: Take user input - Principal and Period */
Scanner input = new Scanner(System.in);
System.out.println("Principal: ");
principal = keyboard.nextDouble();
System.out.println("Years: ");
year = keyboard.nextInt();
/* TASK 5: Calculate balance for the chosen account type */
if (accountType == "Savings") {
balance = principal * Math.pow((1 + rate / 100), year);
} else if (accountType == "Term Deposits") {
balance = (principal * rate * time) / 100;
}
/* TASK 6: Display results */
if (accountType == "Savings") {
System.out.println("");
System.out.println("The Compound Interest is: " + balance);enter code here
} else if (accountType == "Term Deposits") {
System.out.println("");
System.out.println("The Simple Interest is: " + balance);
} else {
System.out.println("");
System.out.println("Error! Account is not recognized.");
}
}
You're missing two more closing braces at the end of the file.
One to close your main
And the other to close off your class.
Also, you should use equals() when comparing accountType as Satya mentioned in the comment.
I'm writing a driver class for a piggy bank class that I created. The idea is that it is supposed to add different types of coins (user input) and then total the cents and display them until "X" is input by the user. I think I have the code right, but there is a weird issue where if I use the "countMoney" accessor into the code, it tells me that all of my variables in the driver class are uninitialized. If I remove it, there are no errors shown by Eclipse. I've printed my source and driver class below:
package piggy;
/**
* #author Kevin
*
*/
import java.util.Scanner;
import piggy.PiggyBank;
public class PiggyBankTester {
/**
* #param args
*/
public static void main(String[] args) {
String num = "str", num1;
int count = 0;
int money;
Scanner scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
PiggyBank total = new PiggyBank();
System.out.println("Welcome to the Piggy Bank Tester");
System.out.println("What type of coin to add (Q, H, D or X to exit)?");
num1 = scan.nextLine();
num = num1.toUpperCase();
{
if (num.equals("X"))
System.out.println("Goodbye.");
else if (num != "X")
{
System.out.println("How many do you wish to add?");
count = scan.nextInt();
if (num.equals("Q"))
total.addQuarters(count);
else if (num.equals("H"))
total.addHalfDollars(count);
else if (num.equals("D"))
total.addDollars(count);
else if (num.equals("X"))
System.out.println("Goodbye.");
}
}
{
total.calculate();
money = total.countMoney();
System.out.println("The piggy bank now contains " + money + " cents.");
}
}
}
You don't need (String Q,D,H,X) .
Also you have declared this variables without give them any value just name.
A way you can do it is to change your if-else statements and set , for example if you want num to be equal to Q ---> if (num.equals("Q") ) <---
I'm trying to add entries to an ArrayList in Java and I had it working, but now it isn't. Here is the code
import java.util.*;
public class SalesPerson
{
// define an array of allowable sales person to be three
static String[] salesPerson = new String[3];
/**
* Calculates the total annual compensation for a salesperson by
* multiplying annual sales by commission rate and then adding the salary
*/
public static void compensation()
{
try {
String[] salesperson = new String[3];
// use scanner class to read input from the user
Scanner input = new Scanner(System.in);
// List to add entries to an array list
ArrayList<String> list = new ArrayList<>();
// do..while loop to add salespersons
do {
System.out.println("Want to compare additional " //GLD-changed verbiage here
+ "salespeople? (y/n)"); //GLD-changed verbiage here
if (input.next().startsWith("y")) {
System.out.println("Enter the salesperson's name:");
addSalesPerson(list).add(input.next());
System.out.println("Enter annual amount for salesperson");
addSalesPerson(list).add(input.next());
} else {
break;
}
}
while (true);
// System.out.println(addSalesPerson(list).get(1));
// check to see if only two sales persons have been entered
if (addSalesPerson(list).size() < 2 || addSalesPerson(list).size() > 4) {
throw new Exception("You may only enter two sales persons.");
}
Object[] arr;
arr = addSalesPerson(list).toArray(new String[addSalesPerson(list).size()]);
// loop through the length of the array
for (Object arr1 : arr) {
salesperson = (String[]) arr;
}
// for this, we will compare two sales people only
float sale2 = Float.parseFloat(salesperson[1]);
float sale4 = Float.parseFloat(salesperson[3]);
// subtract based on which variable is greater to ensure no negative values
float difference = sale2 > sale4 ? sale2 - sale4 : sale4 - sale2;
// print out the difference
System.out.printf("To match the other sales person's amount "
+ "you will need to get $%.2f more\n\n", difference);
} catch (Exception e) {
// handle any exception by displaying an error message
System.out.println("Something went wrong while processing your "
+ "input. Please be sure you only entered numeric values"
+ " and or the correct amount of salespersons.");
}
}
/**
* Adds sales people to an array list
* #param salesperson
* #return ArrayList
*/
static public ArrayList addSalesPerson(ArrayList<String> salesperson)
{
for (int i=0; i<salesPerson.length; i++) {
if (salesperson.get(i).equals("")) {
break;
}
salesperson.add(salesperson.get(i));
}
return salesperson;
}
}
And then I am calling these static methods in two other files
public class Getters
{
public static void handleSalesPersonCompensation()
{
SalesPerson.compensation();
}
}
public class ComparisonWk5
{
public static void main(String args[])
{
Getters.handleSalesPersonCompensation();
}
}
The output of these should be
Want to compare additional salespeople? (y/n)
y
Enter the saleperson's name: My Name
Enter the annual amount for salesperson: 200000
Want to compare an additional salespeople? (y/n)
y
Enter the saleperson's name: My Name 2
Enter the annual amount for salesperson: 100000
To match the other person's amount, you will need to get $100000 more
But the output is:
Want to compare additional salespeople? (y/n)
y
Enter the salesperson's name:
Something went wrong while processing your input. Please be sure you only entered numeric values and or the correct amount of salespersons.
Everytime after I type "y", it shows the salesperson's name input but also displays the exception right after without having the ability to enter a name.
Any help would be appreciated
The stack trace is this:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at SalesPerson.addSalesPerson(SalesPerson.java:96)
at SalesPerson.compensation(SalesPerson.java:48)
at Getters.handleSalesPersonCompensation(Getters.java:61)
at ComparisonWk5.main(ComparisonWk5.java:31)
Thanks
• Creating a payroll file
• A payroll file contains hourly pay information of 20 employees in two department, human resources and police department. The file will have two columns of floating-point numbers. The first column is for human resources and the second column for police department. So each row has two floating-point numbers.
• You will need to create a payroll file by using random numbers in [0, 100) as double types.
• Reading the payroll file.
• You need to use nextLine() of a Scanner object to read each line from the payroll file.
• Parse each line to get an array of two hourly pays by using splitString() function that we discussed in the class. The function will return String [] type. The functions of String and Character class will be a help to solve splitString.
• Compute total pay and average pay for each department
• You will need to use Double.parseDouble() to convert pay of String type to a double type
• Write an output file with total pays and average pays.
• Use “pay.txt” for the input file name and “summary.txt” for the output file name.
Now I understand how to do this without the arrays, as I have finished that. But once I am supposed to parse the txt file into multiple arrays I am completely lost. My professor is prohibiting us from using in.hasNextDouble(), which is how I solved the last program. How do I separate the two numbers on the same line in the txt files in the program into two different arrays without it?
Here is the code from the last program, and where I am currently with the current one.
public class FileHandling {
public static void main(String [] args) throws FileNotFoundException{
File inputFileName = new File("input.txt");
Scanner in = new Scanner(inputFileName);
double averageWorker = 0;
double averageHr = 0;
double totalWorkerPay = 0;
System.out.println(" HR\t\tWorkers");
double totalHrPay = 0;
while (in.hasNextDouble()) {
double humanResourcesPay = in.nextDouble();
System.out.printf("%8.3f\t", humanResourcesPay);
totalHrPay += humanResourcesPay;
double workerPay = in.nextDouble();
System.out.printf("%.3f\n", workerPay);
totalWorkerPay += workerPay;
averageWorker = totalWorkerPay/3;
averageHr = totalHrPay/3;
}
System.out.printf("Total pay for HR is %.1f", totalHrPay);
System.out.printf("\nAverage pay for HR is %.1f", averageHr);
System.out.printf("\nThe total pay for Workers is %.1f", totalWorkerPay);
System.out.printf("\nAverage pay for Workers is %.1f", averageWorker);
System.out.print("\nEnter the file name:");
Scanner console = new Scanner(System.in);
String outputFileName = console.nextLine();
PrintWriter out = new PrintWriter(outputFileName);
System.out.println("total is " + totalHrPay);
in.close();
out.close();
}
}
Okay and here is what I have so far on this homework.
public class FileHandlingNextLine {
public static void main(String [] args) throws FileNotFoundException{
File inputFileName = new File("pay.txt");
Scanner in = new Scanner(inputFileName);
int i = 0;
int j = 0;
double total[] = new double[2];
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println("Line : " + line);
String pays[] = splitString(line);
for(i = 0; i < pays.length; i++) {
System.out.printf(pays[i]);
total[i] += Double.parseDouble(pays[i]);
}
}
}
Any help would be appreciated, I am lost and my teacher is of little help.