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
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.
How would i go around getting my txt to output the following format ! It only outputs the first line i input but would like it look like the following>>
This is an example of how I would like an output to look - http://i.stack.imgur.com/7Lfr0.png
import java.io.FileOutputStream;
import java.io.IOException;
import java.io[enter image description here][1].PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class GAMESCORE {
private static char[] input;
public static void main(String[] args) {
int[] minutesPlayed = new int [100];
String gamerName, gamerReport;
String[] gameNames = new String[100];
int[] highScores = new int[100];
#SuppressWarnings("resource")
Scanner Scan = new Scanner(System.in);
System.out.println("-------------- Game Score Report Generator --------------");
System.out.println(" ");
System.out.println("Enter Your Name");
gamerName = Scan.nextLine();
boolean isEmpty = gamerName == null || gamerName.trim().length() == 0;
if (isEmpty) {
System.out.print("Enter your Name.");
gamerName = Scan.nextLine();
}
System.out.println("Enter details in this format - " + " -->");
System.out.println(" ");
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
Scanner scanner = new Scanner(System.in);
List<String> al = new ArrayList<String>();
String word;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("quit")) {
break;
}
al.add(word);
} else {
break;
}
}
String[] splitUpReport;
splitUpReport = gamerReport.split(":");
int i = 0;
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim() );
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
try
{
PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data.txt", true));
writer.println("Player : " + gamerName);
writer.println();
writer.println("--------------------------------");
writer.println();
String[] report = gamerReport.split(":");
writer.println("Game: " + report[0] + ", score= " +report[1] + ", minutes played= " +report[2]);
//writer.println("Games Played : " + minutesPlayed);
writer.close();
} catch (IOException e)
{
System.err.println("You have made an error with data input");
}
System.out.println("You have quit!");
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
GAMESCORE.input = input;
}
}
Well the variable "gamerReport" is set for the first line, and is never touched again other than to print it, and the list "al" has stuff added to it, but is never used. Maybe try something like this?
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class GAMESCORE {
private static char[] input;
public static void main(String[] args) {
int totalGames, totalAchievements, totalTime;
totalGames = 0;
totalAchievements = 0;
totalTime = 0;
String gamerName, gamerReport;
#SuppressWarnings("resource")
Scanner Scan = new Scanner(System.in);
System.out.println("-------------- Game Score Report Generator --------------");
System.out.println(" ");
System.out.println("Enter Your Name");
gamerName = Scan.nextLine();
boolean isEmpty = gamerName == null || gamerName.trim().length() == 0;
if (isEmpty) {
System.out.print("Enter your Name.");
gamerName = Scan.nextLine();
}
System.out.println("Enter details in this format - " + " -->");
System.out.println(" ");
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
Scanner scanner = new Scanner(System.in);
List<String> al = new ArrayList<String>();
String word;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("quit")) {
break;
}
al.add(word);
} else {
break;
}
}
try
{
PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data.txt", true));
writer.println("Player : " + gamerName);
writer.println();
writer.println("--------------------------------");
writer.println();
for(String listString : al){
String[] splitUpReport;
splitUpReport = listString.split(":");
writer.println("Game: " + splitUpReport[0].trim() + ", score= " + splitUpReport[1].trim() + ", minutes played= " +splitUpReport[2].trim());
totalGames++;
totalTime += Integer.parseInt(splitUpReport[2].trim());
totalAchievements += Integer.parseInt(splitUpReport[1].trim());
}
writer.println();
writer.println("--------------------------------");
writer.println();
writer.println("Games Played: " + String.valueOf(totalGames));
writer.println("Total Achievement: " + String.valueOf(totalAchievements));
writer.println("Total Time: " + String.valueOf(totalTime) + " (" + String.valueOf(totalTime/60) + " hours and " + String.valueOf(totalTime%60) + " minutes)");
//writer.println("Games Played : " + minutesPlayed);
writer.close();
} catch (IOException e)
{
System.err.println("You have made an error with data input");
}
System.out.println("You have quit!");
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
GAMESCORE.input = input;
}
}
does anyone know why "Wrong!!!" is printing out 6 times? Is this something to do with my array list as it contains 6 person ticket details in it.
Thank-you in advance...
public class Method1 {
public static void main(String[] arg) {
Method1 sc = new Method1();
sc.run();
}
private void run() {
PersonData p = new PersonData();
List<PersonType> personDetailsList = (List<PersonType>) p.getList();
int input;
try {
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter person ticket number");
input = in.nextInt();
for (PersonType q : personDetailsList) {
if (q.getPersonNumber() == input) {
System.out.println("Person Ticket Number: " + q.getPersonNumber() + "\n"
+ "Person Ticket Name: " + q.getPersonName() + "\n");
break;
}
else if (q.getPersonNumber() != input) {
System.out.println("Wrong!!!");
}
}
} while (input != -1);
System.out.println("Bye");
} catch (Exception e) {
System.out.println(e);
}
}
}
try this
private void run() {
PersonData p = new PersonData();
List<PersonType> personDetailsList = (List<PersonType>) p.getList();
int input;
boolean flag = false;
try {
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter person ticket number");
input = in.nextInt();
for (PersonType q : personDetailsList) {
if (q.getPersonNumber() == input) {
System.out.println("Person Ticket Number: " + q.getPersonNumber() + "\n"
+ "Person Ticket Name: " + q.getPersonName() + "\n");
flag=true;
break;
}
}
if(!flag){
System.out.println("Wrong!!!");
}
} while (input != -1);
System.out.println("Bye");
} catch (Exception e) {
System.out.println(e);
}
}
Can somebody help me: I get the following error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
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 I6Exc2.menuSelection(I6Exc2.java:28)
at I6Exc2.PersonsWrite(I6Exc2.java:120)
at I6Exc2.menuSelection(I6Exc2.java:43)
at I6Exc2.main(I6Exc2.java:19)
This happens when my first input is 3 en my next input is 5. It looks like I did something wrong with closing a scanner? Is somebody able to help me?
Thanks alot.
public class Abc {
public static Person[] names;
public static void main(String[] args) {
menuSelection();
}
public static void menuSelection() {
Scanner s = new Scanner(System.in);
System.out.println( "Choose menu item:" + "\n" + "1. Read File"
+ "\n" + "2. Creates nr objects" + "\n" + "3. Write a File"
+ "\n" + "4. Display nr objects" + "\n" + "5. Exit");
int menuSelection = s.nextInt();
switch (menuSelection) {
case 1: System.out.println("Input a name");
String filePerson = s.next();
PersonRead(filePerson);
break;
case 2: System.out.println("Input nbr of obj");
int p = s.nextInt();
PersonsCreate(p);
break;
case 3: System.out.println("Input a name");
String filePersonWrite = s.next();
PersonWrite(names, filePersonWrite);
break;
case 4: PersonsDisplay(names);
break;
case 5: System.out.println("Good Bye!");
s.close();
break;
default: System.out.println("Invalid choice");
menuSelection();
break;
}
}
public static Person[] PersonRead (String filePerson) {
Person[] names2 = names;
try (FileInputStream fi = new FileInputStream(filePerson)) {
ObjectInputStream os = new ObjectInputStream(fi);
names2 = (Person[])os.readObject();
os.close();
} catch (IOException e) {
System.out.println("Person file not found.");
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("File " + filePerson + " does not contains valid Person object");
}
names = names2;
if (names != null) {
System.out.println("p Person read successfully from file " + filePerson);
}
menuSelection();
return names;
}
public static Person[] PersonsCreate(int p) {
names = new Person[p];
for(int i=0; i < p; i++) {
names[i] = new Person("Mr. Tim" + i, 20 + i, 'M');
}
menuSelection();
return names;
}
public static void PersonWrite (Person[] Person, String filePerson) {
if (names != null) {
try (FileOutputStream fs = new FileOutputStream(filePerson)) {
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(names);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("p Person written successfully to " + filePerson);
} else {
System.out.println("Nothing to write.");
}
menuSelection();
}
public static void PersonsDisplay(Person[] Person) {
for(Person names: Person) {
System.out.println(names);
}
menuSelection();
}
}
NoSuchElementException Thrown by the nextElement, if no more tokens are available
NoSuchElementException
check using hasNextInt(),
if(input.hasNextInt() ){
int p = s.nextInt();
}
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));