Junaid Mahmud Junaid Mahmud - 1 month ago 3
Java Question

How to get length of int from user input in java

I am trying to get the length of characters that the user prints. If the user prints a length less than 5 or greater than 5 It should say "Enter a valid 5 digit number" If the length is 5 I want it to go on the next question, but for some reason it's not working. Thanks!

package Hw;
import java.util.Scanner;
public class Library {

public static void main(String[] args) {

int cardnumber = 0;
int age;
int item = 0;
int overdue = 0;

int fine = item * overdue;

int length = length(Integer.toString(cardnumber));

Scanner Keyboard = new Scanner (System.in);



System.out.println("Enter Card Number: ");
cardnumber = Keyboard.nextInt();
System.out.println("Enter Age: ");
age = Keyboard.nextInt();
System.out.println("Enter Item Type (Book = 1, Magazine = 2, Dvd = 3): ");
item = Keyboard.nextInt();
System.out.println("Enter The Amount Of Days The Item Has Been Overdue");
overdue = Keyboard.nextInt();

if (length == 5)
{
System.out.println(cardnumber);
}
if (length > 5 || length < 5)
{
System.out.println("Enter A Valid 5 Digit Number");
}



if (item == 1)
{
fine = (int) (overdue * 0.50);
}

else if (item == 2)
{
fine = (int) (overdue * 0.25);
}

else if (item == 3)
{
fine = (int) (overdue * 1.50);
}



if (age > 5 || age < 18)
{
fine = (int) 1.00;
}


if (age > 70)
{
fine = 0;
}


else if(age > 18 || age < 70)
{

if(overdue < 5)
System.out.println("Days Overdue "+ overdue);
}

else
{
fine = (int) 5.00;
}


/*else if (age < 6 || age > 17)
{
fine = (int) 1.00;
}
*/



System.out.println("Card Number "+ cardnumber);



System.out.println("Age "+ age);

// System.out.println("Days overdue "+ overdue);

System.out.println("Fine "+ fine);

// System.out.println("Fine adjustment reason "+ )


if(item == 1)
{
System.out.println("item Book");
}

else if(item == 2)
{
System.out.println("item Magazine");
}

else if(item == 3)
{
System.out.println("item Dvd");
}

else if(item <1 || item >3)
{
System.out.println("Invalid Information");
}
}

private static int length(String string) {
// TODO Auto-generated method stub
return 0;
}
}

Answer

The main concept should be working with String instead of Integer, by that approach it is much easier and quicker to check the user's input length.

I would recommend to change the code as follows: Change that line:

int length = length(Integer.toString(cardnumber));

to:

String length = Integer.toString(cardnumber); 

Another change is the following lines:

if (length == 5)
{
System.out.println(cardnumber);
} 
if (length > 5 || length < 5)
{
System.out.println("Enter A Valid 5 Digit Number");
}

Should be replaced to:

while(length != 5) {
    System.out.println("Enter A Valid 5 Digit Number");
    cardnumber = Keyboard.nextInt();
    length = Integer.toString(cardnumber);
}