Write program which only accepts certain letters in java (exception handling) [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to create a program in Java that writes a line of characters, but only certain characters which in this case is "a" or "b". How would I do this?
Right now it writes "ababbbabbaab", but if it writes "oohmtkgfgk" for example, it needs to throw an exception.
public class Writer {
public void writer() {
try {
FileWriter writer = new FileWriter("FSA.txt", true);
writer.write("ababbbabbaab");
writer.close();
} catch (IOException e) {
System.out.println("Error");
}
}
}

Use regex ^[ab]*$ to validate the string instead of splitting and iterating. Saves lines of code. This regex validates whether the text contains only characters inside [], in your case a&b.
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("FSA.txt", true);
String str = "ababbbabbaabc";
validate(str);
writer.write(str);
writer.close();
} catch (IOException e) {
System.out.println("Error");
}
}
private static void validate(String string) throws IOException {
if(!string.matches("^[ab]*$"))
throw new IOException();
}

Create a method and verify if a or b are present in the string to be stored
Example
// If the 'a' or 'b'are present in string, it returns the index(>=0).
//If not, it returns -1. So, a non-negative return value means that 'a' is
// present in the string.
private boolean checkText(String string) {
final int aIndex = string.indexOf('a');
final int bIndex = string.indexOf('b');
if (aIndex!=-1 && bIndex!=-1) {
return true;
}
else {
return false;
}
}

Split the string and check that all letters are a or b, if not throw a exception.
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("FSA.txt", true);
String str = "ababbbabbaabc";
checkText(str);
writer.write(str);
writer.close();
} catch (IOException e) {
System.out.println("Error");
}
}
private static void checkText(String string) throws IOException {
for(String str: string.split("")) {
if(str.equals("")) continue;
if(!str.equals("a") && !str.equals("b")) throw new IOException();
}
}

Related

Why can't I add text to a file in Java? [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 3 years ago.
It seems that its creating a new file always I try to write or read.
Each line starts with the name of the player, if exists the player should add the score at the end, if not creates a new line and write the info.
.......................
public class JogadorData {
private String nome_player;
private Scanner is;
private FileWriter os;
// this file exists
private final String path = "src/Data/JogadorData";
public JogadorData(String nome_player) {
this.nome_player = nome_player;
try {
is = new Scanner(new File(path));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
os = new FileWriter(path);
} catch (IOException e) {
e.printStackTrace();
}
}
public void escreverScore(String score) {
if (jogadorNovo(nome_player)) {
try {
os.write(nome_player + " " + score);
} catch (IOException e) {
e.printStackTrace();
}
}
else {
escreverResultadoJogadorExistente(score);
}
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// returns true if it is a new player
private boolean jogadorNovo(String nome_player) {
while (is.hasNextLine()) {
String linha = is.nextLine();
String[] info = linha.split(" ");
if (info[0].equals(nome_player)) {
return false;
}
}
return true;
}
}
....................................
....................................
Test:
public class TESTE {
public static void main(String[] args) {
JogadorData jogador = new JogadorData("Manelina");
jogador.escreverScore("100");
// System.out.println(jogador.lerMelhorResultado());
}
}
The example below is a simplified read/write to file from what you have, done in similar format to what you are trying to do. What this code does is reads every line from the file you are loading from via Files#readAllLines, then runs through each line, (put your logic where I commented the if statement, and then output.add appends the new version of the line you are modifying, storing it in the array list "output", after which the file is saved to the path defined by Files#write
List<String> output = new ArrayList<>();
List<String> lines = Files.readAllLines(Paths.get("Path/To/File.txt"));
for (String line : lines) {
//... if (playerExists(line))
output.add(line + " " + score);
}
Files.write(Paths.get("Path/To/Save/File.txt"), output);

How to overwrite a file that is altering an arraylist

I'm writing a program in order to keep track of DVDs in my library. I'm having trouble altering the text file that saves an added or removed DVD object from the arraylist. Whenever I call my save method, which is the one that overwrites the existing text file holding all the information, it will not change it whatsoever. My add and remove methods work fine but it's just the save method which overwrites the file that I'm reading from that will not work. The following code is what I was attempting to use to save the arraylist to the file. My filename is DVDCollection.txt and the boolean variable flag is a static variable used to check whether or not the code which adds or removes an object from the arraylist was reached.
public void save() {
try{
if(flag=true){
FileWriter instream = new FileWriter("DVDCollection.txt",false);
instream.close();
}else{
return;
}
}catch(IOException e){
System.out.println("The file could not be written to!");
}
}
If you are using java 8 or above it's as simple as:
List<String> lines = Arrays.asList("first line", "second line");
try {
Files.write(Paths.get("my-file.txt"), lines);
} catch (IOException e) {
//handle exception
}
Make sure you provide the right path!
Not sure, why this method should save an array list, as the actual code that writes to this file is missing. Here is simple test, let's start here:
import java.io.*;
import java.util.*;
public class FileSaveTest {
public static void main(String[] args) {
FileSaveTest test = new FileSaveTest();
test.fill();
test.save();
}
public void fill() {
arrayList.add("My disc 1");
arrayList.add("My disc 2");
arrayList.add("Another disc");
}
public void save() {
try {
if(flag) { // you dont need ==true
FileWriter instream = new FileWriter("DVDCollection.txt",false);
for (String entry : arrayList) {
instream.write(entry + "\n");
}
instream.close();
} else {
return;
}
} catch(IOException e) {
System.out.println("The file could not be written to!");
}
}
private ArrayList<String> arrayList = new ArrayList<>();
private static boolean flag = true;
}
Next, it's not very good, to close the file in such manner. If an exception occurs while writing, the file will not be closed. instream.close() should be put into the "finally" block. This block will be executed in any case, regardless of whether an exception occurred or the return keyword met:
public void save() {
Writer instream = null;
try {
if(flag) { // you dont need ==true
instream = new FileWriter("DVDCollection.txt",false);
for (String entry : arrayList) {
instream.write(entry + "\n");
}
} else {
return;
}
} catch(IOException e) {
System.out.println("The file could not be written to!");
} finally {
try {
if (instream != null)
instream.close();
} catch (IOException e) {
System.err.println("Exception during close");
}
}
}
Or, if you are using java 7, you can use try-with-resources syntax:
public void save() {
if(flag) { // you dont need ==true
try (Writer instream = new FileWriter("DVDCollection.txt",false)) {
for (String entry : arrayList)
instream.write(entry + "\n");
} catch(IOException e) {
System.out.println("The file could not be written to!");
}
} // you dont need "return else { return; }" anymore
}

How to get array.length after it has been deserialized [duplicate]

This question already has answers here:
why does the catch block give an error with variable not initialized in Java
(7 answers)
Closed 6 years ago.
So, I'm working on a project that automates everything from character sheets to dice rolls for a table top RPG I like to play. I'm trying to store character data (character name, 2 arrays of stats, and 2 arrays of those stat values) that can be accessed at the start of executing the app. This has been very helpful so far.
However, I'd also like to display the name and stats so the user can confirm that this is the character data they want to use. And I'm having trouble displaying the data in a readable format. Here's my code (you'll find the problem I'm having toward the bottom, although if you see anything else that could be optimized along the way, I would appreciate any feedback :-)":
import java.io.*;
import javax.swing.JOptionPane;
public class fengShuiFiles implements Serializable {//start class
private FileOutputStream outFile;
private ObjectOutput objectWriter;
private FileInputStream inFile;
private ObjectInputStream objectReader;
public void WriteFile(String fileNameIn, String[] sArray1, String[] sArray2,
String[] sArray3, String[] sArray4) {
try {
outFile = new FileOutputStream(fileNameIn + ".txt", true);
objectWriter = new ObjectOutputStream(outFile);
objectWriter.writeObject(sArray1);
objectWriter.writeObject(sArray2);
objectWriter.writeObject(sArray3);
objectWriter.writeObject(sArray4);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "I/O occurred during a write operation\nFor more",
"information see console output.",
"Read File", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
} // End try/catch
} // End Open
//not sure if I'll need this. Keeping it for now just in case
//public void writeRecords(String textRecords)
//{
// outFile.close();
// pw.println(textRecords);
//} // End WriteRecords
public void ReadFile(String fileNamein) throws FileNotFoundException {
fengShuiFiles[] sArray1, sArray2, sArray3, sArray4;
try {
inFile = new FileInputStream(fileNamein + ".txt");
objectReader = new ObjectInputStream(inFile);
sArray1 = (fengShuiFiles[]) objectReader.readObject();
sArray2 = (fengShuiFiles[]) objectReader.readObject();
sArray3 = (fengShuiFiles[]) objectReader.readObject();
sArray4 = (fengShuiFiles[]) objectReader.readObject();
} catch (IOException | ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "I/O error occurred opening a",
"file\nFor more information see console output.",
"Read File", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
} // End try/catch
for (int x = 0; x < sArray1.length; x++) {
}
}
public void closeFile() {
try {
outFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // End closeFile
}//end class
So, that sArray1.length in the for statement toward the bottom? It's coming up with an error message saying that sArray1 may not have been initialized. And I'm having trouble figuring out why, and how I can get that length so I can print out the arrays in a readable manner. Does anyone have any ideas? Thanks.
You need to initialize local variables. If an exception occurs, it's possible that some or all of the arrays aren't initialized and the compiler won't allow that.
The easiest way to get rid of the error is to initialize the arrays to null, but your program has a logic problem. You're catching the exceptions and continuing, even though there's no way your program can work correctly after that. You should instead throw the exceptions out of the readFile() method and then most likely exit the program. You could also continue as if the file didn't exist, but at least show a warning about it.
You always have to initialize variables in java. You do this in your try block, but if an exception occurs, the array will not have been initialized.
You can move the for loop to the try block:
public void ReadFile(String fileNamein) throws FileNotFoundException {
fengShuiFiles[] sArray1, sArray2, sArray3, sArray4;
try {
...
for(int x = 0; x < sArray1.length; x++) {
}
} catch (IOException | ClassNotFoundException e) {
...
} // End try/catch
}
Or use a default value to initialize the array in the catch block:
public void ReadFile(String fileNamein) throws FileNotFoundException {
fengShuiFiles[] sArray1, sArray2, sArray3, sArray4;
try {
...
} catch (IOException | ClassNotFoundException e) {
...
sArray1 = new fengShuiFiles[0]; // Some default value.
} // End try/catch
for(int x = 0; x < sArray1.length; x++) {
}
}
Something that might be more convenient though, is to return the read arrays, and do something with them in the calling method.
For instance:
public Optional<fengShuiFiles[][]> ReadFile(String fileNamein) throws FileNotFoundException {
try {
fengShuiFiles[] sArray1, sArray2, sArray3, sArray4;
// read the file
return Optional.of(new fenShuiFiles[][]{ sArray1, sArray2, sArray3, sArray4 });
} catch (IOException | ClassNotFoundException e) {
...
return OPtional.empty();
}
}
Then in some other method:
Optional<fengShuiFiles[][]> ret = ReadFile(...);
if(ret.isPresent()) {
for(fengShuiFiles[] arr : ret.get()) {
System.out.println(Arrays.toString(arr)); // Print here
}
}

unblocked scanner function java [duplicate]

This question already has answers here:
how to read from standard input non-blocking?
(5 answers)
Closed 8 years ago.
I would like to ask to the user if he could press a key before continuing. Then my program will wait for that during 10 seconds.
If nothing is done, then, I would like to be able to exit the program.
My problem is that the function scanner block my program (until the user have pressed a key) and doesn't allow the program to execute the end.
Do you have any idea of what I could do/use instead of scanner? I am just a beginner in java so please, be indulgent with me.
import java.util.Scanner;
public class Test{
public Test(){
Scanner scan = new Scanner(System.in);
boolean first = true;
System.out.println("Press any key to start.\n");
for(int fr = 0; fr <11; fr++){
System.out.println(fr);
try{
Thread.sleep(1000);
} catch (Exception e) {
System.err.println("error -> "+e.getMessage()); // in case of exception, error message
}
if(fr == 10){
Default def = new Default();
}else if(scan.hasNext() == true){
//System.out.println("Hello");
User user = new User(); // or exit, it doesn't matter
}
}
}
}
Use a KeyListener.
First make a Component, give it the focus, and add a KeyListener.
Example code:
Component comp = new Componenet();
comp.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
System.out.print("Hello");
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
});
try {
Thread.sleep(1000);
} catch (Exception e) {
}
System.exit(0);
A possible solution is using a different thread to read user input from the scanner. Here is an example code:
Scanner scanner = new Scanner(System.in);
ExecutorService scannerExecutor = Executors.newSingleThreadExecutor();
Future<String> nextLineFuture = scannerExecutor.submit(scanner::nextLine);
/* For Java < 8:
Future<String> nextLineFuture = scannerExecutor.submit(new Callable<String>() {
#Override
public String call() throws Exception {
return scanner.nextLine();
}
});
*/
String input;
try {
input = nextLineFuture.get(5, TimeUnit.SECONDS);
}
catch (TimeoutException e) {
input = "Nothing was entered";
}
catch (InterruptedException | ExecutionException e) {
// Handle the exception
return;
}
System.out.println(input);
However, you need to keep in mind some of the issues with this:
Even when nextLineFuture.get(...) throws TimeoutException, the nextLine call will still be running. If you later run scannerExecutor.submit(scanner::nextLine) again, the input will first be consumed by the previous call, so you should make sure to have a reference to the last Future created whose result hasn't been used yet.
Because of the issue above, this approach will not work if you need to use different scanner methods such as nextBoolean, nextInt, etc. You can, however, always use nextLine on the primary scanner and then parse the line manually (for example, by using yet another scanner)

Error Reading and writing files (Java) [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hi guys i just implemented object files into my program and i am constantly getting the errors (error reading file and problem writing to file) these are 2 errors in my try catch block, when i try to read the file it does not load, saving doesn't work either.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class Stores implements Serializable
{
public static ArrayList<Student> stud1 = new ArrayList<Student>();
public static ArrayList<SubjectTeacher> sTeach1 = new ArrayList<SubjectTeacher>();
private static int iT = 0;
private static int iS = 0;
public static void savet (ArrayList<SubjectTeacher> teachIn, int count)
{
iT = count;
sTeach1 = teachIn;
saveTeachToFile();
}
public static void saves (ArrayList<Student> studIn, int count)
{
iS = count;
stud1 = studIn;
saveStudToFile();
}
public static ArrayList<Student> getStud ()
{
return stud1;
}
public static ArrayList<SubjectTeacher> getTeach ()
{
return sTeach1;
}
public static int getStudSize()
{
return stud1.size();
}
public static int getTeachSize()
{
return sTeach1.size();
}
private static void saveStudToFile()
{
try
{
// create a FileOutputStream object which will handles the writing of the sudent list of objects to the file.
FileOutputStream studentFile = new FileOutputStream("Students.obf");
// the OutputObjectStream object will allow us to write whole objects to and from files
ObjectOutputStream studentStream = new ObjectOutputStream(studentFile);
for(Student item: stud1) // enhanced for loop
// Loop through the list of studentsListIn and for each of these objects, wite them to the file
{
studentStream.writeObject(item);
}
//close the file so that it is no longer accessible to the program
studentStream.close();
}
catch(IOException e)
{
System.out.println("There was a problem writing the File");
}
}
private static void saveTeachToFile()
{
try
{
FileOutputStream teacherFile = new FileOutputStream("Teacher.obf");
ObjectOutputStream teacherStream = new ObjectOutputStream(teacherFile);
for(SubjectTeacher item1: sTeach1) // enhanced for loop
{
teacherStream.writeObject(item1);
}
//close the file so that it is no longer accessible to the program
teacherStream.close();
}
catch(IOException e)
{
System.out.println("There was a problem writing the File");
}
}
public static void loadStudentList()
{
boolean endOfFile = false;
Student tempStudent;
try
{
// create a FileInputStream object, studentFile
FileInputStream studentFile = new FileInputStream("Students.obf");
// create am ObjectImnputStream object to wrap around studentStream
ObjectInputStream studentStream = new ObjectInputStream(studentFile) ;
// read the first (whole) object with the readObject method
tempStudent = (Student) studentStream.readObject();
while (endOfFile != true)
{
try
{
stud1.add(tempStudent);
// read the next (whole) object
tempStudent = (Student) studentStream.readObject();
}
//use the fact that the readObject throws an EOFException to check whether the end of eth file has been reached
catch(EOFException e)
{
endOfFile = true;
}
studentStream.close();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
catch(ClassNotFoundException e) // thrown by readObject
/* which indicates that the object just read does not correspond to any class
known to the program */
{
System.out.println("Trying to read an object of an unkonown class");
}
catch(StreamCorruptedException e) //thrown by constructor
// which indicates that the input stream given to it was not produced by an ObjectOutputStream object {
{
System.out.println("Unreadable File Format");
}
catch(IOException e)
{
System.out.println("There was a problem reading the file");
}
}
public static void loadTeacherList()
{
boolean endOfFile = false;
SubjectTeacher tempTeacher;
try
{
FileInputStream teacherFile = new FileInputStream("Teacher.obf");
ObjectInputStream teacherStream = new ObjectInputStream(teacherFile) ;
tempTeacher = (SubjectTeacher) teacherStream.readObject();
while (endOfFile != true)
{
try
{
sTeach1.add(tempTeacher);
// read the next (whole) object
tempTeacher = (SubjectTeacher) teacherStream.readObject();
}
//use the fact that the readObject throws an EOFException to check whether the end of eth file has been reached
catch(EOFException e)
{
endOfFile = true;
}
teacherStream.close();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
catch(ClassNotFoundException e) // thrown by readObject
/* which indicates that the object just read does not correspond to any class
known to the program */
{
System.out.println("Trying to read an object of an unkonown class");
}
catch(StreamCorruptedException e) //thrown by constructor
// which indicates that the input stream given to it was not produced by an ObjectOutputStream object {
{
System.out.println("Unreadable File Format");
}
catch(IOException e)
{
System.out.println("There was a problem reading the file");
}
}
}
Well, for one thing, you should edit the question with the correct code so it doesn't get closed. Second, A couple of things could be happening.
The classes you're writing to file aren't serializable
The files are readonly or write protected somehow
Based on the code from your updated question, it looks like you may be confusing which classes need to implement Serializable. The classes that need to implement that are the ones you're actually writing to file (ie SubjectTeacher, etc.).
Check those two, and let me know what you find.
Also, I'd suggest stepping the code and seeing what the exceptions look like at runtime. You'll get a much better idea of what's going on.

Categories