and while trying to make this simple program, im having trouble getting user input in terms of the string. When entering the integer, im having no problems, but when my program asks the user to enter another a character, the cursur will blink waiting for me to type in something, but it wont let me. If i comment out all of the integer stuff, i am then allowed to enter a string. Is there a reason i cant input both? thank you
import java.util.Scanner;
public class math {
public static void main(String args[]){
int int1,int2,int3;
String operator;
Scanner ahmad=new Scanner(System.in);
System.out.print("Enter three integers: ");
int1=ahmad.nextInt();
int2=ahmad.nextInt();
int3=ahmad.nextInt();
System.out.print("Enter a (for average), s (for sum) or p (for product):");
operator=ahmad.nextLine();
System.out.println("Thank you");
}
}
nextInt() only consumes the integer, it doesn't consume the whitespace characters (EOL in this case). Use two nextLine(), one to consume the EOL character, one to prompt you for input.
System.out.print("Enter a (for average), s (for sum) or p (for product):");
operator=ahmad.nextLine();
operator=ahmad.nextLine();
System.out.println("Thank you");
Related
So I have this exercise:
"Create a program that reads characters from the keyboard until it receives a dot.
The program must count the number of spaces.
Indicate the total number of spaces at the end of the program."
My problem is, everytime I type a character, I have to press "Enter", for it to register. This way it acknoledges the dot, but not the spaces, and it's also not practical, the point is to type the whole sentence, and ackowlegde the dot, and proceed with the rest of the code.
If I type the whole sentence (ex.: "I ate food."), it does not acknowledge the dot, and lets me keep writing.
This link: Java Scanner: stop reading after the first entry, suggests reading character by character, which is a thing I don't want.
This link: Java Scanner stop reading input if receives bad character, this one did not help me either.
package m1_praticas;
import java.util.Scanner;
public class M1_Pratica3_ContarEspacos {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char input;
String sentence = "";
//int white_spaces = 0;
System.out.println("Escreva uma frase:");
do{
input = scanner.next().charAt(0);
sentence += input;
} while(input != '.');
//for(char c : sentence.toCharArray()){
//if(c == ' '){
//white_spaces++;
//}
//}
System.out.println(sentence);
System.out.println(white_spaces);
}
}
In short, what I want, is when the user is typing a sentence, there is someking of method that is reading the sentence charater, by character.
Once that method meets the dot, it performs the rest of the code. Is that possible, or do I always have to hit "enter", to register a key?
Thanks in advance.
I am having trouble understanding how memory buffer works when I am working with Scanner class methods such as hasNextInt() hasNextDouble() etc. Considering the following code,
Scanner in = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive integer: ");
while (!in.hasNextInt()) {
System.out.println("It's not an integer!");
in.next();
}
number = in.nextInt();
} while (number <= 0);
System.out.println("Your number is " + number);
The output for some random values:
Enter a positive integer: five
It's not an integer!
-1
Enter a positive integer: 45
Your number is 45
What actually happens here? At line 1 when I enter five the nested while loop runs. What is the job of in.next()? After I enter five it says It's not an integer! But why doesn't it ask again: Enter a positive integer: ? Basically, I want the corresponding output to be like this:
Enter a positive integer: five
It's not an integer!
Enter a positive integer: -1
It's not a positive integer!
Enter a positive integer: 45
Your number is 45.
I would appreciate a brief and intuitive explanation how white spaces, line breaks are handled in input validation? And what is memory buffer? And how different methods of Scanner class like next(), nextLine(), nextInt(), nextDouble() etc. operate?
Also, how do I avoid repetition of It's not an integer!
Enter a positive number: five
It's not an integer!
one two three
It's not an integer!
It's not an integer!
It's not an integer!
10
Your number is 10
And finally, why many recommend try catch?
To start with, 0, -1, -66, 2352, +66, are all Integer values so you can't very well decide to designate them as otherwise. Your validation response should really be:
System.out.println("It's not a positive integer value!");
I personally never use those nextInt(), nextDouble(), etc methods unless I want blind validation. I just stick with a single loop, and utilize the nextLine() method along with the String#matches() method (with a small Regular Expression). I also don't really care for using a try/catch to solve a situation where I don't have to.
Scanner in = new Scanner(System.in);
int number = 0;
while (number < 1) {
System.out.print("Enter a positive integer (q to quit): ");
String str = in.nextLine();
if (!str.equals("") && String.valueOf(str.charAt(0)).equalsIgnoreCase("q")) {
System.exit(0);
}
// If a string representation of a positive Integer value
// is supplied (even if it's prefixed with the '+' character)
// then convert it to Integer.
if (str.matches("\\+?\\d+") && !str.equals("0")) {
number = Integer.parseInt(str);
}
// Otherwise...
else {
System.err.println(str + " is not considered a 'positive' integer value!");
}
}
System.out.println("Your number is " + number);
In this particular use-case, I actually find this more versatile but then, perhaps that's just me. It doesn't matter what is entered, you will always get a response of one form or another and, you have a quit option as well. To quit either the word quit or the letter q (in any letter case) can be supplied.
People like to utilize the try/catch in case a NumberFormatException is thrown by nextInt() because a white-space or any character other than a digit is supplied. This then allows the opportunity of displaying a message to console that an invalid input was supplied.
Because the Scanner class is passed System.in within its' constructor (in is an object of InputStream) it is a Stream mechanism and therefore contains a input (holding) buffer. When anything is typed to the Console Window it is place within the input buffer until the buffer is read by any one of the next...() methods.
Not all Scanner class methods like next(), nextInt(), nextDouble(), etc, completely utilize everything contained within the stream input buffer, for example, these methods do not consume whitespaces, tabs, and any newline characters when the ENTER key is hit. The nextLine() method however does consume everything within the input buffer.
This is exactly why when you have a prompt for a User to supply an Integer value (age) and you use the nextInt() method to get that data and then directly afterwords you prompt for a string like the User's name using the nextLine() method, you will notice that the nextLine() prompt is skipped over. This is because there is still a newline character within the input buffer that wasn't consumed by the nextInt() method and now forces the nextLine() method to consume it. That ENTER that was done in the previous nextInt() method is now passed into the nextLine() method thus giving the impression that the prompt was bypassed when in reality, it did receive a newline character (which in most cases is pretty much useless).
To overcome this particular situation the easiest thing to do is to consume the ENTER key newline character by adding scanner.nextLine(); directly after a int myVar = scanner.nextInt(); call. This then empties the input buffer before the String name = scanner.nextLine(); comes into play.
Ive written a small Java code to calculate the product of two integers input by the user using Scanner. The user is forced to input integer values. The code is shown below.
import java.util.Scanner;
public class Principal {
public static void main(String[] args) {
int x=0,y=0;
Scanner sc=new Scanner(System.in);
//Asks for the first number until the user inputs an integer
System.out.println("First number:");
while(!sc.hasNextInt()){
System.out.println("Not valid. First number:");
sc.nextLine();
}
x=sc.nextInt();
//Asks for the second number until the user inputs an integer
System.out.println("Second number:");
while(!sc.hasNextInt()){
System.out.println("Not valid. Second number:");
sc.nextLine();
}
y=sc.nextInt();
//Show result
System.out.println(x+"*"+y+"="+x*y);
}
}
The loop for the first number works fine. But, the second doesn't: if the user inputs something that is not an integer value, the message "Not valid. Second number:" is shown twice!
First number:
g
Not valid. First number:
2
Second number:
f
Not valid. Second number:
Not valid. Second number:
4
2*4=8
What is the reason for this behaviour? I guess I'm doing something wrong.
I've tried to use two different Scanners (one for each number) and the problem dissapears, but I don't think that creating lots of instances is the correct path.
Can anybody help?
Thanks.
Because even after accepting the first int value there is still the newline character to consume,
so change to
x=sc.nextInt();
sc.nextLine();
So I am trying to make a code that will prompt the user to either use a basic calculator, or a word counter that displays how many words are in a given sentence entered by the user, this is done using methods. I have figured out how to properly set up the calculator, but the word counter is giving me some issues:
public static int wordCounter(String str){
String words[]=str.split(" ");
int count=words.length;
return count;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("What do you want to do( calculator(0)/word counter(1) )? ");
//This runs and I select '1' for word counter
int choice = input.nextInt(); //Input the choice here
if (choice == 0) {
// It runs this selection statment, and since zero is not selected,
//it runs the word Counter branch
calculator();
}else{
System.out.println("Please enter a sentence:"); // Tells me to enter a sentence
String sentence=input.nextLine();
//^ This input is completely skipped and goes
//right to the 'System.out.print(); Statement.
System.out.print("There are "+ wordCounter(sentence) + " words in the sentence.");
//^ This prints a 1 immediately after the branch is selected with '1'
}
}
I'm not sure where it is going wrong since this only happens while it is in the if/else statement. Doing some testing also showed me that it seems that the first scanner "int choice=input.nextInt()" Is somehow interfering with the second scanner for the string. Any ideas keeping a similar formatting would be greatly appreciated.
Please forgive my formatting, it may not look great.
nextLine() will only return the remainder of the current line being scanned. Since you would have pressed enter after selecting the number, all it will capture is an empty string.
To fix it, just add a nextLine() directly after you get the integer.
public String nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()
The problem is when you enter the number int choice = input.nextInt() it's only scanning the integer, not the newline. So when you call input.nextLine() it instantly returns an empty string. One way to fix this would be to replace that line with
int choice = Integer.parseInt(input.nextLine());
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm taking user input from System.in using a java.util.Scanner. I need to validate the input for things like:
It must be a non-negative number
It must be an alphabetical letter
... etc
What's the best way to do this?
Overview of Scanner.hasNextXXX methods
java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them:
hasNext() - does it have any token at all?
hasNextLine() - does it have another line of input?
For Java primitives
hasNextInt() - does it have a token that can be parsed into an int?
Also available are hasNextDouble(), hasNextFloat(), hasNextByte(), hasNextShort(), hasNextLong(), and hasNextBoolean()
As bonus, there's also hasNextBigInteger() and hasNextBigDecimal()
The integral types also has overloads to specify radix (for e.g. hexadecimal)
Regular expression-based
hasNext(String pattern)
hasNext(Pattern pattern) is the Pattern.compile overload
Scanner is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern), which lets you define what pattern separates your tokens. There are also find and skip methods that ignores delimiters.
The following discussion will keep the regex as simple as possible, so the focus remains on Scanner.
Example 1: Validating positive ints
Here's a simple example of using hasNextInt() to validate positive int from the input.
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
Here's an example session:
Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5
Note how much easier Scanner.hasNextInt() is to use compared to the more verbose try/catch Integer.parseInt/NumberFormatException combo. By contract, a Scanner guarantees that if it hasNextInt(), then nextInt() will peacefully give you that int, and will not throw any NumberFormatException/InputMismatchException/NoSuchElementException.
Related questions
How to use Scanner to accept only valid int as input
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
Example 2: Multiple hasNextXXX on the same token
Note that the snippet above contains a sc.next() statement to advance the Scanner until it hasNextInt(). It's important to realize that none of the hasNextXXX methods advance the Scanner past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!
This has two consequences:
If you need to skip the "garbage" input that fails your hasNextXXX test, then you need to advance the Scanner one way or another (e.g. next(), nextLine(), skip, etc).
If one hasNextXXX test fails, you can still test if it perhaps hasNextYYY!
Here's an example of performing multiple hasNextXXX tests.
Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
System.out.println(
sc.hasNextInt() ? "(int) " + sc.nextInt() :
sc.hasNextLong() ? "(long) " + sc.nextLong() :
sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
"(String) " + sc.next()
);
}
Here's an example session:
5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit
Note that the order of the tests matters. If a Scanner hasNextInt(), then it also hasNextLong(), but it's not necessarily true the other way around. More often than not you'd want to do the more specific test before the more general test.
Example 3 : Validating vowels
Scanner has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
System.out.println("That's not a vowel!");
sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);
Here's an example session:
Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e
In regex, as a Java string literal, the pattern "[aeiou]" is what is called a "character class"; it matches any of the letters a, e, i, o, u. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner.
API links
hasNext(String pattern) - Returns true if the next token matches the pattern constructed from the specified string.
java.util.regex.Pattern
Related questions
Reading a single char in Java
References
Java Tutorials/Essential Classes/Regular Expressions
regular-expressions.info/Character Classes
Example 4: Using two Scanner at once
Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner, where the second Scanner takes the nextLine() from the first Scanner as input. Here's an example:
Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
Scanner lineSc = new Scanner(sc.nextLine());
int sum = 0;
while (lineSc.hasNextInt()) {
sum += lineSc.nextInt();
}
System.out.println("Sum is " + sum);
}
Here's an example session:
Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit
In addition to Scanner(String) constructor, there's also Scanner(java.io.File) among others.
Summary
Scanner provides a rich set of features, such as hasNextXXX methods for validation.
Proper usage of hasNextXXX/nextXXX in combination means that a Scanner will NEVER throw an InputMismatchException/NoSuchElementException.
Always remember that hasNextXXX does not advance the Scanner past any input.
Don't be shy to create multiple Scanner if necessary. Two simple Scanner is often better than one overly complex Scanner.
Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any Scanner method that takes a String pattern argument is regex-based.
Tip: an easy way to turn any String into a literal pattern is to Pattern.quote it.
Here's a minimalist way to do it.
System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();
For checking Strings for letters you can use regular expressions for example:
someString.matches("[A-F]");
For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want.
Here
public int readInt(String prompt, int min, int max)
{
Scanner scan = new Scanner(System.in);
int number = 0;
//Run once and loop until the input is within the specified range.
do
{
//Print users message.
System.out.printf("\n%s > ", prompt);
//Prevent string input crashing the program.
while (!scan.hasNextInt())
{
System.out.printf("Input doesn't match specifications. Try again.");
System.out.printf("\n%s > ", prompt);
scan.next();
}
//Set the number.
number = scan.nextInt();
//If the number is outside range print an error message.
if (number < min || number > max)
System.out.printf("Input doesn't match specifications. Try again.");
} while (number < min || number > max);
return number;
}
One idea:
try {
int i = Integer.parseInt(myString);
if (i < 0) {
// Error, negative input
}
} catch (NumberFormatException e) {
// Error, not a number.
}
There is also, in commons-lang library the CharUtils class that provides the methods isAsciiNumeric() to check that a character is a number, and isAsciiAlpha() to check that the character is a letter...
If you are parsing string data from the console or similar, the best way is to use regular expressions. Read more on that here:
http://java.sun.com/developer/technicalArticles/releases/1.4regex/
Otherwise, to parse an int from a string, try
Integer.parseInt(string). If the string is not a number, you will get an exception. Otherise you can then perform your checks on that value to make sure it is not negative.
String input;
int number;
try
{
number = Integer.parseInt(input);
if(number > 0)
{
System.out.println("You positive number is " + number);
}
} catch (NumberFormatException ex)
{
System.out.println("That is not a positive number!");
}
To get a character-only string, you would probably be better of looping over each character checking for digits, using for instance Character.isLetter(char).
String input
for(int i = 0; i<input.length(); i++)
{
if(!Character.isLetter(input.charAt(i)))
{
System.out.println("This string does not contain only letters!");
break;
}
}
Good luck!
what i have tried is that first i took the integer input and checked that whether its is negative or not if its negative then again take the input
Scanner s=new Scanner(System.in);
int a=s.nextInt();
while(a<0)
{
System.out.println("please provide non negative integer input ");
a=s.nextInt();
}
System.out.println("the non negative integer input is "+a);
Here, you need to take the character input first and check whether user gave character or not if not than again take the character input
char ch = s.findInLine(".").charAt(0);
while(!Charcter.isLetter(ch))
{
System.out.println("please provide a character input ");
ch=s.findInLine(".").charAt(0);
}
System.out.println("the character input is "+ch);