I'm at my wits end here, me and a friend have been trying to get user input and write that to a .txt file but I have no idea where I'm gone wrong...
public static void main (String [] args)
{
toTxtFile();
}
static void toTxtFile()
{
//Scanner in = new Scanner (System.in);
try
{
File records = new File("C:\\Users\\rodriscolljava\\Desktop\\IOFiles\\test3.txt");
records.createNewFile();
FileWriter fw = new FileWriter(records, true);
PrintWriter pw = new PrintWriter(fw);
String str = JOptionPane.showInputDialog(null,"Enter your text below");
str = str.toUpperCase();
pw.println(str);
if (str.length() == 3 && str.contains("END"))
{
JOptionPane.showMessageDialog(null, "You've ended the task","ERROR",JOptionPane.ERROR_MESSAGE);
pw.flush();
pw.close();
//in.close();
}
else
{
pw.println(str);
toTxtFile();
}
}
catch (IOException exc)
{
exc.printStackTrace();
}
}
}
I've tried putting the loop as a do/while with far from good results, any help would be appreciated D:
You can use a try-with-resources to close when you're done; and you might use an infinite loop with a break like
static void toTxtFile() {
File records = new File("C:\\Users\\rodriscolljava\\Desktop\\IOFiles\\test3.txt");
try (PrintWriter pw = new PrintWriter(records)) {
while (true) {
String str = JOptionPane.showInputDialog(null, "Enter your text below");
str = str.toUpperCase();
if (str.equals("END")) {
JOptionPane.showMessageDialog(null, "You've ended the task",
"ERROR", JOptionPane.ERROR_MESSAGE);
break;
}
pw.println(str);
}
} catch (IOException exc) {
exc.printStackTrace();
}
}
you have to add ,
pw.flush();
after pw.println(str);
and want to do it again and again then put it into while loop likewise,
while(true){
String str = JOptionPane.showInputDialog(null,"Enter your text below");
str = str.toUpperCase();
if (str.length() == 3 && str.contains("END"))
{
JOptionPane.showMessageDialog(null, "You've ended the task","ERROR",JOptionPane.ERROR_MESSAGE);
break;
}
pw.println(str); // else write to file...
pw.flush();
}
pw.flush();
pw.close();
Related
I got a problem with my university task.
How to start program: type 1 to create a file then write down the name of text file and fill it with words. After that press enter 2 times and you will get my problem -> NoSuchElementException.
I tried to fix this problem by creating different types of loops or changing the structure of the project, but still don`t know how to fix it. I just stuck and wasted some time on this problem. If someone more knowledgeable could help me out it would be wonderful.
My code all in one class:
import java.io.*;
import java.util.Scanner;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
showMenu();
}
static void showMenu() throws IOException {
menuOptions();
Scanner scan = new Scanner(System.in);
int userMenuInput = 0;
if (scan.hasNextLine()) {
try {
userMenuInput = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
while (true) {
switch (userMenuInput) {
case 1:
System.out.println("Create a file");
String userFileName = scan.nextLine();
createFile(userFileName + ".txt");
break;
case 2:
System.out.println("Delete a file");
String userDeleteFile = scan.nextLine();
deleteFile(userDeleteFile);
break;
case 3:
System.out.println("Write to a file");
break;
case 4:
System.out.println("Exit from program");
System.exit(0);
break;
default:
System.out.println("Please type from 1 to 4!");
}
}
}
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
in.close(); // Close reader from input
out.close(); // Close writer to file
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
private static void deleteFile(String fileNameToDelete){
try{
System.out.println("Enter file name to delete: ");
File sourceFile = new File(fileNameToDelete+".txt");
sourceFile.delete();
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static void menuOptions(){
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Create file");
System.out.println("2 - Delete file");
System.out.println("3 - Write to file");
System.out.println("4 - Quit");
System.out.println();
}
}
to add to Ryans answer, the exception comes from the fact that closing any object making use of the input/output stream doesn't really close that object, but the entire input/output stream. A dirty fix would simply be NOT to close them. so change your method createFile from:
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
in.close(); // Close reader from input
out.close(); // Close writer to file
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
to:
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
//were close used to be
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
I will stess that this is NOT ideal. You should do what Ryan said and make it so you only use use a single System.in reader. Doing that is your job, not mine. But if this is just to get something working so you can submit an assignment on time, it will work.
Another issue is that the prompt asking for a menu option is outside of the while loop. This means that it will accept only one input, then get stuck in an infinite loop. You could move that into the loop, but a cleaner alternative is to put all of the menu logic into the menuOption method, pass a reference of the Scanner to that method, and have it return an int for your switch.
for example:
menuOption():
private static int menuOptions(Scanner scan){
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Create file");
System.out.println("2 - Delete file");
System.out.println("3 - Write to file");
System.out.println("4 - Quit");
System.out.println();
if (scan.hasNextLine()) {
try {
return Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
return 0;
}
showMenu():
static void showMenu() throws IOException {
Scanner scan = new Scanner(System.in);
while (true) {
switch (menuOptions(scan)) {
case 1:
System.out.println("Create a file");
String userFileName = scan.nextLine();
createFile(userFileName + ".txt");
break;
case 2:
System.out.println("Delete a file");
String userDeleteFile = scan.nextLine();
deleteFile(userDeleteFile);
break;
case 3:
System.out.println("Write to a file");
break;
case 4:
System.out.println("Exit from program");
System.exit(0);
break;
default:
System.out.println("Please type from 1 to 4!");
}
}
}
all of those changes lead to this as the final code:
import java.io.*;
import java.util.Scanner;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
showMenu();
}
static void showMenu() throws IOException {
Scanner scan = new Scanner(System.in);
while (true) {
switch (menuOptions(scan)) {
case 1:
System.out.println("Create a file");
String userFileName = scan.nextLine();
createFile(userFileName + ".txt");
break;
case 2:
System.out.println("Delete a file");
String userDeleteFile = scan.nextLine();
deleteFile(userDeleteFile);
break;
case 3:
System.out.println("Write to a file");
break;
case 4:
System.out.println("Exit from program");
System.exit(0);
break;
default:
System.out.println("Please type from 1 to 4!");
}
}
}
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
//were close used to be
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
private static void deleteFile(String fileNameToDelete){
try{
System.out.println("Enter file name to delete: ");
File sourceFile = new File(fileNameToDelete+".txt");
sourceFile.delete();
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static int menuOptions(Scanner scan){
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Create file");
System.out.println("2 - Delete file");
System.out.println("3 - Write to file");
System.out.println("4 - Quit");
System.out.println();
if (scan.hasNextLine()) {
try {
return Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
return 0;
}
}
Remember to close scan in your quit method.
Program execution does not loop back once I run the code to read data.
Ive tried shifting where I place the try catch statements along with the finally statement and all manners of breaks continue.
long code;
char choice;
Cars CarSales = new Cars(); //It creates a Java object and allocates memory for it on the heap.
Scanner sc = new Scanner(System.in);
System.out.println(" -----CARS SALES YARD------"); //The println is a method of java.io.PrintStream.
do {
System.out.println("1. Add item");
choice = sc.nextLine().charAt(0);
switch (choice) { //switch statement allows a variable to be tested for equality against a list of values.
case '6':
try{
CarSales.ReadData();
continue;
}
catch(IOException e){
System.out.println("Error reading file '" );
continue;
}
default:
System.out.println("Invalid Selection\n");
}
} while (choice != '6'); //while loop statement repeatedly executes a statement as long as a given condition is true
sc.close();
public void ReadData() throws IOException{//This Method is in the Cars class
String fileName = "input.txt";
String line = null;
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
System.out.println("TRY");
No error messages though program execution just stops looping.
By moving the continue; to after the catch. Like,
do {
System.out.println("1. Add item"); //<-- where are 2-6?
choice = sc.nextLine().charAt(0);
switch (choice) {
case '6': // <-- don't forget case '1' - '5'
try {
CarSales.ReadData();
} catch (IOException e) {
System.out.println("Error reading file '");
}
continue; // <-- here, or a break;
default:
System.out.println("Invalid Selection\n");
}
} while (choice != '6');
my program works great and next, I want to turn it into a GUI. I have a menu:
System.out.println("Menu: ");
System.out.println("1) Enter Student Grade(s)");
System.out.println("2) View Student Grade(s)");
System.out.println("3) Delete Student Grade(s)");
System.out.println("4) Exit");
I'm not sure how to implement this into a GUI. I could maybe have 4 text fields: First name, Last name, unit and mark. I could have a button to delete, and a button to open the 'GradeEnter.txt' file perhaps. Again, I am not sure how I would implement this into a separate GUI class. Could anyone help or get me started? Thanks
Code:
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ExamGrades {
private static int menu = 0;
private static String firstName = "";
private static String firstNameDelete = "";
private static String lastName = "";
private static String lastNameDelete = "";
private static String unit = "";
private static int examMark = 0;
private static String entry = "";
private static String firstCap = "";
private static String surCap = "";
private static Scanner scan = new Scanner(System.in);
public static BufferedWriter bw;
public static BufferedReader reader;
public static PrintWriter out;
public static File deleteRecord;
public static void setup() {
reader = null;
File deleteRecord = new File("GradeEnter.txt");
try {
reader = new BufferedReader(new FileReader(deleteRecord));
} catch (FileNotFoundException e1) {
System.err.println("No file found");
}
FileWriter grades = null;
try {
grades = new FileWriter("GradeEnter.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(grades);
out = new PrintWriter(bw);
}
public static void menuActions()
{
System.out.println("Menu: ");
System.out.println("1) Enter Student Grade(s)");
System.out.println("2) View Student Grade(s)");
System.out.println("3) Delete Student Grade(s)");
System.out.println("4) Exit");
menu = scan.nextInt();
switch(menu) {
case 1:
enterGrades();
break;
case 2:
viewGrades();
break;
case 3:
deleteGrades();
break;
case 4:
exitProgram();
break;
default:
menuActions();
}
}
public static void enterGrades()
{
System.out.print("Please enter student first name: ");
firstName = scan.next();
while(!firstName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid first name: ");
firstName = scan.next();
}
firstCap = firstName.substring(0,1).toUpperCase() + firstName.substring(1);
System.out.print("Please enter student surname: ");
lastName = scan.next();
while(!lastName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid surname: ");
lastName = scan.next();
}
surCap = lastName.substring(0,1).toUpperCase() + lastName.substring(1);
System.out.print("Please select Subject Unit: ");
unit = scan.next();
System.out.print("Please enter student mark: ");
while (!scan.hasNextInt())
{
System.out.print("Please enter a valid mark: ");
scan.next();
}
examMark = scan.nextInt();
if (examMark < 40)
{
System.out.println("Failed");
}
else if (examMark >= 40 && examMark <= 49)
{
System.out.println("3rd");
}
else if (examMark >= 50 && examMark <= 59)
{
System.out.println("2/2");
}
else if (examMark >= 60 && examMark <= 69)
{
System.out.println("2/1");
}
else if (examMark >= 70 && examMark <= 100)
{
System.out.println("1st");
}
else
{
System.out.println("Invalid Mark");
}
entry = (firstCap + " " + surCap + ", " + unit + ", " + examMark);
out.println(entry);
menuActions();
}
public static void viewGrades() {
int i =1;
String line;
try {
while ((line = reader.readLine()) != null) {
System.out.println(i + ") " + line);
i++;
}
} catch (IOException e) {
System.err.println("Error, found IOException when searching for record " + e.getMessage());
}
menuActions();
}
public static void deleteGrades(){
int i = 1;
String line;
File tempFile = new File("MyTempFile.txt");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e) {
System.err.println("Error, found IOException when using BufferedWriter " + e.getMessage());
}
System.out.println("Current Entries Stored: ");
i =1;
try {
while ((line = reader.readLine()) != null) {
System.out.println(i + ") " + line);
i++;
}
} catch (IOException e) {
System.err.println("Error, found IOException when searching for record to delete " + e.getMessage());
}
Scanner scanner = new Scanner(System.in);
System.out.print("To delete, please enter student's First Name: ");
firstNameDelete = scanner.nextLine();
System.out.print("Now, please enter student's Surname: ");
lastNameDelete = scanner.nextLine();
try {
reader.close();
} catch (IOException e) {
System.err.println("Error, found IOException when closing closing reader: " + e.getMessage());
}
try {
reader = new BufferedReader(new FileReader(deleteRecord));
} catch (FileNotFoundException e) {
System.err.println("No file found");
}
String currentLine = "";
try {
currentLine = reader.readLine();
} catch (IOException e) {
System.err.println("Error, found IOException when reading current line " + e.getMessage());
}
while(currentLine != null) {
if(!currentLine.contains(firstNameDelete) && !currentLine.contains(lastNameDelete)) {
try {
writer.write(currentLine);
} catch (IOException e) {
System.err.println("Error, found IOException when deleting line " + e.getMessage());
}
try {
writer.newLine();
} catch (IOException e) {
System.err.println("Error, found IOException when writing a new line " + e.getMessage());
}
}
try {
currentLine = reader.readLine();
} catch (IOException e) {
System.err.println("Error, found IOException when reading file " + e.getMessage());
}
}
System.out.print("if name matches, it will be deleted ");
try {
reader.close();
} catch (IOException e1) {
System.err.println("Error, found IOException when closing reader " + e1.getMessage());
}
try {
writer.close();
} catch (IOException e) {
System.err.println("Error, found IOException when closing writer " + e.getMessage());
}
deleteRecord.delete();
tempFile.renameTo(deleteRecord);
scanner.close();
}
public static void exitProgram(){
System.out.println("Thanks for using 'GradeEnter' ");
System.exit(0);
}
public static void main(String[] args) throws Exception {
System.out.println("Welcome to the 'GradeEnter' program! ");
setup();
menuActions();
out.close();
scan.close();
reader.close();
}
}
EDIT: GradeEnter.txt looks like:
Matt Well, Computing, 100
Adam Smith, Computing, 99
Above is made up of First Name, Last Name, Course and Mark
public static void main (String[] args) {
try{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
System.out.println ("1..case1 | 2..case2");
String ch=Integer.parseInt(bf.readLine()); //user input for switch
System.out.println (ch);
bf.close();
switch(ch) { //userinput ch variable switch in case
case 1 :
String data=bf.readLine();
bf.close();
System.out.println(data);
break;
case 2 :
System.out.print ("Enter Key ");
String key=bf.readLine();
bf.close();
System.out.println(key);
break;
default :
System.out.println ("wrong choice");
}
}
catch(IOException e){
System.out.println ("io error");
}
bf.close();
}
//every time after 1st user input it goes to partcular matching case, but at the next user input it throws an exception.
please help..
thanks in advance..
Its a good habit to close in finally block else use try with resource if you are using java7 or higher version
See this mkyongs example
Also this line is wrong String ch=Integer.parseInt(bf.readLine()); make it to int
you are converting bf.readLIne() to int and storing in string,This is wrong.
Another error is you are closing bf.close(); after the try-catch block so compiler may complain
Complete working code
public static void main (String[] args) {
BufferedReader bf=null;
try{
bf=new BufferedReader(new InputStreamReader(System.in));
System.out.println ("1..case1 | 2..case2");
int ch=Integer.parseInt(bf.readLine()); //user input for switch
System.out.println (ch);
switch(ch){ //userinput ch variable switch in case
case 1 :
String data=bf.readLine();
System.out.println(data);
break;
case 2 :
System.out.print ("Enter Key ");
String key=bf.readLine();
System.out.println(key);
break;
default :
System.out.println ("wrong choice");
}
} catch(IOException e){
System.out.println ("io error");
e.printStackTrace();
}
finally
{
try {
bf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Given the following code, the first call to readLine() is not blocking, both "Enter name:" and "Enter address:" are printed at the same time, and address gets assigned to whatever is entered. Why? I've tried putting them in separate try blocks, getting rid of the loop and generally reordering things.
public class AddressReader {
public static void main(String[] args) {
Path file = Paths.get("d:/java IO/addresses.txt");
try {
Files.createDirectories(file.getParent());
} catch (IOException e) {
System.err.println("Error craeting directory: " + file.getParent());
e.printStackTrace();
System.exit(1);
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int c = 0;
try {
System.out.println("<a>dd an entry or <r>ead entries");
c = br.read();
} catch (IOException e) {
System.out.println("An error has occured, try again");
}
switch (c) {
case 'a':
String name = null;
String address = null;
while (name == null || name == "" || address == null || address == "") {
try {
System.out.println("Enter name:");
name = br.readLine();
System.out.println("Enter address:");
address = br.readLine();
} catch (IOException e) {
System.out.println("An error has occured, try again");
}
System.out.println("name = " + name);
System.out.println("address = " + address);
}
//writeEntry(file, name, address);
break;
case 'r':
//readEntries(file);
break;
default:
System.out.println("Invalid entry, try again.");
}
}
}
This is because of this line:
c = br.read();
This does not consume the new-line character that is produced by pressing ENTER.
To solve this issue, use this instead:
c = br.readLine().charAt(0);
Over and above whats already been said, for what you're trying to do I suggest using the Console instead:
Console console = System.console();
String name = console.readLine("Create a name.");
char[] password = console.readPassword("Create a password.");
System.out.println(name + ":" + new String(password));