Author Topic: How to return question if user enters letters with numbers or vice versa.  (Read 3612 times)

0 Members and 1 Guest are viewing this topic.

Offline Enigmatic Entity

  • Exemplar Essayer
  • 28
  • Amigo ad infinitum.
How to return question if user enters letters with numbers or vice versa.
Hi everyone, I'm currently doing a novice java course, and I wish to ask the user to enter some integer. The problem is, I want the question to repeat if the user enters any letters in the field. At the moment it only repeats if the user enters <0 or >1452. Any letters will cause an input error. The solution needs to be simple using language "relevant" (i.e. simple) to the course. Any help greatly appreciated,

E.E.
Juvenescence and multifariousness is eternal.

 

Offline The E

  • He's Ebeneezer Goode
  • 213
  • Nothing personal, just tech support.
    • Steam
    • Twitter
Re: How to return question if user enters letters with numbers or vice versa.
I'm assuming you are using integer.parseInt() to get the users' input, correct? If so, you could encapsulate that in a try/catch pair, since integer.parseInt() throws a NumberFormatException when confronted with something that isn't an integer.

But then, I guess that exception handling hasn't been discussed yet, has it?
If I'm just aching this can't go on
I came from chasing dreams to feel alone
There must be changes, miss to feel strong
I really need lifе to touch me
--Evergrey, Where August Mourns

 

Offline Enigmatic Entity

  • Exemplar Essayer
  • 28
  • Amigo ad infinitum.
Re: How to return question if user enters letters with numbers or vice versa.
Code: [Select]
Using a scanner object as well.

final int AGE_LO = 0, AGE_HI = 1452;
int age;

do
        {
        System.out.print("Age in months? (Rounded to nearest month between 0 and 1452): ");
        age = sc.nextInt();
        sc.nextLine();
        }
        while(age < 0 && age > 1452);

That's a sample of the loop I'm using. I was wondering if there is a way to check for letters/numbers without having to use a String and then check for 1, 2, 3, 4, 5, ...etc. or a, b, c, ....etc.
using a new command for each check, i.e. perhaps something like

if
{
        ageString.charAt(0) > 9

or similar. We haven't covered exception handling yet, sorry I can't use your suggestion, The E. Thanks for the reply, though.
Juvenescence and multifariousness is eternal.

 
Re: How to return question if user enters letters with numbers or vice versa.
The simplest way I can think of (without trying to be clever) is the following:
Code: [Select]
while ( true )
{
  readLine;
  if (line contains only numbers)
    break;
};
STRONGTEA. Why can't the x86 be sane?

 

Offline Enigmatic Entity

  • Exemplar Essayer
  • 28
  • Amigo ad infinitum.
Re: How to return question if user enters letters with numbers or vice versa.
I've tried this, but I can see it's going to get messy:

Code: [Select]
final char AGE_L = '0', AGE_H = '1', AGE_9 = '9';
        String ageAns;
        char ageChar1;
        char ageChar2;
        char ageChar3;
        char ageChar4;
        int ageLength;
       
       
        do
        {
        do
        {
        do
        { System.out.print("Age in months? (Rounded to nearest month between 0 and 1320): ");
        ageAns = sc.next();
        ageChar1 = ageAns.charAt(0);
        ageChar2 = ageAns.charAt(1);
        ageChar3 = ageAns.charAt(2);
        ageLength = ageAns.length();
        }
        while(ageLength <= 3 && ((ageChar1 < AGE_L && ageChar2 < AGE_L && ageChar3 < AGE_L) || (ageChar1 > AGE_9 && ageChar2 > AGE_9 && ageChar3 > AGE_9)));
        }
        while(ageLength > 3 && (ageChar1 < AGE_L || ageChar1 > AGE_H));
        }
        while(ageLength > 4);


I think that a for loop using charAt and "++" my be an alternate method...
Juvenescence and multifariousness is eternal.

 
Re: How to return question if user enters letters with numbers or vice versa.
 :eek2:

You probably should declare some functions like this:
Code: [Select]
bool isNumber( char c )
{ return ( '0' <= c && c <= '9' ) }

and then
Code: [Select]
bool isNumericString( String str )
{
  for ( int i = 0; i < str.length( ); i++ )
  {
     if ( !isNumber( str.charAt( i ) ) )
        return false;
  }

  return true;
}
STRONGTEA. Why can't the x86 be sane?

 

Offline Hippo

  • Darth water-horse
  • 211
  • Grazing.
    • All Hands to War
Re: How to return question if user enters letters with numbers or vice versa.
or

Code: [Select]
if( isAlpha( foo ) )
VBB Survivor -- 387 Posts -- July 3 2001 - April 12 2002
VWBB Survivor -- 100 Posts -- July 10 2002 - July 10 2004

AHTW

  
Re: How to return question if user enters letters with numbers or vice versa.
or

Code: [Select]
if( isAlpha( foo ) )

That, of course, is the other approach to the problem  ;)
STRONGTEA. Why can't the x86 be sane?

 

Offline Flipside

  • əp!sd!l£
  • 212
Re: How to return question if user enters letters with numbers or vice versa.
I suppose that's one of the beauties and pains of Java, it's a bottomless toolbox, which is brilliant if you are faced with a 4-dimensional phased plasma grill with Base-6 encoding, but can make it a devil to find the damn screwdriver ;)

 

Offline DragonClaw

  • Romeo Kilo India Foxtrot
  • 210
Re: How to return question if user enters letters with numbers or vice versa.
Here you go.

Code: [Select]
final int AGE_LO = 0, AGE_HI = 1452;
int age = -1;

System.out.print("Age in months? ");
while(age < AGE_LO || age > AGE_HI) {
System.out.print("Round to nearest month between 0 and 1452): ");
String line = sc.nextLine();
try {
age = Integer.parseInt(line);
} catch(Exception e) {
System.out.println("Invalid input, please enter an integer.");
}
}

 

Offline chief1983

  • Still lacks a custom title
  • 212
  • ⬇️⬆️⬅️⬅️🅰➡️⬇️
    • Minecraft
    • Skype
    • Steam
    • Twitter
    • Fate of the Galaxy
Re: How to return question if user enters letters with numbers or vice versa.
PHP is worse for that, there are many functions that do seemingly the same thing, sometimes though, with their arguments in a different order.  Also, many coders simply choose the wrong tool for the job, especially with PHP.  There are three replace functions, ereg_replace, preg_replace, and str_replace.  str_replace works with static strings, preg is PCRE and ereg is another (slower) form of Reg ex.  For whatever reason, the guys I work with insist on using ereg for general string replacement instead of str_replace (same with strpos() and ereg()).  There's also print() and echo(), only difference being that echo doesn't set a return.  The lack of consistency in the order of arguments for all those similar functions though is what annoys me the most.  It's like they never could decide if it should be (needle, haystack) or (haystack, needle).
Fate of the Galaxy - Now Hiring!  Apply within | Diaspora | SCP Home | Collada Importer for PCS2
Karajorma's 'How to report bugs' | Mantis
#freespace | #scp-swc | #diaspora | #SCP | #hard-light on EsperNet

"You may not sell or otherwise commercially exploit the source or things you created based on the source." -- Excerpt from FSO license, for reference

Nuclear1:  Jesus Christ zack you're a little too hamyurger for HLP right now...
iamzack:  i dont have hamynerge i just want ptatoc hips D:
redsniper:  Platonic hips?!
iamzack:  lays

 

Offline Enigmatic Entity

  • Exemplar Essayer
  • 28
  • Amigo ad infinitum.
Re: How to return question if user enters letters with numbers or vice versa.
I don't think we've learnt about "parseWhatever" yet, or !isNumber.

Code: [Select]
final int AGE_LO = 0, AGE_HI = 1320;
        char ageChar = ' ';
        int age, ageChk = 0, ageLength, ageCount = 0;
        String ageAns;



do
        {
        do
        {
        System.out.print("Age in months? (Rounded to nearest month between 0 and 1320): ");
        ageAns = sc.nextLine();
        ageLength = ageAns.length();
       
        for(ageChk = 0; ageChk < ageLength; ageChk++)
        {
        ageChar = ageAns.charAt(ageChk);
       
        if(ageChar < '0' || ageChar > '9')
        ageCount++;
        }
        }
        while(ageCount != 0);
       
        age = sc.nextInt();
        System.out.println(age);
        }
        while(age < 0 || age > 1320);

This works better, but stuffs up on letters only. There are some new errors elsewhere that are really annoying me at the moment, mainly:

javaFile.java:332: while expected
    }
     ^
javaFile.java:335: reached end of file while parsing

Process completed.

The first one is the end of the main() method!!! Why does it need a while loop? The other one is not understandable...

EDIT: I forgot a bracket in a for loop. Also, I discovered today that I didn't need to have all the check for correct values code, all it needed to do was accept and not analyse the "proper" input! :rolleyes:

I did have a nice time trying the for loop, which worked for some inputs, but...mabye next time I won't need to attempt something that is so complicated. I have a habit of doing that. ;)
« Last Edit: April 16, 2009, 07:56:33 am by Enigmatic Entity »
Juvenescence and multifariousness is eternal.

 

Offline Flipside

  • əp!sd!l£
  • 212
Re: How to return question if user enters letters with numbers or vice versa.
Building a nest makes your problems grow up faster ;)

 

Offline BS403

  • 29
  • I'm just sitting in my Cave.
Re: How to return question if user enters letters with numbers or vice versa.
I had to do basically this same thing a little bit over a year ago before I learned about exceptions.  We had a simple way to do it, let me see if I can find my old code.
http://woogleville.myminicity.com/

Homer: Aw, twenty dollars! I wanted a peanut!
Homer's Brain: Twenty dollars can buy many peanuts.
Homer: Explain how.
Homer's Brain: Money can be exchanged for goods and services.
Homer: Woo-hoo!

 

Offline Enigmatic Entity

  • Exemplar Essayer
  • 28
  • Amigo ad infinitum.
Re: How to return question if user enters letters with numbers or vice versa.
Oh, and just before I finished mine, I discovered someone's fully completed assignment on another forum. That seems a bit silly...I probably should have used more final variables, but there wasn't enough time left, so all the extraneous code was still there. A nice surprise if the marker accidentally entered the wrong values!
Juvenescence and multifariousness is eternal.