When I run program it never stops, and don't know how to make (for each line) different v number (gives me syntax error) thanks for helping.
file format each line has string int string string
public static void main(String[] args) throws FileNotFoundException, IOException {
String filelocation = "location";
filelocation = JOptionPane.showInputDialog("Enter file address");
BufferedReader inFile = new BufferedReader(new FileReader(filelocation)); //using BufferedReader to get readLine function
ArrayList<Vehicle> VehicleList = new ArrayList<Vehicle>();
int counter = 1;
String dataRow = null;
dataRow= inFile.readLine();
while ( dataRow != null){
try{
String[] temp = dataRow.trim().split("\\s+");
Vehicle v(counter) = new Vehicle (temp[0], Integer.parseInt(temp[1]), temp[2], temp[3], temp[4]);
VehicleList.add(v1);
dataRow= inFile.readLine();
}
catch(Exception e){}
}
inFile.close();
System.out.println(VehicleList);
System.out.println(v1);
}
As has been been said, you are most likely getting an exception within your while loop.
But the main problem with that is dataRow = inFile.readLine() being in the while loop.
while ( dataRow != null){
try{
String[] temp = dataRow.trim().split("\\s+");
Vehicle v(counter) = new Vehicle (temp[0], Integer.parseInt(temp[1]), temp[2], temp[3], temp[4]);
VehicleList.add(v1);
dataRow= inFile.readLine(); // <---shouldn't be in while loop
}
catch(Exception e){}
}
inFile.close();
System.out.println(VehicleList);
System.out.println(v1);
}
So what happens is, an exception is thrown, and then jumps to the catch block without ever changing the value of dataRow!
So everytime the while loop is executed, it is actually comparing dataRow to the first value you set it as.
You can get around this by changing the code as in the example below:
while((dataRow = inFile.readLine()) != null){
try {
//some stuff
}
catch(Exception e){
//some other stuff
}
}
Make sure to remove the line you have before the while loop that is dataRow = inFile.readLine()
So with this, it will behave more or less how you wanted it to. If you wanted to ignore the thrown exceptions, this will continue to process the file until the end. The line where the exception was thrown will be skipped.
You can't assign Dynamic variable names. Java is a strongly type language.
What you can do, is save it on a list, and use the index for getting and setting it.
Your code should be as follow:
String[] temp = dataRow.trim().split("\\s+");
Vehicle v = new Vehicle (temp[0], Integer.parseInt(temp[1]), temp[2], temp[3], temp[4]);
VehicleList.add(v);
System.out.println(v);
dataRow= inFile.readLine();
For getting use
VehicleList.get(index)
For setting use
VehicleList.set(index, VEHICLE)
The most likely cause to the loop not terminating is an exception within the read loop (you consume the exception and try to continue). Based on your example, I think that you have a mismatch on input from split versus the Vehicle constructor. Also as you found out, you cannot have dynamic variable names such that Vehicle v(counter) = new Vehicle(... gives a syntax exception.
See if this version helps show you where the problem is.
public static void main(String[] args) throws FileNotFoundException, IOException {
String filelocation = "location";
filelocation = JOptionPane.showInputDialog("Enter file address");
BufferedReader inFile = new BufferedReader(new FileReader(filelocation)); //using BufferedReader to get readLine function
ArrayList<Vehicle> VehicleList = new ArrayList<Vehicle>();
int counter = 0;
String dataRow = null;
dataRow= inFile.readLine();
try{
while ( dataRow != null){
String[] temp = dataRow.trim().split("\\s+");
if (temp.length != 5)
throw new Exception("split returned "+temp.length);
Vehicle v = new Vehicle (temp[0], Integer.parseInt(temp[1]), temp[2], temp[3], temp[4]);
VehicleList.add(v);
System.out.println(v);
dataRow= inFile.readLine();
}
}
catch(Exception e){
e.printStackTrace();
}
finally {
inFile.close();
}
System.out.println(VehicleList);
}
Related
I'm trying to figure out how to make a function in JAVA that searches through a document line per line:
First I initialize the file and a reader, then convert each line to a string in an ArrayList; after that I try to check the ArrayList against a String to then return the position of the ArrayList as a string.
So for example I have a text containing:
1 - Somewhere over the rainbow
2 - Way up high.
Converted to ArrayList, if then searched for: "Somewhere"; then it should return the sentence "Somewhere over the rainbow";
Here is the code I tried; but it keeps returning 'null';
String FReadUtilString(String line) {
File file = new File(filepath);
ArrayList<String> lineReader = new ArrayList<String>();
System.out.println();
try {
Scanner sc = new Scanner(file);
String outputReader;
while (sc.hasNextLine()) {
lineReader.add(sc.nextLine());
}
sc.close();
for(int count = 0; count < lineReader.size(); count++) {
if(lineReader.get(count).contains(line)){outputReader = lineReader.get(count);}
}
} catch (Exception linereadeline) {
System.out.println(linereadeline);
}
return outputReader;
}
I refactor your code a bit, but I keep your logic, it should work for you:
String FReadUtilString(String line, String fileName){
File file = new File(fileName);
List<String> lineReader = new ArrayList<>();
String outputReader = "";
try (Scanner sc = new Scanner(file))
{
while (sc.hasNextLine()) {
lineReader.add(sc.nextLine());
}
for (int count = 0; count < lineReader.size(); count++){
if (lineReader.get(count).contains(line)){
outputReader = lineReader.get(count);
}
}
}
catch (Exception linereadeline) {
System.out.println(linereadeline);
}
return outputReader;
}
NOTE: I used the try-with-resource statement to ensure the closing of the Scanner.
A more succinct version:
String fReadUtilString(String line, String fileName) {
try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
return lines.filter(l -> l.contains(line)).findFirst();
}
catch (Exception linereadeline) {
System.out.println(linereadeline); // or just let the exception propagate
}
}
Just at it says in the title, I can save something inside the rtf file sometimes(my save function is a working progress). Im using a mac, and i cant save as a txt. I do not know if this is normal or not and I having troubles with it since I dont know why but I get an arrayoutofbounds error when I try to use the line Player p = new Player(splitLine[0], splitLine[1], splitLine[2]);
Here is my read and write code.
final String FILE_PATH = "/Users/macbookair/Desktop/comp sci ia/TypingPractice/Player records.rtf";
BufferedReader reader;
PrintWriter writer;
Player[] readRecords() {
// This is called by AppLogic.load() which runs when the AppLogic is
// instantiated.
// The array of Person objects that we create from the load file
// This holds the current line from the load file
String nextLine;
// This is a two-element array that holds name/surname once it has
// been split at the # sign
String[] splitLine = new String[4];
for(int i=0; i< splitLine.length;i++){
splitLine[i] = "0";
}
// This is just a counter of how many lines I've read in
int count = 0;
try {
reader = new BufferedReader(new FileReader(FILE_PATH));
// Get the first line
nextLine = reader.readLine();
// Loop until we've been through every line in the file
while (nextLine != null) {
// Split the current line at the # sign
splitLine = nextLine.split("#");
Player p = new Player(splitLine[0], splitLine[1], splitLine[2]);
// Put it in the array
playerArray[count] = p;
// Increment the counter
count = count + 1;
// Get the next line
nextLine = reader.readLine();
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
void writeRecords(Player[] p) {
try {
writer = new PrintWriter(new FileWriter(FILE_PATHPhrase));
// Loop through each Person in the Person array
for (int i = 0; i < p.length; i++) {
// Write the name, then a # sign, then the surname
writer.println(p[i].getWPM() + "#" + p[i].getMistakes() + "#" + p[i].getTime());
}
} catch (Exception e) {
e.printStackTrace();
}
writer.close();
}
I am trying to read from a text file, but whenever the program gets to my while loop it just skips over it. I used a previous example I had to check to see if I did it correctly, but it doesn't seem to be working this time.
EDIT: to clarify, the while with "b++" under it is being skipped.
EDIT 2: Updated code.
public static void main(String[] args) throws FileNotFoundException {
ToDoItem td = new ToDoItem();
ToDoList tl = new ToDoList();
File file = new File("ToDoItems.txt");
Scanner ReadFile = new Scanner(file);
Scanner keyboard = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
String inputline;
System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");
try (PrintWriter fout = new PrintWriter(new File("ToDoItems.txt"))) {
do {
System.out.println("add to the list? [y/n]");
inputline = keyboard.nextLine();
if ("y".equals(inputline)) {
fout.print(td.getDescription() + "\n");
} else {
System.out.println("Here is the list so far:");
while (ReadFile.hasNext()) {
String listString = ReadFile.nextLine();
list.add(listString);
}
}
} while ("y".equals(inputline));
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
System.out.println(list);
}
Ideally I want it to print a part of the Array each time it passes through the while loop. But it just ends up skipping over it.
I checked the text file itself, and it does have the information I want to print to it. Yet for some reason the scanner won't read it properly.
I guess your problem is that you are trying to read a file that you are currently using, try close the fout object before read it, something like this:
public static void main(String[] args){
File file = new File("ToDoItems.txt");
ToDoItem td = new ToDoItem();
ToDoList tl = new ToDoList();
Scanner keyboard = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
String inputline;
System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");
try (PrintWriter fout = new PrintWriter(file)) {
// ^^ here
do {
System.out.println("add to the list? [y/n]");
inputline = keyboard.nextLine();
if ("y".equals(inputline)) {
fout.print(td.getDescription() + System.lineSeparator());
} else {
// Important line is here!
fout.close(); // <--- Close printwriter before read file
System.out.println("Here is the list so far:");
Scanner ReadFile = new Scanner(file);
while (ReadFile.hasNext()) {
String listString = ReadFile.nextLine();
list.add(listString);
}
}
} while ("y".equals(inputline));
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
System.out.println(list);
}
String[] stringArray = new String[b]; is problematic as your int b = 0;.
Also, it seems like you do not know how large your array will even be. I would suggest you use an ArrayList instead. That way you will not need a counter, just add to the ArrayList.
It would be better to try and catch your FileNotFoundException instead of throwing at the main but I guess you know that your file will always be there.
I have been working on this code for the day and am almost at the finish line. What I want is that the code should work as a clip card, remembering the number of purchased coffees, and awarding the customer a free coffee every 10th purchase. I'm writing to a file and reading from it in order for a customer to be able to continue his clip card where he left of last time. So to my problem...I have properly been able to write my "count" variable to a file, and it is storing it correctly. However, every time I run the program again it starts off a 0 and I don't see why. I need it to save the current count, and read the count once run again. For example, if a customer has previously purchased 7 coffees and is returning to the store, his counter needs to start at 7. For some reason it is not doing that.
Here's what I have so far:
public class FelixNeww {
public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";
FelixNeww f = new FelixNeww();
System.out.println(f.readFromFile());
while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
entry = key.nextLine();
if(entry.compareTo(password) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
f.saveToFile(count);
}
if(count == 10 && count != 0){
System.out.println("YOU'VE GOT A FREE COFFE!");
count = 0;
}
if(entry.compareTo(password) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
public void saveToFile(int count)
{
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("C:\\Temp\\countStorage.txt"))));
bw.write(Integer.toString(count));
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(bw != null)
{
try
{
bw.close();
}
catch(IOException e) {}
}
}
}
public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(br != null)
{
try
{
br.close();
}
catch(IOException e) {}
}
}
return 0;
}
}
You are currently setting your count variable to 0. You should set it to the value that's in the file. Do this just before the while loop:
count = f.readFromFile();
while(true) {
You should also implement a way to gracefully exit the while loop. For example, if the user enters "q", you can execute the break; statement to exit the while loop. And after your while loop, call key.close(); to close the Scanner object.
The scope of count variable is local in both instances
public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";
System.out.println(f.readFromFile());
public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
In the readFromFile function, you read it from the file, return it, but don't keep track of it in a variable, why don't you replace the println with this inside your main:
count=f.readFromFile
Consider this code:
private static void colourRead(String s) throws IOException {
FileReader readhandle = new FileReader("C:\\****\\****");
BufferedReader br = new BufferedReader(readhandle);
String line = null;
while ((line = br.readLine()) != null) {
ColourInput(); //there's an error here
}
br.close();
readhandle.close();
}
private static void ColourInput(String s) {
char letter;
String fullWord;
Scanner kb = new Scanner(System.in);
System.out.print("Enter whatever: ");
fullWord = kb.nextLine();
System.out.println(fullWord);
for (int i = 0; i < fullWord.length(); i++) {
letter = fullWord.charAt(i);
switch (Character.toUpperCase(letter)) {
case 'A': {
Blue();
}
break;
}
}
}
Is it possible for me to carry the
line
variable from the colourRead method, and somehow assign it to the
fullWord
variable in the ColourInput() method?
I'm trying to read a text file, and output certain colours associated to each letter. I don't want to create a new switch statement in the colourRead method because apparently, this is a bad programming practice.
Any help please?
If you're still unsure of what I'm asking I'll re-edit
EDIT: The problem is that after calling the ColourInput(line) method, the Scanner method comes in to work (original code). I don't want to remove my Scanner method, I want it to 'skip' the scanner method, and continue into the for loop and switch statements.
You're not passing the string to your call of ColourInput
Try
ColourInput(line);
It is also worth mentioning that your code that reads the file is not safe, you should try to read the file, catch the IOException and close the file in a finally clause, if your code crashes somewhere in the while loop your file might remain open
If I understand correctly you want to be able to repeat the functionality of the ColourInput method with the results of the the ColourRead method.
private static void colourRead() throws IOException
{
FileReader readhandle = new FileReader("C:\\****\\****");
BufferedReader br = new BufferedReader(readhandle);
String line = null;
while((line = br.readLine()) != null)
{
ColourText(line); //there's an error here
}
br.close();
readhandle.close();
}
private static void ColourInput()
{
String fullWord;
Scanner kb = new Scanner(System.in);
System.out.print("Enter whatever: ");
fullWord = kb.nextLine();
System.out.println(fullWord);
ColourText(fullWord);
}
private static void ColourText(String text)
{
char letter;
for (int i = 0; i < text.length(); i++)
{
letter = text.charAt(i);
switch(Character.toUpperCase(letter))
{
case 'A':
{
Blue();
}
break;
}
}
This would let you color the text whether it is read from the file or input from the keyboard(using the ColourText method to change the color). But as other people have mentioned you should add to the file reading code as well.
Edit: You could also remove the String s variables from the first two methods since they are not being used in the methods anywhere.