Below code outputs only "Enter a string" and accepts user input however, does not display the number of characters in the string. Kindly help!
System.out.println("Enter a string");
Scanner scan = new Scanner(System.in);
String result = scan.nextLine();
try {
while (a != null) {
count++;
}
} catch (Exception e) {
System.out.println("Invalid string");
}
System.out.println("The number of characters are : " + count);
You can use String.length() to calculate the length of your input string:
System.out.println("Enter a string");
Scanner scan = new Scanner (System.in);
String a = scan.nextLine();
System.out.println("The number of characters are : " + a.length());
oschlueter is right. Also, when using java.util.Scanner to get a string from user input, you won't need a try/catch to look for invalid strings, as anything the user can input can be a String. However, you will need a Try/Catch when asking for a number through Scanner.nextInt.
Also, it's generally recommended to catch a specific error and not just Exception. In this case, you would catch java.util.InputMismatchException.
Related
So I was using this code in my program and whenever I give input consisting of multiple words, the compiler executes the catch block that many times. I've also tried it with different methods & till now all efforts went to vain.
Method 1:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
try
{
size = scanner.nextInt();
break;
}
catch (InputMismatchException e)
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
}
Method 2:
Scanner scanner = new Scanner(System.in);
int size = 0;
boolean bError = true;
while (bError)
{
if (scanner.hasNextInt())
size = scanner.nextInt();
else
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
bError = false;
}
Method 3:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
if (scanner.hasNextInt())
size = scanner.nextInt();
else
{
scanner.next();
System.out.println("Enter valid input (Digit Only)");
continue;
}
String sizeStr = Integer.toString(size);
Pattern pattern = Pattern.compile(new String ("^[0-9]*$"));
Matcher matcher = pattern.matcher(sizeStr);
if(matcher.matches())
{
break;
}
else
{
System.out.println("Enter valid input (Digit Only)");
continue;
}
}
Method 4:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (scanner.hasNext())
{
if (scanner.hasNextInt())
{
size = scanner.nextInt();
System.out.println(size);
break;
}
else
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
}
}
I'm now able to do the task via taking a String input and then parsing it to int. But the initial doubt still remains that why that was not working properly. The code below is working fine.
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
try
{
String sizeStr = scanner.nextLine();
size = Integer.parseInt(sizeStr);
break;
}
catch (NumberFormatException e)
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
}
According to the official Java Doc (https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html):
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next
methods.
The scanner can also use delimiters other than whitespace.
By default, all the next*() functions of scanner class other than nextLine() read the next token, not the next line. This means it reads until it finds a whitespace. If you want to read all the tokens in a line, you need to use nextLine() and then format the input explicitly as you want.
Consider this input:
abcd xyz
When you do scanner.nextInt() or any of scanner.next*() functions other than scanner.nextLine(), only "abcd" is read because it is the next token. When you do scanner.nextLine(), the complete string in the current line "abcd xyz" is read and the scanner advances to the next line.
However, if you want the nextInt() function to read the whole line, then you can set the delimiter to be new line '\n'.
Scanner scan = new Scanner(System.in).useDelimiter("\n");
Using this, you can get the behaviour that you want.
This question already has answers here:
How do I ensure that Scanner hasNextInt() asks for new input?
(2 answers)
Closed 6 years ago.
Desired outcome:
Accepts user input
Makes sure user inputs only 1 integer value at a time
Stores that integer in a variable
I tried to achieve this by doing the following:
Store user input in variable
Count number of tokens in variable
If there's not one token, reject the input
If the input is not of data type int, reject the input
Code:
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer:");
String myString = scan.nextLine();
int tokens = new StringTokenizer(myString, " ").countTokens();
while (tokens != 1 && !scan.hasNextInt()) {
System.out.println("Enter a single integer");
myString = scanner.nextLine();
tokens = new StringTokenizer(myString, " ").countTokens();
}
int number = scanner.nextInt();
System.out.println(number);
This code is full of holes. The output is inconsistent and undesired. It typically ends by throwing a java.util.InputMismatchException error, indicating the value it's trying to store isn't an int. I've experienced this error occur after one loop and after multiple loops, even with the same type and quantity of input (e.g. 2 strings).
Should I keep going with this code, or should I try to approach this problem from a different angle?
I've modified your program a little bit. My approach was to accept a single line of input. If the input contains more than one token, ask the user to re-enter input. If there is only one input, check if the input is an integer, if not, as the user to again provide input.
Seems to work for me:
Scanner scanner = new Scanner(System.in);
String myString;
int tokens;
int number;
do {
System.out.println("Enter a single integer");
myString = scanner.nextLine();
tokens = new StringTokenizer(myString, " ").countTokens();
try {
number = Integer.parseInt(myString);
} catch(NumberFormatException e) {
tokens = 0;
number = -1;
}
}while (tokens != 1);
scanner.close();
System.out.println(number);
Update: Alternate approach without using StringTokenizer
Scanner scanner = new Scanner(System.in);
String myString;
boolean validInput;
int number;
do {
System.out.println("Enter a single integer");
myString = scanner.nextLine();
try {
number = Integer.parseInt(myString);
validInput = true;
} catch(NumberFormatException e) {
validInput = false;
number = -1;
}
}while (validInput == false);
scanner.close();
System.out.println(number);
Update 2: Another approach using regular expressions to validate input before accepting it.
The Scanner allows us to use a regular expression to match the input. If the input matches the pattern, you can use it to accept the input. Otherwise, discard it and ask user to provide input again.
Here's the code:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a single integer");
String integerPattern = "[+-]?\\d+$"; // positive or negative and digits only
while(scanner.hasNext(integerPattern) == false) {
String x = scanner.nextLine();// capture and discard input.
System.out.println("Enter a single integer. '" + x + "' is an invalid input.");
}
int number = scanner.nextInt(); // capture input only if it matches pattern.
scanner.close();
System.out.println("number: " + number);
Hope this helps!
Very Frustrated at my professor, because she did not teach try and catch concepts, neither did she teach us about throw exceptions either, so it is very difficult for me to do this program. The objective is to make a program where the user is asked to input an integer that prints "Hello World" that many times of the integer. The problem is I cannot check to make sure the user input is an integer. For instance, if the user chose to type a character or a double, how do I implement that into my code? And I cannot use throw exceptions or try and catch because we did not learn them yet.Thanks guys!!!
import java.util.Scanner;
public class PrintHelloWorld
{
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
int number;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
number = scan.nextInt();
System.out.print("Your integer is " + number);
int remainder = number%1;
int counts = 0;
if( number>0 && remainder == 0)
{
while(counts <= number)
{
System.out.println("Hello World!");
counts++;
}
}
else
System.out.print("Wrong, choose an integer!");
}
}
scan.hasNextInt()
will check to see if the next value in the input stream is an integer.
as such:
int number = -1;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
if (scan.hasNextInt()) number = scan.nextInt();
if (number != -1) System.out.print("Your integer is " + number);
You can use a loop and validate the input with a regex, like this:
Scanner scan = new Scanner(System.in);
String input = null;
while (true) {
input = scan.nextLine();
if (input.matches("\\d+")) {
break;
}
System.out.println("Invalid input, please enter an integer!");
}
int number = Integer.parseInt(input);
This will keep asking for input until a valid integer is entered.
And I cannot use throw exceptions or try and catch because we did not
learn them yet.
For a first attempt, you could create a method that accepts a String as parameter. You will loop through all the chars of this String and check if each char is a digit. While this method returns false, re-ask the user for a new input.
Then use Integer.valueOf to get the int value..
public static boolean isNumber(String input)
You will have to use sc.nextLine() to get the input
The method Character.isDigit and toCharArray() will be useful
public int cut(int b){
String str1;
b = 0;
Scanner str = new Scanner(System.in);
System.out.println("Write your string: ");
str1 = str.next();
Scanner in = new Scanner (System.in);
System.out.println("Write a number: ");
int num1 = in.nextInt();
System.out.println("Write another number: ");
int num2 = in.nextInt();
System.out.println(str1.substring(num1, num2));
return b;
}
This is my code so far. I want for a user to write a string and write from where to where he wants to cut the string he just entered. The part I can't get is getting that substring.
If you're having spaces in your string. Use Scanner#nextLine() instead.
For an input, "my input string"
str1 = str.next(); // returns "my" only
because space is Scanner's default delimiter. To read the whole line use
str1 = str.nextLine(); // returns "my input string"
Secondly, you're not using Scanner str to read the numbers at all. It should be
int num1 = str.nextInt(); // instead of in.nextInt()
You should also check that the numbers are within bounds or, I think better catch IndexOutOfBoundsException itself. Would take care of negatives and what not.
try {
System.out.println(str1.substring(num1, num2));
} catch (IndexOutOfBoundsException e) {
System.out.println("Range specified is out of bounds for '" + str1 + "'");
}
Why is good practice to empty the 'Garbage' from the input buffer in a block of code like this? What would happen if I didn't?
try{
age = scanner.nextInt();
// If the exception is thrown, the following line will be skipped over.
// The flow of execution goes directly to the catch statement (Hence, Exception is caught)
finish = true;
} catch(InputMismatchException e) {
System.out.println("Invalid input. age must be a number.");
// The following line empties the "garbage" left in the input buffer
scanner.next();
}
Assuming you are reading from the scanner in a loop, if you don't skip the invalid token, you will keep reading it forever. That's what scanner.next() does: it moves the scanner to the next token. See the below simple example, which outputs:
Found int: 123
Invalid input. age must be a number.
Skipping: abc
Found int: 456
Without the String s = scanner.next() line, it would keep printing "Invalid input" (you can try by commenting out the last 2 lines).
public static void main(String[] args) {
Scanner scanner = new Scanner("123 abc 456");
while (scanner.hasNext()) {
try {
int age = scanner.nextInt();
System.out.println("Found int: " + age);
} catch (InputMismatchException e) {
System.out.println("Invalid input. age must be a number.");
String s = scanner.next();
System.out.println("Skipping: " + s);
}
}
}