This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I am a beginner in Java, I have written a simple input java program. I am giving the user the option to repeat the program with a do while, however it's not properly functioning. Can someone point my mistake please?
public static void main(String args[]){
char repeat = 0;
Scanner input = new Scanner(System.in);
do{
String word = null;
boolean oneWord = false;
while(!oneWord){
System.out.println("Please enter a word: ");
try{
word = input.nextLine().toLowerCase();
word= word.trim();
int words = word.isEmpty() ? 0 : word.split("\\s+").length;
if(words==1 && word.length()>1 && word.length()<100){
System.out.println("Success");
oneWord = true;
System.out.println("Continue(Y/N)");
repeat = input.next().charAt(0);
}else{
System.out.println("Failure.");
}
} catch (Exception e) {
System.out.println("Exception occurred");
}
}
}while(repeat=='Y'|| repeat=='y');
input.close();
}
I would suggest you using nextLine() function of Scanner class instead of next() function.
See the difference here
Even tho its a duplicate, have a look at the line
repeat = input.next().charAt(0);
and change it to
repeat = input.nextLine().charAt(0);
This will solve your problem. For further information regarding the problem, read the duplicate link.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I've got a problem with looping a scanner, wich should return EVERY string given as an input unless String != "end". Here is what I've done so far
private static String fetchString() {
Scanner scanner = new Scanner(System.in);
String stringElement = "";
System.out.println("Write a string");
while(scanner.hasNextLine()) {
stringElement = scanner.next();
if(stringElement == "end") {
break;
}
}
return stringElement;
}
result:
Write a string
abc
abc
abc
end
end
Loop, somehow, doesn't understand if(stringElement == "end"), it still wants new word. I can't get it. Where am I making a mistake?
First change, stringElement = scanner.next(); to stringElement = scanner.nextLine();, second change if(stringElement == "end") to if(stringElement.equals("end"))
This question already has answers here:
How to use .nextInt() and hasNextInt() in a while loop
(3 answers)
Closed 6 years ago.
I have this code that I want to run to solve a problem which needs a three user inputs, and I used Scanner class for this:
public static void main(String[] args) {
int M = 0;
int A = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml:");
M = input.nextInt();
System.out.println("Please, insert the set of experiments (3 integers per line, stop by 0 0 0):");
try {
while (input.hasNextInt()) {
System.out.print(input.hasNext());
int i = input.nextInt();
A += i;
System.out.println(A);
}
} catch (Exception x) {
System.out.print(x.getMessage());
}
System.out.println("Loop ended");
}
The strange thing is that input.hasNextInt() gets stuck or something after I Insert the three values, It seem that it keeps looping or something even though there are no inputs in the console, can some one provide some help for me?
That's because input.hasNextInt() waits until a integer value is available. It would return false if an alphanumeric value was informed.
You have to define another way to break while loop, maybe with a counter or, like your message says, checking whether 3 values are equal to 0.
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
The following Java method is suppose to accept a string (name of a person) from the user via keyboard, search that name in an array called name[] and delete that person's name from the array (by assigning name[i] = "INVALID").
The code tries to accept the input string (the name of the person) using a Scanner class object del_name, but I am getting a NoSuchElementException in the statement
s=del_name.next();
i.e the 4th statement from the top.
I will be really grateful if someone can give a solution and also explain as to why this code is not working. (Thank You)
void Deletee()
{
Scanner del_name=new Scanner(System.in);
String s;
System.out.println("Enter the name to be deleted");
s=del_name.next(); // causing NoSuchElementException
int i=0;
/* find position in which the name occurs using while-loop below */
while(!s.equalsIgnoreCase(name[i]) && i<count)
i++ ; // increment i to search in next array index
if(i<count)
{
name[i]="INVALID";
count--;
System.out.println("Deletion Successful");
}
else
{
System.out.println("No such person exist");
}
del_name.close();
}
Change .next() to .nextLine().
Scanner del_name=new Scanner(System.in);
String s;
System.out.println("Enter the name to be deleted");
s=del_name.nextLine();
Scanner.next() returns whatever the current input is, even if there is none (giving you your error).
Scanner.nextLine() skips past the current line, and returns the skipped portion.
Try with,
del_name.nextLine()
Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns the input that was skipped.
The code that you posted does not throw an exception as-is. You might have done something prior to this method call that caused this. As proof, run this code:
public class Test {
static String[] name = new String[] {"AAA", "BBB", "CCC"};
static void deletee() {
Scanner delName = new Scanner(System.in);
System.out.println("Enter the name to be deleted");
String s = delName.next();
boolean found = false;
for (int i = 0; i < name.length; i++) {
if (name[i].equalsIgnoreCase(s)) {
name[i] = "INVALID";
System.out.println("Deletion Successful");
found = true;
break;
}
}
if (!found)
System.out.println("No such person exist");
delName.close();
}
public static void main(String[] args) {
deletee();
for (int i = 0; i < name.length; i++)
System.out.print(name[i] + ", ");
}
}
Notes:
Method names should start with lower case.
Non-final variables should not use underscores, just uppercases where a new word begins.
I rewrote the searching mechanism for something more intuitive, although there are many more ways to do this.
Good job on closing the scanner.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 9 years ago.
For a console menu in Java, I sometimes want to read integers and some strings. I have these two functions:
To get a String:
public String enterString(String question) {
System.out.println(question);
return scanner.nextLine();
}
To get an int (for a switch statement later):
public int choose(int b, String question) {
Boolean chosen = false;
while(!chosen) {
chosen = true;
System.out.println(question);
int choice = scanner.nextInt();
if(choice >= 0 && choice <= b) {
return choice;
}
else {
chosen = false;
System.out.println("Not a valid choice.");
}
}
return 0; //the compiler complains otherwise
}
However, if I use enterString() first and then choose() and then enterString(), it seems to use the newline from choose. Entering scanner.nextLine() at various places (start and end of each function) always caused problems.
How can I make any combination of the two work?
nextInt() is not going to consume the EOL. So, either scan for Int as
int choice = Integer.parseInt(scanner.nextLine());
or, consume the extra new line
int choice = scanner.nextInt();
scanner.nextLine(); // Skip
scanner.nextInt() does not consume the line-end.
You could wrap the nextLine in a while loop and ask for input again if the line is empty.
This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
I am writing a simple java console game. I use the scanner to read the input from the console. I am trying to verify that it I ask for an integer, I don't get an error if a letter is entered. I tried this:
boolean validResponce = false;
int choice = 0;
while (!validResponce)
{
try
{
choice = stdin.nextInt();
validResponce = true;
}
catch (java.util.InputMismatchException ex)
{
System.out.println("I did not understand what you said. Try again: ");
}
}
but it seems to create an infinite loop, just printing out the catch block. What am I doing wrong.
And yes, I am new to Java
nextInt() won't discard the mismatched output; the program will try to read it over and over again, failing each time. Use the hasNextInt() method to determine whether there's an int available to be read before calling nextInt().
Make sure that when you find something in the InputStream other than an integer you clear it with nextLine() because hasNextInt() also doesn't discard input, it just tests the next token in the input stream.
Try using
boolean isInValidResponse = true;
//then
while(isInValidResponse){
//makes more sense and is less confusing
try{
//let user know you are now asking for a number, don't just leave empty console
System.out.println("Please enter a number: ");
String lineEntered = stdin.nextLine(); //as suggested in accepted answer, it will allow you to exit console waiting for more integers from user
//test if user entered a number in that line
int number=Integer.parseInt(lineEntered);
System.out.println("You entered a number: "+number);
isInValidResponse = false;
}
//it tries to read integer from input, the exceptions should be either NumberFormatException, IOException or just Exception
catch (Exception e){
System.out.println("I did not understand what you said. Try again: ");
}
}
Because of common topic of avoiding negative conditionals https://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/