So here is my program:
// Creates a Scanner object that monitors keyboard input
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("How old are you? ");
int age = checkValidAge();
if (age != 0)
{
System.out.println("You are " + age + " years old");
}
}
public static int checkValidAge()
{
try
{
return userInput.nextInt(); // nextInt() receives the user input
}
catch (InputMismatchException e)
{
userInput.next(); // Skips the last user input and waits for the next
System.out.print("That isn't a whole number");
return 0;
}
}
When I enter a number with 3 decimal places, Java outputs it as an Integer:
If I input the number with 2 or more than 3 decimal points, then the program will know that input is not correct. So why does it ignore 3 decimal places and outputs it as an int?
Stream::nextInt reads an integer from a stream.
2,444 is an integer in your default locale (2,444 = 2444).
If you want to read a decimal number you need to use the Stream::nextDouble or another appropriate method.
Related
I need the user to enter an integer input, check whether it starts by 0 and tell the user to enter another integer if that is the case
I tried parsing the integer input to a string, that works but only once. The string cannot be edited when program loops
I think the solution should not at all involve strings because i need the program to loop and check over and over until the input is valid (ie has no leading zeroes)
Splitting each digit of the int into an array does not work also because the ways i found pass by string.
public static void main(String[] args){
Scanner key = new Scanner(System.in);
int in= 0;
boolean looper=true;
while (looper == true) {
System.out.println("Enter an integer");
in = key.nextInt();
/* check whether in has any leading zeroes, example of
wrong input: 09999, 0099*/
if (/*in has no leading zeroes*/)
looper = false;
}
key.close();
}
Maybe another answer would be to have a method that creates a brand new string every time the program loops, so maybe like a recursion that automatically creates strings, not sure if that's even a thing though.
You can make it cleaner by using a do-while loop instead of while(true). Note that an integer starting with 0 is an octal number e.g.
public class Main {
public static void main(String[] args) {
int x = 06;
System.out.println(x);
// x = 09; // Compilation error - out of range
}
}
Thus, 06 is a valid integer. For your requirement, you can input to a String variable and prompt the user to again if it starts with a zero. If the input does not start with a zero, try parsing it to an int and process it if it succeeds; otherwise, loopback e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
String input = "";
int in = 0;
boolean valid = true;
do {
System.out.print("Enter an integer: ");
input = key.nextLine();
if (input.startsWith("0")) {
System.out.println("Invalid input");
valid = false;
} else {
try {
in = Integer.parseInt(input);
System.out.println("You entered " + in);
// ... process it
valid = true;
} catch (NumberFormatException e) {
System.out.println("Invalid input");
valid = false;
}
}
} while (!valid);
}
}
A sample run:
Enter an integer: 09999
Invalid input
Enter an integer: xyz
Invalid input
Enter an integer: 123
You entered 123
As an aside, never close a Scanner(System.in) because it also closes System.in and there is no way to open it without rebooting the JVM.
This question already has an answer here:
While loop to determine if entered value is a double
(1 answer)
Closed 1 year ago.
I know there are lots of questions similar to this but I can't understand most of it, also I can't see any similar questions related to java language.
So can you guys help me how to loop this question if the input is not a double data type?
The code:
System.out.println("Enter first number");
num1 = input.nextDouble();
System.out.println("Enter second number");
num2 = input.nextDouble();
I really appreciate anyone who tries to answer, tia!!
This is a solution (without exception handling). It loops until two Doubles have been entered. So it is possible to enter this:
3
4.2
or also:
www
3
abc
4.2
Both will give the same result
3
4.2
Note that the code is locale sensitive in regard of the numbers you enter at the command prompt (meaning that the decimal sign depends on your computer settings – in Germany for example it is the comma and not the dot, so you would enter 4,2):
Scanner scanner = new Scanner(System.in);
Double part1 = null;
Double part2 = null;
while (true) {
if (scanner.hasNextDouble()) {
if (part1 == null ) {
part1 = scanner.nextDouble();
} else {
part2 = scanner.nextDouble();
break;
}
} else {
scanner.next(); // The input is not a Double, so just drop it
}
}
scanner.close();
System.out.println(part1);
System.out.println(part2);
If you add the line scanner.useLocale(Locale.ROOT) after creating the scanner:
Scanner scanner = new Scanner(System.in);
scanner.useLocale(Locale.ROOT);
the decimal sign will be the dot '.' like in 4.2 independent of the settings of your computer.
I like to create a separate method to validate input. If the value is invalid, then I have the method return -1. Then I'll have a while loop that checks if the input is -1, if so, than it'll ask the for a new input value till it's correct. There are many ways to go about it. But the gist is something like this.
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
double num1 = validateDouble(input);
while (num1 == -1) {
num1 = validateDouble(input);
}
System.out.println(num1);
}
private static double validateDouble(Scanner scanner) {
String input = scanner.nextLine();
try {
double i = Double.parseDouble(input);;
return i;
}catch (InputMismatchException | NumberFormatException e) {
if (input.equals("q")) {
System.exit(0);
}
System.out.println("Please try again.");
return -1;
}
}
I am trying to read an integer from the user, then print even if that number is an even number or odd otherwise. I have been told I can assume that the user types a valid integer. The input/output should match the following example:
Type a number: 14
even
What am I missing? Any ideas on how I can get the desired inputs and expected outputs? Test1[3][Test4]4
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int even = scan.nextInt();
int odd = scan.nextInt();
if ((even%2)==0){
System.out.println("Type a number:"+ even);
}
else {
System.out.println("Type a number:"+ odd);
}
}
}
The problem is that you have all your variables and order of the flow of your program mixed up. In English this is what you are doing
Prompt user for an integer, call that integer "even"
Prompt user for an integer, call that integer "odd"
If the integer called "even" is divisible by 2 without a remainder then print "type a number" and then the value of the integer called "even"
Otherwise print "type a number" and then the value of the integer called "odd"
You only need to read a value from the user once, then decide which message to print based on that value:
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
System.out.println("Type a number:");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
if ((number%2)==0){
System.out.println("even");
}
else {
System.out.println("odd");
}
}
}
I have pointed out some issues in your code. Please correct them.
import java.util.Scanner;
//follow java naming convention and name class as "EvenOdd"
public class evenOdd {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt(); //renamed to number
int odd = scan.nextInt(); //do not need this variable
if ((number %2)==0){
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
}
Ask the user the question first so that he knows he has to input a number
System.out.println("Type a number: ");
You can simply just get 1 input from the user and store on the same variable
int input = scan.nextInt();
Then you would just check that 1 input with the if/else and display the correct output
if ((input%2)==0){
System.out.println(input + " is even.");
}
else {
System.out.println(input + " is odd.");
}
This program is for computing the digits of an integer. So there is chances to enter the input by user may string("raju" whatever it may be), number(12334), combination(string & number i.e, 234dsd) and nothing(he doesn't enter anything), isn't it? There might be another chances too I don't know(If there is mention it here).Try out with various inputs and the problems here are when I entered number and nothing. If input is number "result not coming" cmd prompt not continuing further and input is nothing(not entered) if statement is not executing. when the cmd prompt goes like that?
//computing digits of integer.
import java.util.Scanner;
class Main
{
public static void main (String w[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a number");
String g=s.nextLine();
System.out.println("Entered value is"+g);
if(g==null)
{
System.out.println("Enter atleast one number");
}
else
{
try
{
int st=Integer.parseInt(g);
int sum=0;
while(st>=0)
{
int value=st%10;
st=st/10;
sum=value+sum;
}
System.out.println("the sum of digits: "+sum);
}catch (NumberFormatException nfe)
{
System.err.println("Invalid input. Enter only number...");
}
}
}
}
It is hard to understand you are asking here, but if you are asking you code is not trying again when the user inputs invalid input, the answer is that it is because your code has no loop to do that.
Repetition of something (in this case, the task of asking for input) generally requires a loop of some kind.
If you indented your code properly, this would probably be more obvious to you.
Try this one
//computing digits of integer.
import java.util.Scanner;
public class Main {
public static void main(String w[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
String g = s.nextLine();
System.out.println("Entered value is " + g);
try {
int st = Integer.parseInt(g);
int sum = 0;
while (st > 0) {
int value = st % 10;
st = st / 10;
sum = value + sum;
}
System.out.println("the sum of digits: " + sum);
} catch (NumberFormatException nfe) {
System.err.println("Invalid input. Enter only number...");
}
}
}
None of the answers so far explicitly mentioned the problem: There is an endless loop here:
int st=Integer.parseInt(g);
int sum=0;
while(st>=0)
{
int value=st%10;
st=st/10;
sum=value+sum;
}
because st never becomes negative when you start with a positive value.
What I'm trying to accomplish is the following...
Asks user for number and check to see if number provided by user input is a 7 digit integer.
If it's a string, throw InputMismatchException and ask again for the number. Is there an easy way to accomplish this other than using regex and provided that the number is in the form 1234567? The other problem is if I input a value such as 12345678, it gets rounded due to int, so how do avoid this.
int number = 0;
try {
number = scan.nextInt(); // Phone Number is 7 digits long - excludes area code
} catch(InputMismatchException e) {
System.out.println("Invalid Input.");
number = validateNumber(number, scan);
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
// Method checks to see if the phone number provided is 7 digits long
// Precondition: the number provided is a positive integer
// Postcondition: returns a 7 digit positive integer
public static int validateNumber(int phoneNumber, Scanner scan) {
int number = phoneNumber;
// edited while((String.valueOf(number)).length() != 7) to account for only positive values
// Continue to ask for 7 digit number until a positive 7 digit number is provided
while(number < 1000000 || number > 9999999) {
try {
System.out.print("Number must be 7 digits long. Please provide the number again: ");
number = scan.nextInt(); // reads next integer provided
} catch(InputMismatchException e) { // outputs error message if value provided is not an integer
System.out.println("Incorrect input type.");
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
}
return number;
}
A valid telephone number is not necessarily an integer (Containing a + sign for country codes for example). So use a String instead.
Simple example with basic regex (7 digits, not validating country codes etc.):
public class Test {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String telephoneNumber = stdin.nextLine();
System.out.println(Pattern.matches("[0-9]{7}", telephoneNumber));
}
}
Here is working example along the lines of your original idea.
public int GetvalidNumber(Scanner scan) {
int number = 0;
while(true) {
try {
System.out.print("Enter a 7 digit number: ");
number = scan.nextInt();
if (number > 0 && Integer.toString(number).length() == 7)
break;
} catch(InputMismatchException e) {
scan.nextLine();
System.out.println("Invalid input: Use digits 0 to 9 only");
continue;
}
System.out.println("Invalid input: Not 7 digits long");
}
return number;
}