Code works in Netbeans, but not TextPad? - java

Here is the code throwing the error. In TextPad, I get a NullPointerException when I try to write the contents of the array to the text file. (It doesn't see anything in the array.) Note: it works perfectly in Netbeans. I only get this in Textpad. I have scoured Google and i have no idea why it is doing this.
void enterContact(){
// test contact
contactName = nameField.getText();
if (contactName == null || contactName.equals(""))
{
JOptionPane.showMessageDialog(null, "Please enter a name.");
return;
}
//test age betweeen 0 and 120
contactAge = ageField.getText();
try{
Integer.parseInt(contactAge);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Please enter a valid age.");
}
finally{
if (Integer.parseInt(contactAge) <= 0 || Integer.parseInt(contactAge) >= 121){
JOptionPane.showMessageDialog(null, "Please enter a valid age.");
return;
}
}
// test email
contactEmail = emailField.getText();
if ( contactEmail == null || contactEmail.equals(""))
{
JOptionPane.showMessageDialog(null, "Please Enter an Email Address.");
return;
}
//test cell number
contactPhone = phoneField.getText();
try
{
Integer.parseInt(contactPhone);
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, "Please Enter a valid Phone Number.");
return;
}
String columns2[] = { contactName, contactAge, contactEmail, contactPhone };
//write data to file
try{
for (int i = 0; i < columns2.length; i++){
fw.write(columns2[i].toString() + ", ");
}
fw.write("\r\n");
fw.flush();
fw.close();

If you get NullPointerException during writing in file, there is two possibilities:
You may not open the file. For example because of forgetting calling the constructor of FileWriter.
You don't have any permission to open the file and write into it.
If you got the exception only when you are run it using TextPad, I think the second problems occurred. You don't have permission.

Try To run your TextPad in Administrator Mode
Right Click on Textpad icon -> Run as administrator
& then RUN above program
i sure your program get executed properly.

Related

How to create custom exception for just Integers

I want to create a class that will serve me as an exception. I will give you two examples of how I tried. I've been looking for it but I can't find an example of how to put this into practice, or it doesn't work for me.
This is my method where user choose flight by ID, I want to throw an exception if a program user enters a String.
Code:
#Override
public void choosePassenger(ArrayList<Passenger> passengerList) {
System.out.println("Choose passenger by ID: ");
try {
int pickedPassenger = scanner.nextInt();
for (Passenger tempUser : passengerList) {
if (pickedPassenger == tempUser.getId()) {
System.out.println("You picked passenger: " + tempUser.getFirstName() + ", "
+ tempUser.getLastName() + ". Balance is: " + tempUser.getBalance());
selectedPassenger = tempUser;
break;
}
}
} catch (InputMismatchException e) {
System.out.println("Wrong input! Try again");
scanner.nextLine();
}
}
I tried on that way but after program show me message Wrong input! Try again it goes to another method not giving me chance to enter valid input
Also, how I can create exception here for just Strings?
System.out.print("Add name of passenger: ");
passenger.setFirstName(scanner.nextLine());
This is part of code that enable program user to create new user, he is adding here name, I want to create exception so if program user add integer for name I want to show him an exception
EDIT:
If I delete scanner.nextLine(); program stops but first print me my own exception message then print me message from next method and then InputMissMatchException for that method on his own because I input string instead of integer
If you want the user to try again, you can keep them in an infinite loop that breaks after correct input.
Editing as per #DevilsHnd observation. You cannot use scanner.nextInt() in this manner as it will read without user being prompted for input and it results in being stuck in an infinite loop.
You can then use nextLine() and validate the input is a number like this:
while(true) {
try {
int pickedPassenger = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Wrong input! Try again");
}
}
For restricting input to a non numeral value as you want for the name, you would have to check if the value entered is a number (there is no scanner method to restrict reading to non numeral values)
Most elegant way in my opinion is to use an external library that has this like Apache Commons:
while(true) {
String firstName = scanner.nextLine();
if (!NumberUtils.isCreatable(firstName )) {
passenger.setFirstName(firstName );
break;
} else {
System.out.println("Value cannot be a number!");
}
}
However, if you cannot import external libraries, simplest way to do this is by using built in Java Integer.parseInt() function(although you might want to consider regex - see link below):
while(true) {
String firstName = scanner.nextLine();
try {
Integer.parseInt(firstName);
System.out.println("Value cannot be a number!");
} catch (NumberFormatException e) {
passenger.setFirstName();
break;
}
}
For more options on checking if a value is a number (like regex) check this:
https://www.baeldung.com/java-check-string-number

why console.readpassword does not work in Eclipse?

I am trying to get the input from the from the user (hidden)
and trying to print that password, but the console is null and getting NullPointerException.
Is readPassword() supported in java? What is the substitute for this?
Console cons;
if((cons = System.console()) != null) {
char[] password = null;
try {
System.out.println("Enter the password :");
password=cons.readPassword();
System.out.println("Your password is" + new String(password));
} finally {
if(password != null) {
java.util.Arrays.fill(password,' ');
}
}
} else {
throw new RuntimeException("can't get password...No console");
}
The problem is that there is an open bug in Eclipse that leads to System.console being NULL. Related question:
How to read password from console without using System.console()?
Still open bug: https://bugs.eclipse.org/bugs/show_bug.cgi?id=122429
Also see the duplicates of that bug.

Validating input and preventing try/catch from exiting

I'm new to java but I've experimented a lot with this particular program and I've hit a wall. The purpose of this program is to catch if the user inputs a value exceeding the variable limit and also to validate that the input satisfies my specified range.
If the input exceeds the variable limit without a while loop, the program exits.
If the input exceeds the variable limit with a while loop, it loops infinitely.
I've tried using a while loop and my three outcomes are this:
The user inputs a programmer-specified valid number and all is well.
The user inputs a number above 100 and is prompted to try again...
The user exceeds the variable limit and the program goes into an
infinite loop.
If I put an escape in the catch block, it does the same as if the while was not there. I want the program to print the error but allow the user to retry a value.
while(!success){
try{
sh = sc.nextShort();
while(sh < 1 || sh > 100){
System.out.print("You must enter a value between 1-100: ");
sh = sc.nextShort();
} //close try
System.out.println("Great job!");
success = true; //escape the while
}catch{Exception ex){
System.out.println("ERROR: " + ex);
success = false; //causes infinite loop... I understand
} //close catch
} //close while
The problem is, that Scanner stores the whole input string and processes it.
When your input is not a short value but a string it throws an exception. You log the exception in the catch and in the next circle it tries to read a short value from the same stored string, which throws exception again .... -> infinite loop.
If you create a new Scanner in the catch, it will read again from the console:
while (!success) {
try {
sh = sc.nextShort();
while (sh < 1 || sh > 100) {
System.out.print("You must enter a value between 1-100: ");
sh = sc.nextShort();
} //close try
System.out.println("Great job!");
success = true; //escape the while
} catch (Exception ex) {
System.out.println("ERROR: " + ex);
sc = new Scanner(System.in);
} //close catch
}
As i understand your problem , you are facing a loop of exception on passing a bigger value (something bigger like e.g "10000000000").
you have the exceptions coming as below in infinite loop:
ERROR: java.util.InputMismatchException: For input string: "10000000000"
ERROR: java.util.InputMismatchException: For input string: "10000000000"
But you want program to print a exception line and then allow user to input again.
You can do that by below a way of reading bad input (String bad_input = sc.next();) from the scanner you used.
while (!success) {
try {
sh = sc.nextShort();
while (sh < 1 || sh > 100) {
System.out.print("You must enter a value between 1-100: ");
sh = sc.nextShort();
} // close try
System.out.println("Great job!");
success = true; // escape the while
} catch (Exception ex) {
System.out.println("ERROR: " + ex);
success = false; // causes infinite loop... I understand
String bad_input = sc.next();// your bad input to allow read that exception
} // close catch
} // close while
The cause of this problem can be found here:
If the translation is successful, the scanner advances past the input
that matched
If I understand your question correctly, you can get rid of your second while loop and replace it with an if. Then you can print out the value must be 1-100 and throw and exception to cause your program to go through the catch statement and print out the error you threw.
while(!success){
try{
sh = sc.nextShort();
if(sh < 1 || sh > 100){
System.out.print("You must enter a value between 1-100");
throw Exception;
} //close try
System.out.println("Great job!");
success = true; //escape the while
}catch{Exception ex){
System.out.println("ERROR: " + ex);
success = false; //causes infinite loop... I understand
} //close catch
} //close while

Return to previous spot in loop after try catch?

} else if (selectionKey == 2) {
System.out.println("Please enter the item name");
if (s.nextLine() != "") {
item = s.nextLine();
}
try {
ZybezChecker zb = new ZybezChecker(item);
zb.getAveragePrice();
System.out.println(zb.toString());
} catch(Exception e) {
System.out.println("Something went wrong. Perhaps an invalid item name?");
}
That's my code atm. How do I return back to the if statement and continue the loop after it catches?
You could embed it in a loop like,
for (;;) { // <-- start an infinite loop
System.out.println("Please enter the item name");
if (s.nextLine() != "") {
item = s.nextLine();
}
try {
ZybezChecker zb = new ZybezChecker(item);
zb.getAveragePrice();
System.out.println(zb.toString());
break; // <-- terminate the infinite loop.
} catch(Exception e) {
System.out.println("Something went wrong. Perhaps an "
+ "invalid item name?");
e.printStackTrace(); // <-- tell them what went wrong.
}
}
I think (if I understand your question and code correctly) that what you want is a loop containing the s.nextLine(). Note that I am assuming several things here:
s is a Scanner or something equivalent that reads input from the user
an exception is thrown if the user enters invalid input
you want to keep asking the user for input until they enter something valid
If this is the case, then you should create a loop like this:
while (true) {
System.out.println("Please enter the item name");
if (s.nextLine() != "") {
item = s.nextLine();
}
try {
ZybezChecker zb = new ZybezChecker(item);
zb.getAveragePrice();
System.out.println(zb.toString());
break;
} catch(Exception e) {
System.out.println("Something went wrong. Perhaps an invalid item name?");
}
}
Also, why are you calling nextLine() twice? When you call it the first time, it will read a line from the scanner. When you call it again, it will not return the same line; it will instead wait for a new line. This means the user has to enter some random string, then enter the actual value. Finally, you should NEVER use == or != on Strings. Since they are reference types, you are essentially checking if they occupy the same location in memory, rather than if they are equal. Use s.nextLine().equals("") instead.

How to show an error when wrong input is given

I wrote this code for hiding and unhiding any files or folders but how to show an error when user gives wrong input, I tried using else if but with wrong logic code, I want to show error when ever user gives wrong input while selecting to hide or unhide and if user gives wrong path to hide or unhide files.
import java.io.*;
class k
{
public static void main(String args[])
{
String a,h;
boolean q=true;
while(q==true){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nunhide/hide/exit (u/h/e): ");
h=br.readLine();
if("hide".equalsIgnoreCase(h)){
System.out.print("\nwhat you want 2 hide: ");
a=br.readLine();
if(a.equals(a)){
Runtime r=Runtime.getRuntime();
Process p=r.exec("cmd.exe /c attrib +h "+a);
System.out.print("HIDDEN SUCCESSFULLY");
}
//else if(!a.equals(a)){System.out.print("error");}
}else if("unhide".equalsIgnoreCase(h)){
System.out.print("what u want to unhide: ");
a=br.readLine();
if(a.equals(a)){
Runtime r=Runtime.getRuntime();
Process p=r.exec("cmd.exe /c attrib -h "+a);
}
System.out.print("UNHIDDEN SUCCESSFULLY");
}
else if("exit".equalsIgnoreCase(h)){
System.exit(1);
}
}catch(Exception e){
System.out.println(e);
}
}
}
}
First: You make the user choose from 3 letters (h, u, e),
so you need to sure that the user enter "h" not "hide" , so your check need to be
if ("h".equalsIgnoreCase(h)) //h not hide {
.....
}
second : Its easy to check if the path you entered is exist or not , so if it's wrong you can know that , like this :
if (new File(a).exists()) {
Process p = r.exec("cmd.exe /c attrib +h " + a);
System.out.print("HIDDEN SUCCESSFULLY " + p);
} else {
System.out.println("wrong input");
}
Validating option selection
You're 90% of the way there with the first error message, remember if you have a series of if{} else if{} else if {}else{} then anything that doesn't fit in the ifs will end up in the else. So
if("hide".equalsIgnoreCase(h)){
System.out.print("\nwhat you want 2 hide: ");
a=br.readLine();
if(a.equals(a)){ //<-----a.equals(a) is not valid validation!
Runtime r=Runtime.getRuntime();
Process p=r.exec("cmd.exe /c attrib +h "+a);
System.out.print("HIDDEN SUCCESSFULLY");
}else{
System.out.println("Invalid Input");
}
}
}else if("unhide".equalsIgnoreCase(h)){
System.out.print("what u want to unhide: ");
a=br.readLine();
if(a.equals(a)){
Runtime r=Runtime.getRuntime();
Process p=r.exec("cmd.exe /c attrib -h "+a);
}
System.out.print("UNHIDDEN SUCCESSFULLY");
}else if("exit".equalsIgnoreCase(h)){
System.exit(1);
}else{
System.out.println("Invalid Input");
}
This will give an error message on entering a non valid option, but your existing validation of the file name is not correct so an error message for that cannot be generated without a definition of "incorrect".
Path validation
I'm guessing invalid is anything that triggers that catch block so move the try catch inside the loop and use it to validate the input;
if("hide".equalsIgnoreCase(h)){
System.out.print("\nwhat you want 2 hide: ");
a=br.readLine();
try{
Runtime r=Runtime.getRuntime();
Process p=r.exec("cmd.exe /c attrib +h "+a);
System.out.print("HIDDEN SUCCESSFULLY");
}catch(Exception e){
System.out.print("Invalid path");
}
}
Other points
As discussed in the comments if(a.equals(a)) will always be false. Whatever a is, it intrinsically is itself

Categories

Resources