I am writting a program where the user enters a String input and the program finds the number of words and the number of int numbers. Scanner should close when the user enters "0".
My code
import java.util.Scanner;
public class RunMe
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String input = in.nextLine();
Counter numbers = new Counter();
Counter words = new Counter();
Scanner s = new Scanner(input).useDelimiter("\\s");
while(s.nextInt() != 0)
{
if(s.hasNextInt())
{
numbers.add();
}
else
{
words.add();
}
}
s.close();
in.close();
System.out.println("Number of numbers : " + numbers.value());
System.out.println("Number of words : " + words.value());
}
}
and the class Counter
public class Counter
{
private int value;
public int add()
{
value++;
return value;
}
public int value()
{
return value;
}
}
When I run my program I get the following excepion:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at RunMe.main(RunMe.java:13)
Change the condition of your main loop to check if there is something to read and use a break if the numeral is equals to 0.
Solution
while(s.hasNext())
{
if(s.hasNextInt())
{
if (s.nextInt() == 0) break;
numbers.add();
}
else
{
s.next();
words.add();
}
}
With Scanner the console input must be feed using "enter". To avoid this, some other native library would be required, such as JLine. There are other options in this similar question.
Related
I'm trying to make a program where a user needs to input a random integer. If the user inputs a String I want an error message to pop out: "This is not a number" and after that restart the program until the user inputs a number. I got this so far and I'm stuck. I just get an error message if I input a string and program crashes.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 0;
do {
System.out.println("Input a number!");
number = scanner.nextInt();
if (!scanner.hasNextInt()) {
System.err.println("This is not a number");
}
} while (!scanner.hasNextInt());
System.out.println("You entered: " + number);
}
You're getting an InputMisMatchException because if you input a string into a scanner.nextInt(), it will immediately give an error and stop the program before it does anything else, so it won't reach your if statement. One way to get around this issue is to instead receive user input as a string, try to parse it for an int, and end the loop if it doesn't throw an exception. This is my implementation:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
int number = 0;
boolean end = true;
do {
System.out.println("Input a number!");
input = scanner.nextLine();
try {
number = Integer.parseInt(input);
end = true;
} catch(Exception e) {
System.err.println("This is not a number");
end = false;
}
} while (!end);
System.out.println("You entered: " + number);
}
See if the below code can help achieve what you want to do.
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String number;
do {
System.out.println("Input a number!");
number = scanner.next();
} while (!isNumeric(number));
System.out.println("You entered: " + number);
}
public static boolean isNumeric(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
return str.chars().allMatch(Character::isDigit);
}
}
I'm trying to make it to were is will throw my exception if the input is not a number and i cant figure it out, Could someone help me get on the right track
import java.util.Scanner;
class calculations
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int number;
int total = 0;
try
{
} catch ( IllegalArgumentException e)
{
//error
}
while (true)
{
number = scan.nextInt();
if (number == 0)
{
break;
}
total += number;
}
System.out.println("Total is " + total);
}
}
You should use hasNextInt, which will allow you to check if the next token in the stream can be parsed as an int.
if (! scanner.hasNextInt()) throw new IllegalArgumentException()
I am wondering how I can check if a user's input is a certain primitive type (I mean integer, String, etc... I think it's called primitive type?). I want a user to input something, then I check if it's a String or not, and do a certain action accordingly. (JAVA)
I have seen some codes like this:
if (input == (String)input) { (RANDOM STUFF HERE) }
or something like
if input.equals((String) input)
And they don't work. I want to know how I can Check for only a String? (EDITED OUT)
I was wondering if there was a function that can do that? Thanks for the answers
EDIT: With the help of everyone I have created my fixed code that does what I want it to:
package files;
import java.util.*;
public class CheckforSomething {
static Scanner inputofUser = new Scanner(System.in);
static Object userInput;
static Object classofInput;
public static void main(String[] args){
try{
System.out.print("Enter an integer, only an integer: ");
userInput = inputofUser.nextInt();
classofInput = userInput.getClass();
System.out.println(classofInput);
} catch(InputMismatchException e) {
System.out.println("Not an integer, crashing down");
}
}
}
No need for answers anymore, thanks!
Use instanceof to check type and typecast according to your type:
public class A {
public static void main(String[]s){
show(5);
show("hello");
}
public static void show(Object obj){
if(obj instanceof Integer){
System.out.println((Integer)obj);
}else if(obj instanceof String){
System.out.println((String)obj);
}
}
}
You may try this with Regex:
String input = "34";
if(input.matches("^\\d+(\\.\\d+)?")) {
//okay
} else {
// not okay !
}
Here,
^\\d+ says that input starts with a digit 0-9,
()? may/or may not occur
\\. allows one period in input
Scanner input = new Scanner (System.in);
if (input.hasNextInt()) System.out.println("This input is of type Integer.");
else if (input.hasNextFloat()) System.out.println("This input is of type Float.");
else if (input.hasNextLine()) System.out.println("This input is of type string.");
else if (input.hasNextDouble()) System.out.println("This input is of type Double.");
else if (input.hasNextBoolean()) System.out.println("This input is of type Boolean.");
else if (input.hasNextLong())
System.out.println("This input is of type Long.");
Hate to bring this up after 6 years but I found another possible solution.
Currently attending a coding bootcamp and had to solve a similar problem. We introduce booleans and change their values depending on the result of the try/catch blocks. We then check the booleans using simple if statements. You can omit the prints and input your code instead. Here's what it looks like:
import java.io.IOException;
import java.util.Scanner;
public class DataTypeFinder {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
String input = "";
while (true) { //so we can check multiple inputs (optional)
input = scan.nextLine();
if ("END".equals(input)) { //a way to exit the loop
break;
}
boolean isInt = true; //introduce boolean to check if input is of type Integer
try { // surround with try/catch
int integer = Integer.parseInt(input); //boolean is still true if it works
} catch (NumberFormatException e) {
isInt = false; //changed to false if it doesn't
}
boolean isDouble = true; //same story
try {
double dbl = Double.parseDouble(input);
} catch (NumberFormatException e) {
isDouble = false;
}
if (isInt) {
System.out.printf("%s is integer type%n", input);
} else if (isDouble) {
System.out.printf("%s is floating point type%n", input);
} else if (input.length() == 1) { //this could be useless depending on your case
System.out.printf("%s is character type%n", input);
} else if ("true".equals(input.toLowerCase()) || "false".equals(input.toLowerCase())) {
System.out.printf("%s is boolean type%n", input);
} else {
System.out.printf("%s is string type%n", input);
}
}
}
}
class Main{
public static void main(String args[]){
String str;
Scanner sc=new Scanner(System.in);
int n,
boolean flag=false;
while(!flag){
try{
str=sc.nextLine();
n=Integer.parseInt(str);
flag=true;
}
catch(NumberFormatException e){
System.out.println("enter an no");
str=sc.nextLine();
}
}
}
}
Is this ok?
class Test
{
public static void main(String args[])
{
java.util.Scanner in = new java.util.Scanner(System.in);
String x = in.nextLine();
System.out.println("\n The type of the variable is : "+x.getClass());
}
}
Output:
subham#subham-SVE15125CNB:~/Desktop$ javac Test.java
subham#subham-SVE15125CNB:~/Desktop$ java Test
hello
The type of the variable is : java.lang.String
But Zechariax wanted an answer with out using try catch
You can achieve this using NumberForamtter and ParsePosition.
Check out this solution
import java.text.NumberFormat;
import java.text.ParsePosition;
public class TypeChecker {
public static void main(String[] args) {
String temp = "a"; // "1"
NumberFormat numberFormatter = NumberFormat.getInstance();
ParsePosition parsePosition = new ParsePosition(0);
numberFormatter.parse(temp, parsePosition);
if(temp.length() == parsePosition.getIndex()) {
System.out.println("It is a number");
} else {
System.out.println("It is a not number");
}
}
}
Try instanceof function with Integer instead of int.. each primitive also have a class
probably missing something really silly, but my while loop will not stop printing the error message.
Could someone have a quick look and point me in the right direction?
package week5;
import java.util.*;
public class Week5 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
inputInt();
}
public static int inputInt(){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter number:");
int num;
boolean carryOn = true;
while (carryOn = true) {
{
try {
num = myKeyboard.nextInt();
carryOn = false;
}
catch (Exception e) {
System.out.println ("Integers only");
}
}
}
return 0;
}
This line is the problem
while (carryOn = true) {
Instead of using the comparison operator ==, you are using the assignment operator =. So essentially, you're setting carryOn to true every iteration, then automatically running the body of the loop since the condition essentially becomes
while (true) {
Just change that problem line to
while (carryOn == true) {
Apart from the infinite loop and the fact you always return 0; no matter what the user types, the code is far more complex than it needs to be.
// only create one scanner
private static final Scanner myKeyboard = new Scanner(System.in);
public static void main(String[] args) {
int num = inputInt();
// do something with num
}
public static int inputInt() {
System.out.println("Enter number:");
while (true) {
if (myKeyboard.hasNextInt()) {
int num = myKeyboard.nextInt();
myKeyboard.nextLine(); // discard the rest of the line.
return num;
}
System.out.println ("Integers only, please try again");
}
}
In your case:
while(carryOn==true)
or
while(carryOn)
will solve your problem
If I enter the wrong input(example , if I enter String instead of Integer) loop is not ending, it wont get input next time. Here(below) i attach the entire program. can you please help this?. Thanks in advance!!!
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* If we enter the wrong input(example , if we enter sting instead of integer) it goes unending loop
*
* #author Nithish
*
*/
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
e.printStackTrace();
}
}
}
}
On an InputMismatchException you are doing i--, so the loop condition is modified to prevent the loop from ending without the needed input. If you read the API documentation for Scanner.nextInt() you should notice the following:
If the translation is successful, the scanner advances past the input that matched.
This means that if the input cannot be translated to int, the scanner does not advance. So on the next invocation of nextInt() it will re-read the exact same, non-int, input and fail again. You will need to read past that non-integer token before attempting to get an int again.
Again, don't mess with the loop index inside of the loop as this can cause problems down the road. Instead use a while loop which is much cleaner and much easier to debug 3 months from now:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean done = false;
int result = 0;
while (!done) {
try {
System.out.print("Enter the value: ");
String temp = scanner.nextLine();
result = Integer.parseInt(temp);
done = true;
} catch (NumberFormatException e) {
System.out.println("Please only enter integer data");
}
}
scanner.close();
}
}
what about the below?
Scanner sc = new Scanner(System.in);
while (!sc.hasNext()) {
System.out.println("Enter the value");
if (src.hasNextInt()) {
i = src.nextInt();
System.out.println("Thank you! (" + i+ ")");
}
else
{
System.out.println("Please only int");
}
}
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
//e.printStackTrace();
scanner.nextLine(); //you can add this here.
//scanner.next(); you can also use this
}
}