would you please help me on this?
I have written an class and here is the code. I have two problems.
(1) I wanted to know how to get back to the beginning of the loop after user has enter copies he wants to add instead of exiting the system. I mean after system says "copies has been added." it ask user "if you want to add a book?" and then loop start again.
(2) What should I do to add an object to the array each time loop is finished?
my problem is everytime loop is running, the book1 is being rewritten.
thank guys- solved
As discussed, this will make your loop run until the user enters yes
System.out.println("do you want to add a Book?(yes or no) ");
Scanner s=new Scanner(System.in);
String h = s.nextLine();
while (h.contains("yes")|| h.compareToIgnoreCase("YES") == 0) {
int size=list.size();
//your code here
System.out.println("do you want to add a Book?(yes or no) ");
h = s.nextLine();
}
Replace for (int m=0;m<10;m++) with a do-while loop
Declare Book book1=new Book(); at the top instead of inside the loop
Branching statements would help. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Ok to restart the loop there is a keyword continue
Related
to summarise it give me any idea or solution on how I could fix it.
I tried what is given in the code below.
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end =="Y")
System.out.println("hello");
I expect the output hello in the above code, but the actual results are nothing the program just ends.
First of all, I have no idea what your question is about exactly. I can't see any information on which programming language you are using (I suppose Java) or on which operating system you are working.
But I've got an idea what the problem might be: As you are using stdout, I suppose the program happens on a Console or Terminal. And in some environments, the cmd window will close after there program terminated (when working with an IDE like VS Community, which I don't know if you do or not, given no context). If this is the case, "hello" will be printed but you won't see it because the window closes immediately. Try to add some kind of getline at the end and try again.
Supposing sc is a Scanner object.
String comparison must be done with the equal method instead of using == because by doing that you'll compare the object's referer in the memory instead of the String content, try this:
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end.equals("Y")) {
System.out.println("hello");
}
In my program I need to take an input from a user, but it must be an integer. If the user doesn't input an integer, I need the program to reprompt them to enter an integer, and keep doing so until they enter one. I found an example while loop code snippet online which works perfectly, but I am having problems understanding why and how it works, and I'd really like to understand better:
Scanner reader = new Scanner(System.in);
int guess=0;
System.out.println("Guess the number");
while (!reader.hasNextInt()) { //I get that this is a "not have" boolean
System.out.println("That's not a number. Please enter a valid number");
reader.next();
}
guess= reader.nextInt();
System.out.println(guess);
My questions are:
Does the !hasNext condition in the while loop actually trigger the scanner object to ask the user for input and then check that input, or does it only check anything that has already been inputted?
Why is it necessary to have the reader.next(); line after the while loop's main statement and what is this doing exactly? I know it's necessary as the program doesn't work when I take it out. But is it prompting for input? If yes what happens to this input?
When guess= reader.nextInt(); runs, why doesn't it re-prompt the user for input at this point?
Sorry that these are probably really basic questions, I'm new to coding and Java and just can't get my head around what's happening internally in this particular example, though have no problem doing other basic stuff with the Scanner.
It's not particularly intuitive, for sure, so don't feel bad for not getting it immediately.
It seems to me that the problem you're having with your understanding is that that methods such as nextInt may or may not prompt for user input, depending if anything is already in the Scanner.
Here's the sequence of events:
All your code executes until you hit !reader.hasNextInt(). There's no input so it "blocks" (waits) until there is some input from the user.
If the user enters 'A', that's not an integer so we enter the body of the while loop. We then print the error message.
Now, hasNextInt doesn't "consume" (process) the user input when it's checking whether or not it's an integer, so we still have that invalid user input of 'A' sitting in our scanner. We call reader.next() to effectively discard that value.
Now we're back to !reader.hasNextInt(). The scanner is empty once again, so we prompt for user input. If they enter another non-integer, that process will simply keep repeating.
Say this time we do have a valid user input - they've entered the number 2. This passes the check so our while loop ends and we continue along.
We've now got some input in our scanner, but we've not consumed it. We're sure it's an integer because of the while loop condition. We can now consume the input with reader.nextInt() and assign it to our variable.
hasNextInt() only checks whether the next input is an integer. It won't consume any input at all. The ! is just negate theu outcome of this function.
As hasNextInt() won't consume, then we need to use next() to consumeo the user input to let hasNextInt() to check with user's next input value. As you won't need it at all, then no need to assign it to any variables.
Scanner won't display the prompt at all. The prompt is printed by System.out.println().
For the line nextInt(), it is used to consume the next user input. Since hasNextInt() must be true when it execute this line, there must be one integer input waiting for consumption, so this method can return immediately with that user input.
Try it :)
public static void main(String[] args) {
int option;
if(args!=null&&args.length>0){
option = Integer.parseInt(args[0]);
}
else{
System.out.println("Enter:\n 1 to run x \n 2 to run y \n");
Scanner keyboard = new Scanner(System.in);
option = keyboard.nextInt();
}
switch (option) {
case 1:
xx
break;
case 2:
yy
break;
default:
break;
}
}
For a university assignment, from the console I need to be able to read in multiple lines until the user enters Ctrl+Z. That I have no issue with, my problem lies with me being unable to read anything in from System.in after that because it always throws a NoSuchElementException.
The following is the code that I am using for reading in the multiple lines, it was provided by the instructor and so I don't want to change it.
System.out.println("To terminate input, type the correct end-of-file indicator ");
System.out.println("when you are prompted to enter input.");
System.out.println("On UNIX/Linux/Mac OS X type <ctrl> d");
System.out.println("On Windows type <ctrl> z");
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
//Processes input
addFileIntoDirectory(input.nextLine());
}
I understand that this is caused by the Ctrl+Z which equates to an EOF marker, but I don't know how to move past it. No matter how many reads after it I do, regardless of if I have typed more to the console, I just instantly get back another NoSuchElementException.
I have tried having a separate scanner for the menu, closing the scanner above and opening a new one for the menu but neither works.
Is there a way to flush/purge System.in or to reset it?
Please let me know if you would like more details. I have kept the rest of the program vague as it is homework.
EDIT 1: Assignment says "The system provides a textual selection menu as follows, and
runs in loop." Which means the program is not to terminate on Ctrl+Z.
add files from user inputs
display the whole directory
display the size of directory
exit
Please give a selection [0-4]:
The short answer is:
if (!input.hasNext())
input = new Scanner(System.in);
The long answer is:
Below is code, with comments made for removing later, to demonstrate the problem as I understand it and solution.
Note this demo is intended to only work with integer and ^Z inputs.
Copy out the code and save into file HN.java to compile.
Run the program and it will prompt One. Enter integers to your heart's content and exit the loop by entering ^Z.
Two will be displayed followed by the NoSuchElementFound exception in the question. This is because the ^Z remains in the Scanner object input and thereby fails on the nextInt() method.
The first inclination might be to use hasNext() to account for this. So go ahead and uncomment /*Comment1 and recompile and run again.
Now you avoid the exception, but the program blazes through to the end, skipping over the nextInt() originally intended.
So now, uncomment /*Comment2, recompile, and run again. Now the program will wait at the Two prompt as intended. If you enter an integer here, you will proceed to the Three prompt for another entry.
However, if you enter ^Z at Two, again, the program skips the next input. To correct this, uncomment /*Comment3, recompile, and run, and you will see the program works for all combos of integers and ^Z at the various inputs.
Now, you might be wondering why I didn't just reuse the !input.hasNext() solution in /*Comment3. Here's a demo why:
Put back the /*Comment3 and uncomment the /*Comment4, compile and run again. The program works fine and dandy with a ^Z input at the Two prompt, but if you enter an integer there, you'll see the system waiting for input, but there is no prompt Three!
This is because the integer you entered was used in the preceding nextInt() so when the program gets to the hasNext(), it stops and waits for input.
The lesson here is you use the !input.hasNext() when you KNOW you have a ^Z in queue such as when it was used to escape the while loop in this program and the original poster's question. Otherwise the else structure is better suited.
hasNext() is confusing to work with. You have to keep in mind that if nothing is in queue the program will stop and wait for input at that point. This may mess up your prompting if you're not careful.
import java.util.Scanner;
public class HN
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int temp = 0;
System.out.println("One");
while (input.hasNext())
{
temp = input.nextInt();
}
System.out.println("Two");
/*Comment2
if(!input.hasNext()) input = new Scanner(System.in);
Comment2*/
/*Comment1
if (input.hasNext())
Comment1*/
{
temp = input.nextInt();
System.out.printf("%d\n", temp);
}
/*Comment3
else input = new Scanner(System.in);
Comment3*/
/*Comment4
if(!input.hasNext()) input = new Scanner(System.in);
Comment4*/
System.out.println("Three");
if (input.hasNext())
{
temp = input.nextInt();
System.out.printf("%d\n", temp);
}
System.out.println("Four");
}
}
So basically this code is supposed to keep asking "Please insert a valid number" until an integer is introduced through the keyboard. It works just fine, I'm just curious as to how it actually does what it does.
Scanner input = new Scanner(System.in);
System.out.println("Please insert the number of lives.");
while (!input.hasNextInt()) {
input.next();
System.out.println("Please insert a valid number.");
}
numberOfLives = input.nextInt();
In my head it would make more sense to put the numberOfLives = input.nextInt(); line inside of the while loop. This is basically what I'm understanding from this snippet once it reaches the while loop:
Check condition in while, if input scanner variable doesn't have an int value, do the following
Discard what is in the input scanner variable
Print out the valid number message
Obviously this isn't how it goes, else this snippet wouldn't work. I'm thinking maybe each time it checks the condition, the actual !input.hasNextInt() opens up the buffer again for input and THEN checks what's inside, but I have no clue.
Sorry if I'm not using the terms correctly, pretty now to all of this stuff.
Thanks!
Like an iterator, scanner will always point to the element before the stream starts. i.e. if the list starts with position 0, scanner will point to -1st position. next() will advance the scanner and return the element present at location.
In this code, we are checking if the next element is integer. If it is not, why to advance the scanner?
am having trouble trying to validate a user response to exit my app or try again(its a simple game)? when the game finishes I ask the user if they want to continue type "y" for yes or "n" for no to exit. How can I validate their response so if its neither y or n I show an error message and ask them to type it again???
This doesn't seem to worK for me???
if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
System.out.println("Error enter y for yes and n for no");
System.out.println("Would you like to play again (y/n):");
choice = sc.next();
Just change the
if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
to
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
This will continue to ask them for another letter each time they don't choose the letter 'n' or 'y'.
EDIT: Also, you might want brackets around the code within the if (soon to be while) statement.
Without any full context, difficult to give a relevant answer.
But you can already test your code with curly braces around the if statement:
if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
System.out.println("Error enter y for yes and n for no");
System.out.println("Would you like to play again (y/n):");
choice = sc.next();
}
Indeed, with your current code, only the first line:
System.out.println("Error enter y for yes and n for no");
is taken in account by your condition.