I am doing this Java assignment for class, and for some reason this method keeps saying the symbol can not be found. The block of code below is what gave me the error. Not entirely sure as to why because I followed the book verbatim and there was no mention of it compiling with an error (usually there is an indication to look for that)
I added the rest of the assignment to the post. I wasnt sure if it was relative or not because I was getting the error before I wrote the second half of this that is being posted now. I'm not sure if the error has to do with calling the methods before the method is actually defined, but i tried switching the order and it did not make a difference when I compiled it.
import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.text.*;
public class CreateFilesBasedOnState
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Path inStateFile = Paths.get("InStateCusts.txt");
Path outOfStateFile = Paths.get("OutofStateCusts.txt");
final String ID_FORMAT = "000";
final String NAME_FORMAT = " ";
final int NAME_LENGTH = NAME_FORMAT.length();
final String HOME_STATE = "WI";
final String BALANCE_FORMAT = "0000.00";
String delimiter = ",";
String s = ID_FORMAT + delimiter + NAME_FORMAT + delimiter
+ HOME_STATE + delimiter + BALANCE_FORMAT
+ System.getProperty("line.seperator");
final int RECSIZE = s.length();
FileChannel fcIn = null;
FileChannel fcOut = null;
String idString;
int id;
String name;
String state;
double balance;
final String QUIT = "999";
createEmptyFile(inStateFile, s);
createEmptyFile(outOfStateFile, s);
try
{
fcIn = (FileChannel) Files.newByteChannel(inStateFile,
CREATE,
WRITE);
fcOut = (FileChannel) Files.newByteChannel(outOfStateFile,
CREATE,
WRITE);
System.out.print("Enter customer account number >> ");
idString = input.nextLine();
while (!(idString.equals(QUIT)))
{
id = Integer.parseInt(idString);
System.out.print("Enter name for customer >> ");
name = input.nextLine();
StringBuilder sb = new StringBuilder(name);
name = sb.toString();
System.out.print("Enter state >> ");
state = input.nextLine();
System.out.print("Enter balance >> ");
balance = input.nextDouble();
input.nextLine();
DecimalFormat df = new DecimalFormat(BALANCE_FORMAT);
s = idString + delimiter + name + delimiter + state
+ delimiter + df.format(balance)
+ System.getProperty("line.separator");
byte[] data = s.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(data);
if (state.equals(HOME_STATE))
{
fcIn.position(id * RECSIZE);
fcIn.write(buffer);
}
else
{
fcOut.position(id * RECSIZE);
fcOut.write(buffer);
}
System.out.print( "Ener next cusomter account number or "
+ QUIT + " to quit >> ");
idString = input.nextLine();
}
fcIn.close();
fcOut.close();
}
catch (Exception e)
{
System.out.println("Error message: " + e);
}
}
public static void createEmtpyFile(Path file, String s)
{
final int NUMRECS = 1000;
try
{
OutputStream outputStr
= new BufferedOutputStream(Files.newOutputStream(file
, CREATE));
BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(outputStr));
for (int count = 0; count < NUMRECS; ++count) {
writer.write(s, 0, s.length());
}
writer.close();
}
catch (Exception e)
{
System.out.println("Error message: " + e);
}
}
}
Related
This is a project for school, and I am having difficulty figuring out why it is this way. We are to create a program that will put data into a text file, but whenever I run my code, it will output to the file, but it will be at line 224, and not start at the beginning. Does anyone know why this may be? Here is my code
import java.nio.file.*;
import java.io.*;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.nio.channels.FileChannel;
public class CreateCustomerFile
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Path file = Paths.get("C:\\Users\\brady\\IdeaProjects\\TestNew\\Customers.txt");
String s = "000, ,00000" + System.getProperty("line.separator");
String[] array;
byte[] data = s.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(data);
FileChannel fc = null;
final int recordSize = s.length(); //Size of record
final int recordNums = 1000; //Number of records stored in file
final String QUIT = "exit";
String custString;
int custNum;
String lastName;
String zipCode;
String fileNum;
try
{
OutputStream output = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
for(int count = 0; count < recordNums; ++count)
writer.write(s, 0, s.length());
writer.close();
}
catch(Exception e)
{
System.out.println("Error message: " + e);
}
try
{
fc = (FileChannel)Files.newByteChannel(file, READ, WRITE);
System.out.print("Enter customer number or 'exit' to quit >> ");
custString = input.nextLine();
while(!(custString.equalsIgnoreCase(QUIT)))
{
custNum = Integer.parseInt(custString);
buffer = ByteBuffer.wrap(data);
fc.position((long) custNum * recordSize);
fc.read(buffer);
s = new String(data);
array = s.split(",");
fileNum = array[0];
if(!(fileNum.equals("000")))
System.out.println("Sorry - customer " + custString + " already exists");
else
{
System.out.print("Enter the last name for customer #" + custNum + ": ");
lastName = input.nextLine();
StringBuilder sb = new StringBuilder(lastName);
sb.append(" ");
sb.setLength(6);
lastName = sb.toString();
System.out.print("Enter zip code: ");
zipCode = input.nextLine();
s = custString + "," + lastName + "," + zipCode + System.getProperty("line.separator");
data = s.getBytes();
buffer = ByteBuffer.wrap(data);
fc.position((long) custNum * recordSize);
fc.write(buffer);
}
System.out.print("Enter next customer number or 'exit' to quit: ");
custString = input.nextLine();
}
fc.close();
}
catch (Exception e)
{
System.out.println("Error message: " + e);
}
}
}
Your code needs more input validation, any user provided string input must be sized for the output field, no matter the input.
lastName is done correctly, but customer number and zip code are left to chance, and can throw off the record count in the file.
A customer id entered as "1" is 2 characters shorter than "001" thus upsetting the fixed length record for the remaining file.
I've written an extremely basic program with 3 options. While executing the "Quit" section of the code I get a InputMismatchError. I know that this is because the program is expecting an integer when me/User is giving it a String.
I was just wondering how I would go about setting something like this up.
I've also tried a string to char method but that's also gave me the same error.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
static Scanner S = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
int DisJ, ISJ, User;
ISJ = 1;
DisJ = 2;
String input = "";
// change print outs to appropriate names::::
System.out.println("--Main Menu--");
System.out.println("Display Journeys:" + ISJ);
System.out.println("Suitable Journeys:" + DisJ);
System.out.println("Quit: " );
//User = S.next().charAt(0);
User = S.nextInt();
if (User == 1)
{
System.out.println("You have selected Display Journeys");
try
(BufferedReader ReadFile = new BufferedReader(new FileReader("E:\\input.txt")))
{
String line = null;
while ((line = ReadFile.readLine()) != null)
{
System.out.println(line);
}
}
}
else if (User ==2)
{
System.out.println("You have selected Suitable Journeys");
}
System.out.println("Specify Destination: ");
String destination = S.next();
System.out.println("Specify Max Time (HH:MM): ");
String specificTime = S.next();
// This assigns the first two integers to the string hours
String hours = specificTime.substring(0,2);
//This assigns the last two integers to the string minutes
String minutes = specificTime.substring(3,5);
//integer.parseInt converts the string into an integer
int hours1 = Integer.parseInt(hours);
//integer.parseInt converts the string into an integer
int minutes1 = Integer.parseInt(minutes);
int Time;
// Equation to convert the hh:mm into minutes
Time = (60 * hours1) + minutes1;
System.out.println("Specify number of changes");
int Changes = S.nextInt();
System.out.println( "Destination selected: " + input + "Minutes specified: " + Time + "," + "Number of changes: " + Changes);
int quit;
String Quit = S.next();
if (Quit.equals("Quit")) {
System.out.println("Goodbye!");
System.exit(0);
}
try {
quit = Integer.parseInt(Quit);
}
catch (Exception e)
{
System.out.println("Type Quit to leave");
}
}
}
Is your question that you are not able to make the argument in the if statement true?
Try setting it as a boolean instead of an int / string, and throughout your code just have it changing quit to true/false instead of a number/string.
EDIT: Oh i see. So you just want to make it so that the user can press a key and it will quit, like a "Please enter Y to exit the program"
Do you have a scanner set up?
Wrap yor coe with a try and catch errors to handle them
int quit;
try {
quit = Integer.parseInt(Quit);
} catch (Exception e) {
// handle error...
}
http://beginnersbook.com/2013/04/try-catch-in-java/
To simply check what the user entered just accept a string and check its value like so:
Scanner scanner = new Scanner(System.in);
System.out.print("Quit?");
String text = scanner.nextLine();
if (text.equals("Quit") or text.equals("q")) {
//...
}
I am creating a reverse polish notation calculator in java that accepts file input. One of the requirements is that certain statistics are generated from the calculations too.
below are two snippets of my code.
public static int invalidlines = 0;
public static int validlines = 0;
public static int stats1 = 0;
private static Scanner input;
public static ArrayList<String> validList = new ArrayList<String>();
public static ArrayList<Integer> stats = new ArrayList<Integer>(); {
if (stats.isEmpty());
display("n/a");
}
static int sum(ArrayList<Integer> stats)
{
int value = 0;
for(int i : stats)
{
value += i;
}
return value;
}
Thats the code for my array lists.
static void fileInput() throws IOException
{
input = new Scanner(System.in);
try
{
String currentLine = new String();
int answer = 0;
//Open the file
display("Enter File Name: ");
FileInputStream fstream = new FileInputStream(input.nextLine()); // make a input stream
BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); // pass input stream to a buffered reader for manipulation
String strLine; // create string vars
//loop to read the file line by line
while ((strLine = br.readLine()) != null) { // Whilst the buffered readers read line method is not null, read and validate it.
currentLine = strLine;
if(strLine.trim().isEmpty())
{
display("You have entered a blank line, the program will now exit");
System.exit(0);
}
if(isValidLine(currentLine))
{
validList.add(currentLine);
validlines++;
String[] filearray = new String[3];
filearray = currentLine.split(" ");
int val1 = Integer.parseInt(filearray[0]);
int val2 = Integer.parseInt(filearray[1]);
display("Your expression is: " + filearray[0] + " " + filearray[1] + " " + filearray[2]);
switch(filearray[2]) {
case("+"):
answer = val1 + val2;
stats.add(answer);
break;
case("-"):
answer = val1 - val2;
stats.add(answer);
break;
case("/"):
answer = val1 / val2;
stats.add(answer);
break;
case("*"):
answer = val1 * val2;
stats.add(answer);
break;
}
display("Your calculation is " + filearray[0] + " " + filearray[2] + " " + filearray[1] + " = " + answer);
}
}
}
catch (FileNotFoundException e)
{
display("Please Enter a valid file name");
}
display("Evaluations Complete");
display("=====================");
display("Highest Result: " + Collections.max(stats));
display("Lowest Result: " + Collections.min(stats));
display("Aggregate Result: " + sum(stats));
display("Average Result: " + sum(stats) / validlines);
display("Total Valid Lines: " + validlines);
display("Total Invalid Lines: " + invalidlines);
}
I require it so that if there are no valid calculations from the text file that the highest, lowest and average result displays show as 'n/a' instead they bring the java error in my console shown below.
Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(Unknown Source)
at java.util.Collections.max(Unknown Source)
at Assignment.fileInput(Assignment.java:156)
at Assignment.main(Assignment.java:177)
Replace
Collections.max(stats)
with
(!stats.isEmpty() ? Collections.max(stats) : "n/a")
(similarly for Collections.min)
You are also going to want to handle the case of validlines == 0 to avoid the division by zero error in / validlines.
What I want to do is make it so that when the program runs it will run the ordinary way but if the user selects that they want the display to be in html then it will run what the ordinary program would do but rather than display it in the console it will write what was going to appear in the console into a html file that the user specifies. Is this possible? I have code to accept the user input and have them specify what format they want it in as well as open the browser but I'm not sure if this could work. The code I have already is below:
import java.awt.Desktop;
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
// Used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
// Checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
// Also checks to make sure that there are no results that are just whitespace
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
}
catch (Exception e) {
return false;
}
}
// Checks to make sure that the data is an integer
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
while (true) { // Runs until it is specified to break
Scanner scanner = new Scanner(System.in);
System.out.println("Enter filename");
String UserFile = sc.nextLine();
File file = new File(UserFile);
if (!file.exists()) {
continue;
}
if (UserFile != null && !UserFile.isEmpty()){
System.out.println("Do you want to generate plain (T)ext or (H)TML");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("H")) {
Desktop.getDesktop().browse(file.toURI());
} else if (input.equalsIgnoreCase("T")) {
processFile(UserFile);
} else {
System.out.println("Do you want to generate plain (T)ext or (H)TML");
}
}
}
}
// Checks how the user wants the file to be displayed
private static void processFile(String UserFile) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(UserFile))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
// Splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + "|" + " " + ateam + " " + "[" + ascore + "]");
// Output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
// Displays the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}
//This is where we'll write the HTML to if the user's chooses so
private static final String OUTPUT_FILENAME = "output.html";
public static void main(String[] args) throws IOException
{
final Scanner scanner = new Scanner(System.in);
final String content = "Foobar";
final boolean toHtml;
String input;
//Get the user's input
do
{
System.out.print("Do you want messages "
+ "written to (P)lain text, or (H)TML? ");
input = scanner.nextLine();
} while (!(input.equalsIgnoreCase("p")
|| input.equalsIgnoreCase("h")));
toHtml = input.equalsIgnoreCase("h");
if (toHtml)
{
//Redirect the standard output stream to the HTML file
final FileOutputStream fileOut //False indicates we're not appending
= new FileOutputStream(OUTPUT_FILENAME, false);
final PrintStream outStream = new PrintStream(fileOut);
System.setOut(outStream);
}
System.out.println(toHtml
? String.format("<p>%s</p>", content) //Write HTML to file
: content); //We're not writing to an HTML file: plain text
}
I am receiving a message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
when trying to run the below code. This program is taking the input from a text file, conducting some salary numbers, and outputting their gross pay.
This is the contents of the text file:
http://m.uploadedit.com/b034/139892732049.txt
package payroll;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class PayRoll
{
private String empName;
private int hours;
private int hourlyPayRate;
public PayRoll(String name, int hh, int rr)
{
empName = name;
hours = hh;
hourlyPayRate = rr;
}
public String getName()
{
return empName;
}
public double getPay()
{
if(hours <= 40)
return hours * hourlyPayRate;
else
return (40 * hourlyPayRate) + (hours - 40) * 1.5 * hourlyPayRate;
}
public static void main(String[] args)
{
Scanner inFile = null;
try
{
inFile = new Scanner(new File("payroll.txt"));
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
String name;
String first;
String last;
int hh;
int rr;
String result = "Details of employees:\n";
while(inFile.hasNextLine())
{
String line = inFile.nextLine();
String tokens[] = line.split(" ");
first = tokens[0];
last = tokens[1];
hh = Integer.parseInt(tokens[2]);
rr = Integer.parseInt(tokens[3]);
name = first + " " + last;
PayRoll payroll = new PayRoll(name, hh, rr);
result += "Name: " + payroll.getName() + ", GrossPay: $" + payroll.getPay() + "\n";
}
JOptionPane.showMessageDialog(null, result);
inFile.close();
}
}
The problem is that you have blank lines in your file which results in a zero length token array
Verify the length of your token array after each read.
if (token == null || token.length != 4) continue;
or of course as Duncan suggests simply skip empty lines or both (better option).
if (line == null || line.trim().length() < 1) continue;
Both of these checks should be done, and maybe reported on separately.
You are not checking how many tokens you have after doing String tokens[] = line.split(" ");
If the split results in less that 2 tokens, you will get the ArrayIndexOutOfBoundsException
You should probably add a check like:
if(tokens.length < 2) {
continue;
}
As far as I can see your data file contains empty lines. I believe that the first empty line causes this problem because split() returns empty (zero length) array.
The last line in the payroll.txt file is an empty line, so when it is split, it will will generate an array having size one. Then this (last = tokens[1];) line of code will obviously make an error.
Rewrite your code as follows, I have added to trim the line before splitting, and added a continue in the while loop.
package payroll;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class PayRoll {
private String empName;
private int hours;
private int hourlyPayRate;
public PayRoll(String name, int hh, int rr) {
empName = name;
hours = hh;
hourlyPayRate = rr;
}
public String getName() {
return empName;
}
public double getPay() {
if (hours <= 40)
return hours * hourlyPayRate;
else
return (40 * hourlyPayRate) + (hours - 40) * 1.5 * hourlyPayRate;
}
public static void main(String[] args) {
Scanner inFile = null;
try {
inFile = new Scanner(new File(
"C:\\Users\\Visruth\\Desktop\\payroll.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String name = null;
String first = null;
String last = null;
int hh;
int rr;
String result = "Details of employees:\n";
while (inFile.hasNextLine()) {
String line = inFile.nextLine().trim();
System.out.println(line);
String[] tokens = line.split(" ");
if (tokens.length != 4) {
continue;
}
first = tokens[0];
last = tokens[1];
hh = Integer.parseInt(tokens[2]);
rr = Integer.parseInt(tokens[3]);
name = first + " " + last;
PayRoll payroll = new PayRoll(name, hh, rr);
result += "Name: " + payroll.getName() + ", GrossPay: $"
+ payroll.getPay() + "\n";
}
JOptionPane.showMessageDialog(null, result);
inFile.close();
}
}