inputing and validating the tax number in java - java

I want to take the tax number from a user and check if the number that i am getting is correct but i have a problem .When i run the programm if the user first gives a wrong number(a number with less or more than nine digits) i see the message that i wrote which is correct but when the user gives a correct number after some inputs i see the message again and the loop never stops.If anyone can help me i would appreciate it because i'm stuck :)
enter image description here
enter image description here

The problem occurs when you get the input the 2nd time inside the while loop... Beacuse you aren't actually checking again the TIN number.
I advice you to create a function to check if the TIN is valid and use a while loop to continuously get the input
like so:
public static void main(String[] args) {
System.out.println("Give me your TIN number");
Scanner in = new Scanner(System.in);
long TIN = in.nextLong();
//while the input is not valid ("!" negates the boolean) print invalid input and get the input again
while(!isValidTIN(TIN)){
System.out.println("Wrong number! Try Again");
TIN = in.nextLong();
};
// Countinue with your program
System.out.println("Success");
}
public static boolean isValidTIN(long TIN){
int count = 0;
while(TIN > 0){
TIN /= 10; //You can also use TIN /= 10 instead of TIN = TIN / 10
count++;
}
return count == 9;
}
Also paste the code next time instead of an image

Related

Why can I not enter the while loop? (Java)

I want to prompt the user to enter their value within the while loop. The error is caused from trying to receive the user's values using input = kbd.nextInt() and then trying to use that object name in the condition within my while loop (caused a deadlock). Therefore, when trying to run it, the console was blank. Thank you for the help!
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
Random generator = new Random();
int num = generator.nextInt(100);
int counter = 10;
while (input != num && counter > 0 )
{
System.out.print("Enter your guess at my number ");
input = keyboard.nextInt();
counter--;
}
//close scanner
kbd.close();
}
}
Whenever you use a statement which takes input (in your case - int input = kbd.nextInt();) the Java application stops executing right there and waits for a input from the specified source (System.in here). Try executing the code again and this time input a random number which will be the value of input variable. After that the loop will start.
Also, in this case of the game you should change int input = kbd.nextInt(); to
int input = -1;
That will kill the 1 percent chance of the random number being same as the number entered before the loop (game) starts. Or you could put an if condition checking if input and the random number are equal and if they are take a new random number and check again (in a loop).
With the statement int input = kbd.nextInt(); before the while loop you are already waiting for user input - without prompting the user. I bet you application is waiting for you to enter the first int. Since you are waiting for while loop to start and the application is waiting for you there is a deadlock.
Figure out how to run a debugger to execute your code step by step. It will help a lot.

Java Input/output MyProgrammingLab 21212

I am trying to solve a problem in MyProgrammingLab in which I must use a scanner variable named input, and an integer variable named total, to accept all the integer values in input, and put them into total. The program recommends a while loop;however, I have no idea what the condition would be since the scanner is tied to (system.in) instead of a file so it is accepting random user input rather than a predefined string. Can anyone offer advice? Here is the current code I've tried to use:
int number = 0;
while (input.hasNext())
{
number = input.nextInt();
total = number;
}
I am getting a message that literally only reads ("compiler error") while not understand what is going on. I understand that hasnext will not work, but even if I remove it I get the same compile error message; furthermore, I'm not sure what while condition to use without the hasNext method.
I tried changing to input.hasNextLine since two people suggest it may be an EOF reached error, but I'm still getting a compiler error.
/*
I am trying to solve a problem in MyProgrammingLab in which I must use a scanner variable named input,
and an integer variable named total, to accept all the integer values in input, and put them into total.
The program recommends a while loop;
*/
private static Scanner input; //Collect user numbers
private static int total = 0; // to display total at end
private static int number = 0; // Variable to hold user number
private static boolean loopCheck = true; // Condition for running
public static void main(String[] args) {
// Main loop
while(loopCheck) {
input = new Scanner(System.in); // Setting up Scanner variable
// Information for user
System.out.println("Enter 0 to finish and display total");
System.out.println("Enter an Integer now: ");
number = input.nextInt(); // This sets the input as a variable (so you can work with the information)
total += number; // total = (total + number); Continually adds up.
// When user inputs 0, changes boolean to false, stops the loop
if(number == 0) {
loopCheck = false;
}
}
//Displays this when 0 is entered and exits loop
System.out.println("Your total is: " + total); // Displays the total here
System.out.println("Program completed");
}

Why is output shown only alternately?

public class Two {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
while(obj.nextInt() > 5)
{
System.out.println(obj.nextInt());
}
}
}
If i input the number ( > 5) for first time there is no output on the console but if i input a number on second try there is output on the console.
So I get an output alternatively.
Can anyone explain why is it so?
The java.util.Scanner.nextInt() method Scans the next token of the input as an int and returns it. After the token is read another nextInt()-Call will read (as the name says) the next Integer.
I think you were expecting something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int read;
while((read = scanner.nextInt()) > 5)
{
System.out.println(read);
}
}
Now the read Integer is stored in the variable read and is printed, if it was greater than five.
The reason you're getting output every other input is because you're prompting the Scanner object to gather input twice within your loop system. Every time you call a next... method on your Scanner you are prompting the user.
So in your condition for the while loop you are asking the user to input a value integer value which is then compared against 5. THEN, in your print statement you call the nextInt() method again, which will then prompt the user again for another value integer input.
So given a series of 6 integer inputs for your current loop, 6 2 10 4, you loop will only print 2 and 4.
Instead, you should prompt and store once outside of your loop, then test with the condition and reprompt after the print within the loop like so...
int input = obj.nextInt();
while (input > 5){
System.out.println(input);
input = obj.nextInt();
}

Java program makes user enter same input twice to run after initial input error

I am having problems with my program. Everything is running smoothly, however, when the user inputs the wrong variable it does display the right feedback, but the user then has to enter one extra variable than previously stated.
Maybe it's a simple mistake I have made, but I can't see it..
It's confusing. An example when I run the program:
How many grades would you like to average?
3
Please enter 3 grades:
90
jf //Intentional user input error
You've entered a non-numerical variable. Please enter a number:
95
100 //The program should go ahead and calculate the average after this is entered
100 //It should not expect this fourth input if the amount of grades is 3
Your average is: 96.67
The second 100 input in the console should not appear, but it does when the user has at least one input error. If I were to run the program and input all the correct variables, then the program works smoothly.
This error also occurs when asking for how many grades the user would like to average. I thought it'd be easier to view what's wrong with my program by the second part.
I'm trying to get this program to run smoothly. Help is appreciated!
for (gradesCount = 0; gradesCount < gradeNumber; gradesCount++) {
// Check if the input variables are numerical variables
while (!input.hasNextDouble()) {
input.next();
System.out.println("You've entered a non-numerical variable. Please enter a number: ");
while (input.nextInt()<= 0){
System.out.println("You've entered a negative number. Please eneter a positive number: ");
}
}
// Read grade input
gradesInput = input.nextDouble();
Instead of input.hasNextDouble() you can try below
Scanner scan = new Scanner(System.in);
System.out.print("Enter total no of input ");
int total = Integer.parseInt(scan.nextLine());
int[] input = new int[total];
for (int i = 0; i < total; i++) {
while (true) {
try {
System.out.print("Enter number ");
String in = scan.nextLine();
input[i] = Integer.parseInt(in);
break;
} catch (RuntimeException re) {
System.err.print("Invalid input. ");
}
}
}
scan.close();
System.out.println(Arrays.toString(input));
It'll force the user input only numbers, you can add boundaries or change data type if required.

How to insist that a users input is an int?

Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}

Categories