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();
}
Related
I have been encountering a specific problem where only the first item in Arraylist is included when it comes to iterating each element in Arraylist (to search/to remove). That means that the second until n-1 iteams won't be found whenever I try to iterate.
Edited: currently improving my code.
You could try the following program. It is perfectly working only when adding the first record of the order: I can remove and search its values. However, when adding the second order: I can not remove and search its values, rather it is not found.
Source code
import java.util.*;
import java.io.*;
public class TestOrders {
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchElementException {
File afile = new File("order.txt");
FileOutputStream outFile = new FileOutputStream("order.txt");
ObjectOutputStream outStream = new ObjectOutputStream(outFile);
FileInputStream inFile = new FileInputStream("order.txt");
ObjectInputStream inStream = new ObjectInputStream(inFile);
//Create an arraylist of order
ArrayList<Order> theorder = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Order");
System.out.println("Please choose an option (1-5): ");
int choice = 0;
try {
while (choice != 5) {
//A list of options
System.out.println("\n1. Add a new order: ");
System.out.println("2. Search an order: ");
System.out.println("3. Compute sum of all orders:");
System.out.println("4. Remove an order: ");
System.out.println("5. Exit: ");
//prompt user
System.out.print("Pick a number: ");
if (scan.hasNextInt()) {
choice = scan.nextInt();
}
switch(choice) {
case 1:
addNewOrder(outStream, theorder);
break;
case 2:
searchOrder(outStream, inStream, theorder);
break;
case 3:
computeSum(afile, theorder);
break;
case 4:
removeOrder(outStream, inStream, theorder);
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Please enter from (1-5)");
}
}
} catch (IOException | InputMismatchException ex) {
System.out.println(ex);
} finally {
if (choice == 5) {
scan.close();
outStream.close();
inStream.close();
}
}
}
public static void addNewOrder(ObjectOutputStream outStream, ArrayList<Order> theorder) throws IOException {
Scanner input = new Scanner(System.in);
Order anorder = new Order();
System.out.print("Enter the order ID: ");
anorder.setOrderID(input.nextInt());
input.nextLine();
System.out.print("Enter the customer name: ");
anorder.setCustomerName(input.nextLine());
System.out.print("Enter the order (meal/drink): ");
anorder.setOrderType(input.nextLine());
System.out.print("Enter the order price: ");
anorder.setPrice(input.nextDouble());
if(theorder.size() <= 1000) {
theorder.add(anorder);
outStream.writeObject(anorder);
System.out.println("Order information saved.\n");
} else {
System.out.println("There is not enough space.");
}
}
public static void searchOrder(ObjectOutputStream outStream, ObjectInputStream inStream, ArrayList<Order> theorder) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
Order o = new Order();
System.out.println("Please enter a customer ID: ");
int custID = input.nextInt();
for (Order or : theorder) {
if(or.getOrderID() == custID) {
System.out.println(or.toString());
break;
} else {
System.out.println("No matching record found");
break;
}
}
}
public static void computeSum(File aFile, ArrayList<Order> theorder) throws FileNotFoundException, IOException {
double sum = 0;
for (Order o : theorder) {
sum += o.getPrice();
}
sum = (double) Math.round(sum*100)/100;
System.out.println("The total sum of price for " + theorder.size() + " orders is " + sum);
}
public static void removeOrder(ObjectOutputStream outStream, ObjectInputStream inStream, ArrayList<Order> theorder) {
Iterator<Order> iterator = theorder.iterator();
Scanner input = new Scanner(System.in);
System.out.println("Enter the order ID to remove: ");
int custID = input.nextInt();
while (iterator.hasNext()) {
Order anorder = iterator.next();
if(anorder.getOrderID() == custID) {
theorder.remove(anorder);
System.out.println(anorder.toString());
break;
} else {
System.out.println("Not found\n");
break;
}
}
for (Order o : theorder) {
System.out.println(o.toString());
}
}
}
Order class
import java.util.*;
import java.io.*;
public class Order implements Serializable {
private int orderID;
private String customerName;
private String orderType;
private double price;
public Order() {
}
public Order(int orderID, String customerName, String orderType, double price) {
this.orderID = orderID;
this.customerName = customerName;
this.orderType = orderType;
this.price = price;
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public String getCustomerName() {
return this.customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getOrderType() {
return this.orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString() {
return this.orderID + " " + this.customerName + " " + this.orderType + " " + this.price + "\n";
}
}
This part is where I am struggling. I had tried using iterator but it got the same result, second item cannot be iterated/found.
for (Order o : theorder) {
if(o.getOrderID() == orderIDSearch) {
theorder.remove(orderIDSearch);
System.out.println("Order has been successfully removed");
continue;
} else {
System.out.println("Not found ");
break;
}
}
What should I do to fix this problem? is there any way it can be solved?
for ( Order o : theorder ) {
if ( o.getOrderID() == orderIDSearch ) {
theorder.remove(orderIDSearch);
System.out.println("Order has been successfully removed");
continue;
} else {
System.out.println("Not found ");
break;
}
}
There are several problems here:
First, removal of an element of a collection whilst iterating across the collection requires a different technique than you are using. Generally, modifying a collection in the midst of iteration will result in a ConcurrentModificationException.
Second, are multiple matches expected? If there is at most one match, the continue should be a break.
Third, one would expect the code to continue to following elements when a current element is not a match. That is, the break should be a continue, or better yet, should be removed entirely.
Fourth, its not clear that theorder.remove(orderIDSearch) will do anything, unless the collection type has a remove operation which takes a key value instead of an element value. For basic collection types (List, Set), the call won't do anything.
Here are two rewrites:
If the iterator supports remove:
Iterator<Order> orders = theorder.iterator();
boolean found = false;
while ( !found && orders.hasNext() ) {
if ( orders.next().getOrderID() == orderIDSearch ) {
found = true;
}
}
if ( found ) {
orders.remove();
System.out.println("Found and removed [ " + orderIDSearch + " ]");
} else {
System.out.println("Not found [ " + orderIDSearch + " ]");
}
If the iterator does not support remove, then:
boolean found = false;
for ( Order o : theorder ) {
if ( o.getOrderID() == orderIDSearch ) {
found = true;
break;
}
}
if ( found ) {
theorder.remove(orderIDSearch);
System.out.println("Found and removed [ " + orderIDSearch + " ]");
} else {
System.out.println("Not found [ " + orderIDSearch + " ]");
}
Note that this relies on remove accepting a key as the parameter value.
You are breaking the loop in for search in else condition.
Why would you do that.. Remove the else part
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);
}
}
HI My prof said this about my code
Please Help me I do not get what he wanted me to do with my code
// The following code (mark by "-")can be replace by getEntryDetails(AddressBookEntry entry)
// you can just pass "addent" to the method
// always try to reuse as much methods/codes as possible
Please Help me I do not get what he wanted me to do with my code
This is an address book containing 3 classes and this is one of the class that i really had a problem with
import java.util.Scanner;
public class AddressBookApp {
private static Scanner dataReader;
private static AddressBook book;
// TODO Address Book App
public static void main(String[] args) {
book = new AddressBook(10);
dataReader = new Scanner(System.in);
boolean lContinue = true;
while (lContinue) {
switch (Character.toUpperCase(menu())) {
case '1': addBookEntry(); break;
case '2': deleteEntry(); break;
case '3': viewAllEntries(); break;
case '4': editEntry(); break;
case '5': searchEntryByName(); break;
case '6': searchEntryByRecord(); break;
case 'X':
lContinue = false;
break;
default:
System.out.println("\nInvalid Menu option");
}
}
System.out.println("\nEnd of program...");
}
public static char menu() {
char choice;
System.out.println("\nAddressBook Menu");
System.out.println("1. Add Entry");
System.out.println("2. Delete Entry");
System.out.println("3. View all Entries");
System.out.println("4. Update an Entry");
System.out.println("5. Search Entry By Name");
System.out.println("6. Search Entry By Record Number");
System.out.println("X. Exit Program");
System.out.print("\nSelect Menu Option: ");
choice = dataReader.nextLine().charAt(0);
return choice;
}
public static AddressBookEntry getEntryDetails(AddressBookEntry entry) {
if( entry == null ) {
entry = new AddressBookEntry();
}
System.out.print("\nName : "); entry.setName(dataReader.nextLine());
System.out.print("Address : "); entry.setAddress(dataReader.nextLine());
System.out.print("Phone No.: "); entry.setTelNo(dataReader.nextLine());
System.out.print("Email : "); entry.setEmailAdd(dataReader.nextLine());
return entry;
}
public static void addBookEntry() {
AddressBookEntry entry = getEntryDetails(null);
if( entry != null ) {
book.addAddressBookEntry(entry);
}
}
public static void editEntry() {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number: ");
int recnumb = datainput.nextInt();
AddressBookEntry addent = new AddressBookEntry();
addent = book.findAddressBookEntryByRecordNo(recnumb);
// The following code (mark by "-")can be replace by getEntryDetails(AddressBookEntry entry)
// you can just pass "addent" to the method
// always try to reuse as much methods/codes as possible
getEntryDetails(AddressBookEntry)
- System.out.println("Name: " + addent.getName());
- System.out.println("Edit Name: ");
- String name = datainput.next();
- addent.setName(name);
- System.out.println("Edit Address: ");
- String address = datainput.next();
- addent.setAddress(address);
- System.out.println("Edit EmailAdd: ");
- String emailAdd = datainput.next();
- addent.setEmailAdd(emailAdd);
- System.out.println("Edit TelNo: ");
- String telNo = datainput.next();
- addent.setTelNo(telNo);
displayEntry(addent, recnumb);
// TODO: edit a single record entry
//System.out.println("\nUnder construction....");
}
public static void searchEntryByRecord() {
try {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number: ");
int recnumb = datainput.nextInt();
AddressBookEntry addent = new AddressBookEntry();
addent = book.findAddressBookEntryByRecordNo(recnumb);
System.out.println("Name: " + addent.getName());
System.out.println("Address:" + addent.getAddress());
} catch (Exception NullPointerException) {
// TODO Auto-generated catch block
return;
}
// TODO: search an entry using its record no.
// display "record not found" if such record does not exist.
// Display all its entry.
// Hint: use the method "findAddressBookEntryByRecordNo()"
// from the AddressBook class
//System.out.println("\nUnder construction....");
}
public static void deleteEntry() {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number to delete: ");
int recnumb = datainput.nextInt();
if (book.deleteAddressBookEntry(recnumb)) {
System.out.println("Deleted successfully.");
} else {
System.out.println("Record not found");
}
}
// TODO: delete an entry using its record no.
// display "record not found" if such record does not exist.
// Hint: use the method "deleteAddressBookEntry()"
// from the AddressBook class
// display a single record
public static void displayEntry(AddressBookEntry entry, int recNo) {
System.out.println("\nRecord No. " + recNo);
System.out.println("Name : " + entry.getName());
System.out.println("Address : " + entry.getAddress());
System.out.println("Phone No.: " + entry.getTelNo());
System.out.println("Email : " + entry.getEmailAdd());
}
// Search all entries containing name search criteria
public static void searchEntryByName() {
System.out.print("\nSearch[Name]: ");
// ensure no extraneous space and search criteria all in lowercase
String name = dataReader.nextLine().trim().toLowerCase();
// get a reference to the Addressbook list
AddressBookEntry[] list = book.getAllEntries();
for( int i = 0; i < list.length; i++ ) {
// compare search criteria with every entry
if(list[i]!=null && list[i].getName().toLowerCase().contains(name)) {
displayEntry(list[i],i+1);
}
}
System.out.println("No more records follow...");
}
public static void viewAllEntries() {
int validRecords = 0;
// get a reference to the Addressbook list
AddressBookEntry[] list = book.getAllEntries();
if( list.length == 0) {
System.out.println("\nList empty...");
}
for( int i = 0; i < list.length; i++ ) {
if( list[i] != null ) {
displayEntry(list[i],++validRecords);
}
}
System.out.println("No more entries to follow...");
}
}
Remove all lines which start with "-" and use this instead:
getEntryDetails( addent );
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
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));