I am a newbie. I know that my code is messy. I will be working on adding the comments and such.
try // get customer's address
{
System.out.println("\nPlease type in your shipping address.");
System.out.println ("This way you can receive what you have ordered.");
System.out.println ("In this format: Street, City, State, Zipcode\n");
customerAddress = input.nextLine();
}
catch (Exception e)
{
System.out.println("You need to enter in an address.");
}
try // get customer's telephone number
{
System.out.println("Please enter in your telephone number:\n");
phoneNumber = input.nextLine();
}
catch (Exception e)
{
System.out.println("You need to enter in a phone number.");
}
I am able to get an input from the phoneNumber but the program seems to skip right over the customerAddress input.
Below is what I get in the command prompt. Notice that I was able to input data under the telephone number, but did not get the chance to put it in the address section.
Please type in your shipping address.
This way you can receive what you have ordered.
In this format: Street, City, State, Zipcode
Please enter in your telephone number:
123457890
Are there any logic errors that could be causing it to skip over?
If you are reading more data, with Scaner like input.nextInt(); then it will read only one int.
One solution is that add input.nextLine(); and it should probably work.
Solution 2:
Use BufferedReader;
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
try{
System.out.println("\nPlease type in your shipping address.");
System.out.println ("This way you can receive what you have ordered.");
System.out.println ("In this format: Street, City, State, Zipcode\n");
customerAddress = bufferRead.readLine();
}catch (Exception e){
System.out.println("You need to enter in an address.");
}
try {
System.out.println("Please enter in your telephone number:\n");
phoneNumber = bufferRead.readLine();
}catch (Exception e){
System.out.println("You need to enter in a phone number.");
}
System.out.println(customerAddress + " " + phoneNumber);
See if you get the output with the BufferedReader.
Hope this helps.
Any number of other things that weren't shown in your post could be causing a stray new line to remain on the buffer. A more robust option is to loop while nextLine returns an empty string.
Related
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
assume that my text file consist this:
NOT VOTED/1/gello/18
NOT VOTED/2/tara/24
arrangements is like status if user already voted or not/voter's number/name/age i divided the information line into array so it is like this
info[0]=status/info[1]=voters number/info[2]=name/info[3]=age
here is the function of my program:
read a file
let the user enter a voters number
if voters number matches info[1], proceed to step 3
while info[0] contains "VOTED" it will get an error message that that voter's number already voted and enter another voters number. if false it will proceed to the voting process
now info[0] will changed in to "VOTED"
here is my code:
File original = new File("C:\\voters.txt");//open the original file
File temporary = new File("C:\\tempvoters.txt");//create temporary file
BufferedReader infile = new BufferedReader(new FileReader(original));//read the file
PrintWriter outfile = new PrintWriter(new PrintWriter(temporary));//write the data
vNum=JOptionPane.showInputDialog("Enter voters number: ");
String line=null;
String something="VOTED";
while((line=infile.readLine())!=null){
String [] info=line.split("/");
if(info[1].matches(vNum)){
while(info[0].matches(something)) {
JOptionPane.showMessageDialog(null, "Voter already voted or Voter not registered. Please try again");
vNum=JOptionPane.showInputDialog("Enter voters number: ");
}
President();
Vice_President();
info[0]="VOTED";
all=info[0]+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
outfile.flush();
}
else{
outfile.println(line);
outfile.flush();
}
}
infile.close();
outfile.close();
original.delete();//delete the original file
temporary.renameTo(original);//rename the temporary file to original file
now this happens in the code that i made:
assume i enter 1 as voters number. and because the info[0] still contains "NOT VOTED", it will proceed to voting process and after that the element of info[0] now contains "VOTED". now after that process it will go back to main menu. now when i go back entering another voters number again, i tried entering 1 again to see if it will appear the error message. it did. so i entered the other voter's number again which is 2 and its info[0] still contains "NOT VOTED" BUT the error message will still appear!! i am really stuck with that process and i don't know what to do with that anymore because i am really clueless what is wrong. to think the functions in this method of my program are just the same with the other methods that i had. please please please help
while(info[0].matches(something))
It looks to me as though you're not breaking out of this while loop, since info[0] will always be true since variable "something" isn't being changed. What I would suggest is this:
{
JOptionPane.showMessageDialog(null, "Voter already voted or Voter not registered. Please try again");
vNum=JOptionPane.showInputDialog("Enter voters number: ");
something = "NOT VOTED"; //This will break the loop
}
} 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.
I am trying to create a program which asks the user to guess a number which is randomly generated and the loop exits when the input is correct. I am also trying to stop user from entering an invalid data and want the loop to repeat until user enters a valid data. The problem is when is type in an alphabet as an input, the program repeats. thank you for helping in advance. I am using eclipse kepler
Output:
Try guessing the number:
k
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
You have entered invalid data. Please try again
Try guessing the number:
while(true){
try{
System.out.println("Try guessing the number: ");
guess=input.nextInt();
if(guess==sum){
System.out.println("You have guessed it correctly");
break;
}
}catch(InputMismatchException e){
System.out.println("You have entered invalid data. Please try again");
}
}
You don't have to use try/cathc structure. A while loop would be enough
while(true){
System.out.println("Try guessing the number: ");
guess=input.nextInt();
if(guess==sum){
System.out.println("You have guessed it correctly");
break;
}
if(!(guess instanceof Int)){
System.out.println("You have entered invalid data. Please try again");
}
}
This worked for me...
It fixes the while(true) issue and uses a simpler way to check for incorrect data that is easier to debug! Enjoy and good luck with your game!
String guessString="";
int guess = 0;
Scanner input = new Scanner(System.in);
int sum = 12;
//just used 12 as a placeholder, you'll have to connect your
//random number generator, as well as changing the default of
//guess=0 if 0 is in your range for the random number
while(sum!=guess){
System.out.println("Try guessing the number: ");
guessString=input.next();
try {
guess = Integer.parseInt(guessString);
} catch(Exception e) {
System.out.println("Invalid Data.");
guess=0;
}
}
System.out.println("You have guessed it correctly");
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