if condition not working with length function - java

I've used the length function to calculate the length of digits in an integer input in my program. But when I enter the condition in if syntax, it specifically accepts 1234567890 as input. More clearly, if I enter any random 10 digit no. it shows error whereas on entering 1234567890 it works.
My code snippet:
import java.util.*;
public class tryy {
public static void main(String[] args) {
System.out.println("Mobile Number");
Scanner sc1= new Scanner(System.in);
int number = sc1.nextInt();
int length = String.valueOf(number).length();
if (length != 10){
System.out.println("Invalid Mobile number!");
System.exit(0);
}
}
}
Output when entering any 10 digit random number:
Mobile Number
6483928564
Exception in thread "main" java.util.InputMismatchException: For input string: "6483928564"
at java.base/java.util.Scanner.nextInt(Scanner.java:2264)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at tryy.main(tryy.java:6)

The reason is that you have input value more than Integer.MAX_VALUE,check the Integer documentation,we can find that the max value of Integer is 2147483647,while your input is 6483928564,it's greater than the max value,which cause this problem.
In order to solve this problem,you can use long instead of int(keep in mind that long type also may face this issue)
long number = sc1.nextLong();

Here is your Solution
Maximum value that a integer variable in java can accept is 2147483647
Use Double or Long Int

The problem is that, you are assigning a big number for integer type, so try long or another type.
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Mobile Number");
Scanner sc1= new Scanner(System.in);
// int number = sc1.nextInt();
long number = 6483928564L;
int length = String.valueOf(number).length();
if (length != 10){
System.out.println("Invalid Mobile number!");
System.exit(0);
}
else
{
System.out.println("No problem!");
}
}
}

If you are not performing any calculations, then you can take the input as String, and check the length of it.
It will solve your dependency on data types' storage capacity.
You can also do pattern validations, for a phone number, if you take the input as a string.
But if you want to do calculations, then you can change the variable type to a higher type and it will solve your problem.

Related

While-loop will not terminate in console after entering numbers

I keep trying to get this to work but when I enter in the numbers and enter them into the console it does not finish. I have to terminate myself.
import java.util.Scanner;
public static void main(String[] args) {
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (keyboard.hasNextInt());
System.out.println(outputSum);
}
Well, yes. The keyboard.hasNextInt() call will return false for two reasons.
The next token is a NOT an integer.
You have reached the end-of-input.
What is (most likely) happening is that you have stopped entering numbers. The program is (patiently) waiting for you to enter ... something.
Solutions:
Tell the user to enter the (OS specific) terminal "end of file" character. On Linux it is CTRL-D. On Windows CTRL-Z.
Tell the user to enter something that isn't an integer.
Pick an integer as meaning that there are no more numbers, and test for that.
You also need to instruct the user how to "end" the sequence; e.g.
System.out.println("Enter sequence of numbers. Enter a non-number to stop.");
This is actually a problem with your application's "user interface" design. If the user is expected to type an arbitrarily long sequence of numbers (or something else), then there needs to be some way for the user to tell the program that the sequence is finished. The program cannot magically distinguish the cases of "there are no more" and "hang on, I'm taking a break from typing".
The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default. That is, hasNext() checks the input and returns true if it has another non-whitespace character.
In this case hasNext() won't return true because there is neither any integer nor any whitespace. Therefore the program waits for the next input. Besides use a specific integer to break the loop.
for instance,
System.out.println("Input -1 will end the program!";
do{
int x = keyboard.nextInt();
if(x == -1){
break;
}
//do something
}while(true);
Your code is ok. There is no issue.
But before writing code, we need to think about it. The workflow of your code below:
1st time when we enter do loop, keyboard.nextInt() takes input from us.
Then it calculates the sum and performs string operation.
After that, while's keyboard.hasNextInt() takes next input from you.
Checks your input. If your input is not an integer, while loop will terminate(break).
If your input is an integer then, code loop back to keyboard.nextInt(). But this time, it does not take input from you.
It pases the buffered input(keyboard.hasNextInt()) to keyboard.nextInt() and assign the value to inputNum
So, when you want to terminate while loop, you should input any character like a, b, c, etc.
You haven't specified when the loop will end. Have a condition such as inputting a certain number that will end the program once entered, as currently your program is just going to wait for more input. Something like :
System.out.println("Enter sequence of numbers to add. Enter '0' to end the program");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (inputNum != 0);//Keeps going as long as 0 is not entered
//When zero is entered, program shows the total sum and terminates
if (inputNum == 0) {
System.out.println("The sum of all total numbers: ");
System.out.println(outputSum);
System.exit(0);//Terminates program
}
Basic syntax of do-while Loop:
do{
// do something
}while(terminating condition);
If you are using hasNextInt() method of Scanner object for terminating condition in do-while loop then loop will be terminated once it get input other than an integer value (e.g float, double, char, String etc.. ) as shown in below complete program.
import java.util.Scanner;
public class Cumulative{
public static void main(String[] args){
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do{
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
}while (keyboard.hasNextInt()); // loop will terminated whenever get any value other than valid integer such as float char or String etc..
System.out.println(outputSum);
}
}

I try to make a guess game and let user decide under what max number to guess

In oder to check the value entered by the user AND to see what random number has been calculated, I want to let those numbers projected in the console (eclipse). But what sketches my astonishment?? the last two system.out.println's (right above invoermax.close())) do NOT appear in the console screen after I entered the number???? It's like java doesn't even read or notice these code lines, How come???
Here my code:
package Package1;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class test6KOPIE1 {
public static void main(String[] args)
{
Scanner Invoermax = new Scanner(System.in);
System.out.println("Under which number you want to guess");
int Invoer = Invoermax.nextInt();
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
System.out.println("So a guess under max: " + Invoer);
System.out.println("The random number has become " + Hoogte);
Invoermax.close();
}
}
every time you call Scanner.nextInt() it will wait for input from you.
The problem is that you are calling it twice, replace:
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
With the variable you already got:
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoer);
And BTW, usually in java you start field/variable name with lower case letter, so should be hoogte, inoverMax, inover etc.
You can do something like this.
// code
Scanner Invoermax = new Scanner(System.in);
System.out.println("Under which number you want to guess");
int Invoer = Invoermax.nextInt();
Invoermax.nextLine(); // reading empty space left
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
// code
You have two scanner.nextInt() calls, so there are two input readings, two input waitings.
int Invoer = Invoermax.nextInt(); // the first input reading
int Hoogte = ThreadLocalRandom.current().nextInt(1,
Invoermax.nextInt()); // the second input reading
When you enter two int values in a console (any of the kind) you'll see your ending print rows.
If your design was to have a single input, then use cashed value for the second usage
int Invoer = Invoermax.nextInt(); // the first input reading
int Hoogte = ThreadLocalRandom.current().nextInt(1,
Invoer ); // use cashed value

Using ints/doubles and Strings in the same Scanner variable

So I'm new to java programming, coming from Python, and there's a few concepts that I can't quite understand.
I'm writing a program which allows the user to enter as many numbers as they want and the program should output the average of all of the numbers. I used a while loop to loop through the inputs by the user as many times as they wanted, but I needed a way of exiting the loop so that the program could proceed with calculating the average of all of the inputs. I decided that if the user enters an "=" sign instead of a number, then the program would break out of the loop, but since the Scanner variable was looking for a double, and the "=" sign is not a number, I would have to make it a String. But because the Scanner is looking for a double, the program threw an error when it encountered the "=".
How can I get the program to exit the loop when the user types "="? I know I could just allow the user to enter a number that breaks the loop, but if it was a real world program and the user entered a number, it would count that number along with the previous ones when calculating the average. The code I have so far is as follows:
import java.util.Scanner;
// imports the Scanner class
public class Average{
public static void main(String[] args){
double num, total = 0, noOfInputs = 0, answer;
Scanner scanner = new Scanner(System.in);
while(true){
System.out.print("Enter number: ");
//Prompts the user to enter a number
num = scanner.nextDouble();
/*Adds the number inputted to the "num" variable. This is the
source of my problem*/
if(num.equals("=")){
break;}
/*The if statement breaks the loop if a certain character is
entered*/
total = total + num;
//Adds the number inputted to the sum of all previous inputs
noOfInputs++;
/*This will be divided by the sum of all of the numbers because
Number of inputs = Number of numbers*/
}
answer = total / noOfInputs;
System.out.print(answer);
}
}
Several ways to do this.
You could read every number as a string, and then if it is a number, parse it to get the value.
Integer.parseInt(String s)
Or you could check what comes next and read accordingly:
while (scanner.hasNext()) {
if (sc.hasNextInt()) {
int a = scanner.nextInt();
} else if (scanner.hasNextLong()) {
//...
}
}
Or you could just catch the InputMismatchException, and work from there.
try{
...
} catch(InputMismatchException e){
//check if '=' ...
}

Putting a check for variable type when using Scanner

I am writing a small program (student, though not an assignment for class...but rather a play on a previous assignment). Previously for class, while learning do/while loops, I wrote a program that prompted a user to input integers. When the user typed in 0, it served to get out of the loop, and then outputted the sum of the squares of all the integers typed.
Example output (double spaced for line breaks):
Type an integer: 3
Type an integer: 0
The sum of the squares is 9
My goal now is to take it a step farther. As written, the program crashes if the user types in anything other than an integer. I have been playing around trying to find ways to allow the user to type in other forms of values, without having it crash. In referencing the code below (which is the program at the moment that does crash at any value sans ints), I tried putting in variations of if statements with the console.hasNextInt() method. Yet my attempts in this would cause an error that number in the do/while test may not have been referenced.
Can anyone offer me any tips? It would be appreciated.
public static void userInterface() {
Scanner console = new Scanner(System.in);
int number;
int numberSquared;
int squaredOutput = 0;
do {
System.out.print("Type an integer (0 to quit): ");
number = console.nextInt();
if (number > 0 || number < 0) {
numberSquared = number * number;
squaredOutput += numberSquared;
}
} while (number != 0);
System.out.println("The sum of the squares is " + squaredOutput);
}
The problem is that you are using console.nextInt(); which only takes the next int.
You can use: console.nextLine();.
It would allow your program to accept a string and you can parse it into an Int when necessary:
try {
number=Integer.parseInt(console.nextLine());
} catch(NumberFormatException e) {
System.out.println("Please input an Integer");
}
Just use this function
public static int next(String message) {
while (true) {
System.out.println(message);
try {
return new Scanner(System.in).nextInt();
} catch (Exception e) {
System.out.println("Invalid input.");
}
}
}
There is problem with your code. When you use console.nextInt() and the scanner try to parse every string as Integer. Better solution is to use console.nextLine() and by your own parse it to your number and catch exception that might be thrown if that string is not parsable as any number that you want.
simply it might look like this.
String yourValue = console.nextLine();
try{
int value = Integer.parseInt(yourValue);
}catch(NumberFormatException e){
System.out.println("watch out this value is unparsable!");
}

How to conver a string value to an integer

I want to convert a string value to an integer but I can't. My statement checked
=Integer.parseInt(input);
has an error, please help and thanks a lot in advance.
import java.util.Scanner;
public class ass2a
{
public static void main(String []args)
{
Scanner reader = new Scanner(System.in);
String input,b;
long checked;
System.out.print("Please enter the 12 digit:");
input = reader.nextLine();
if(input.length() < 12)
{
System.out.println("The digit is less than 12.");
}
int one,two,three,four,five,six,seven,eight,nine,ten,eleven,twevle;
checked =Integer.parseInt(input);
System.out.println(checked);
}
}
Use checked =Long.parseLong(input); instead of checked =Integer.parseInt(input);
12 digit numbers are very large and so you can not store it in int.So you need to store in Long
12 digits number is a really big number...Integer can't store it. That is you error - so you need another type to store the number.
I recommend you to use Long : Long.parseLong(input);
That should solve the problem.
Your issue is this line:
input = reader.nextLine();
try this:
checked = Long.parseLong(input);
use
checked= Long.parseLong(input)
instead of
Integer.parseInt
it can't handle a 12 digit long number
You're getting an error because the string value that you are giving as input is more than 2147483647. This is the max int can store (you can sysout Integer.MAX_VALUE to check this). If you intend to input a bigger number, may be you can use long (max value 9223372036854775807)
System.out.println(Integer.MAX_VALUE); // =2147483647 (2^31 - 1)
System.out.println(Long.MAX_VALUE); // =9223372036854775807 (2^63 - 1)
Depending on the input size, you might want to choose the correct data type.
Please see http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for further details.
Here is the corrected program(assuming that your trying to find whether a User-inputted number is less than 12 and displaying the number
import java.util.Scanner;
public class ass2a
{
public static void main(String []args)
{
Scanner reader = new Scanner(System.in);
long input,b;
long checked;
System.out.print("Please enter the 12 digit:");
input = reader.nextLong();
if(String.valueOf(input).length() < 12)
{
System.out.println("The digit is less than 12.");
}
int one,two,three,four,five,six,seven,eight,nine,ten,eleven,twevle;
checked =(long)(input);
System.out.println(checked);
}
}

Categories

Resources