View Poll Results: Who do you think is the best beginner?

Voters
19. You may not vote on this poll
Page 22 of 22 FirstFirst ... 12202122
Results 211 to 217 of 217

Thread: [Beginner] Programming Challenge: 2

  1. #211
    Join Date
    Sep 2006
    Beans
    2,914

    Re: [Beginner] Programming Challenge: 2

    i didn't ask you to remove try/exception. Anyway, i misread your try/catch block, so just leave it. remove all the ( and ) from you if/else and while loop

  2. #212
    Join Date
    Dec 2006
    Location
    Hogwarts, `UNKNOWN`
    Beans
    Hidden!
    Distro
    Ubuntu 8.10 Intrepid Ibex

    Re: [Beginner] Programming Challenge: 2

    Updated Code
    ------------

    Changes
    Removed Repitation by usage of functions
    Removed the unnessecary cls() function


    Code:
    #!/usr/bin/python
    #Author: Anurag Panda
    #Functions
    
    def getnumeric(msg, l, u): 
    	try:
    		isOK = False
    		
    		while(isOK==False):
    			val = input(msg)
    			if(val>=l and val<u):
    				isOK=True	
    			else:
    				print "***Illogical Data Entered!\n"
    						
    		return val
    		
    			
    	except (NameError, SyntaxError):
    		print "***Text entered into Numerical Field\n"
    		return getnumeric(msg, l, u)
    		
    		
    def getname():
    	name=raw_input("Enter Name: ")
    	while(len(name)==0 or name[0] == ' '):
    		print "***Names can't begin with space or can be empty\n"
    		name=raw_input("Enter Name: ")
    	return name
    	
    #MAIN
    
    name = getname()
    age = getnumeric("Enter Age: ",1, 150)
    id_ = getnumeric("Enter ID: ", 1, 1000000)
    
    
    
    if id_==999999:
    	print "You are", name,", aged ", age, " next year you'll be ", age+1, ", with user id ", id_, ", you are the last user"	
    else:
    	print "You are", name,", aged ", age, " next year you'll be ", age+1, ", with user id ", id_, ",the next user is ", (id_ + 1)

  3. #213
    Join Date
    Apr 2008
    Beans
    221

    Re: [Beginner] Programming Challenge: 2

    I am starting to find these very interesting. Is it to late to enter?

  4. #214
    Join Date
    May 2008
    Beans
    Hidden!

    Re: [Beginner] Programming Challenge: 2

    I don't think they have an end, so probably not.

  5. #215
    Join Date
    Apr 2007
    Beans
    210

    Re: [Beginner] Programming Challenge: 2

    ^If that's the case, I want to see if there are anything to fix in my entries (aside from my horrible organization, format, and comments):

    PHP Code:
    import sys

    def 
    exit (userInput):
        if (
    userInput == "exit"):
            
    sys.exit(0)

    print 
    "If you want to exit any time, type exit"
    name raw_input("Enter name: ")
    exit(
    name)

    #remove all leading and trailing white spaces
    name name.strip()
    while (
    len(name) == 0):
        
    name raw_input("Enter name: ")
        
    name name.strip()

    #Truncate string name if over 20 characters
    #If there's a space in an the last nth character where n <= 20, then only truncate
    #until the last space.
    if (len(name) > 20):
        for 
    ii in xrange(19, -1, -1):
            if 
    name[ii].isspace(): 
                
    name name[0:ii]
                break
        else:
            
    name name[:20]

    age raw_input("Enter age: ")
    exit(
    age)

    #Check if age is larger than 0 or is an integer. If not, then prompt the user to
    #reinput the age.
    while (type(age) == str):
        try:
            
    age int(age)
            if (
    age 1):
                
    age raw_input ("Age has to be an integer larger than 0: ")
                exit(
    age)
        
    except (TypeErrorValueError):
            
    age raw_input ("Age has to be an integer larger than 0: ")
            exit(
    age)

    userID raw_input("Enter User ID: ")
    exit(
    userID)
    #Check if User ID is between 1-999999 (inclusive)
    while (type(userID) == str):
        try:
            
    userID int(userID)
            if (
    userID or userID 999999):
                
    userID raw_input ("User ID has to be an integer between 1-999999 (inclusive): ")
                exit(
    userID)
        
    except (TypeErrorValueError):
            
    userID raw_input ("User ID has to be an integer between 1-999999 (inclusive): ")
            exit(
    userID)

    #check if userID is 999999. If so, nextUserID is none.
    if (userID == 999999):
        
    nextUserID "none"
    else:
        
    nextUserID str(userID 1)

    print 
    "You are %s, aged %d next year you will be %d, with user id %d, the next user is %s" %\
            (
    nameageage 1userIDnextUserID
    I kinda took TypeError exception from the tutorial linked in the first page, but I'm not sure what it does. I could reproduce ValueError in the interactive mode, but how do I reproduce TypeError?

  6. #216
    Join Date
    Feb 2008
    Location
    Denmark
    Beans
    91

    Re: [Beginner] Programming Challenge: 2

    My C entry:

    PHP Code:
    /* Beginner Programming Challenge 2

       Write a program to take a person's forum name, age, forum user id (a
       postive integer equal to or between 1 and 999999). The program should ask
       for each datum individually, and not go to the next unless the previous
       was valid. If there is an error, it must prompt again until it is write
       or the program is halted. The entry "exit" should exit the program at any
       question.

       If all data is entered, it should print a sentence like:
          "You are LaRoza, aged 20 next year you will be 21, with user id
           266234, the next user is 266235." */

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    /* Clears the buffer. Used after fgets, because fgets appends a '\n' if it 
       doesn't exceed the length of the array (so there needs to be room for '\0').
       strchr returns a pointer to the occurence of '\n' and a NULL pointer if 
       there's no '\n'. If there's not room for a newline the buffer contains 
       letters we want erased. This is done by calling getchar until it reaches
       '\n'. If there is a '\n' it's replaced by a '\0', so the newline isn't
       printed later. */
    void clear_buffer(char *input)
    {
        
    char *i;

        
    strchr(input'\n');

        if(
    == NULL)
            while(
    getchar() != '\n')
                ;
        else
            *
    '\0';
    }

    /* Get the input using fgets. If it's exit, quit the program. Is the string
       empty or is the first character a space return 1 (error) and otherwise 0
       (succes). */
    int get_check(char *inputsize_t len_arr)
    {
        
    fgets(inputlen_arrstdin);
        
    clear_buffer(input);

        if(
    strcmp(input"exit") == 0) {
            exit(
    0);
        } else if(
    input[0] == ' '
               
    || input[0] == 10) {
            
    puts("Invalid input");
            return 
    1;
        }

        return 
    0;
    }

    /* Get name, then age and then ID by calling get_check. If it returns 0
       continue to the next input otherwise call get_check again. After
       succesfully acquiring name, age and ID display the message in the
       specified format. */
    int main()
    {
        
    char name[21];
        
    char age[4];
        
    char id[7];
        
    int check;
        
    int num_agenum_id;

        
    /* Get name. */
        
    do {
            
    printf("What's your name: ");
            
    check get_check(namesizeof(name));
        } while(
    check != 0);

        
    /* Get age. */
        
    do {
            
    printf("How old are you: ");
            
    check get_check(agesizeof(age));
            
    /* Convert the age string to a number, so it is easier to check
               if the input is a valid age print. */
            
    num_age atoi(age);

            if(
    num_age 1
            
    || num_age 122) {
                
    puts("Come on. We both know that ain't possible.");
                
    check 1;
            }
        } while(
    check != 0);

        
    /* Get ID. */
        
    do {
            
    printf("What's your user ID: ");
            
    check get_check(idsizeof(id));
            
    /* Convert the ID string to a number, so it is easier to check
               if the input is a valid ID and print. */
            
    num_id atoi(id);

            if(
    num_id 1
            
    || num_id 999999) {
                
    puts("User IDs must be between 1 and 999999");
                
    check 1;
            }
        } while(
    check != 0);

        
    /* Print desired output. */
        
    printf("\nYou are %s, "name);
        
    printf("aged %d next year you will be %d, "num_agenum_age 1);
        
    printf("with user id %d, the next user is %d.\n"num_idnum_id 1);

        return 
    0;

    EDIT: New and better version. It now clears the buffer, if the input's too long and removes the newline character fgets appends.
    Last edited by Nemooo; October 22nd, 2008 at 03:24 PM. Reason: New version

  7. #217
    Join Date
    Jun 2009
    Location
    Stavanger, Norway
    Beans
    6

    Re: [Beginner] Programming Challenge: 2

    Hello everyone!

    I would like to show what I can do. I am new to the forum and are not that experienced in programming. I am just doing these challenges to get better. This is my contribution to the challenge and I hope you will give me feedback on my work.

    PHP Code:
    /* Challenge 2 - Input Validation
    Author: Benjamin Nordtorp
    Language: C++
    Date: 2009-06-03
    */
    #include <iostream>
    #include <string>
    #include <ctype.h>
    using namespace std;

    string getNick()
    {
        
    bool validInput 0;
        
    string sNick;

        while (
    validInput == 0)
        {
            
    cout << "What's your nick? ";
            
    getline(cinsNick'\n');

            if (
    sNick == "quit")
                exit(
    0);

            
    // Nick is empty
            
    if (sNick.empty() == true)
                
    cout << "Nick not valid, nothing entered!\n";

            
    // Nick start with space
            
    else if (sNick.find(" "0) == 0)
                
    cout << "Nick not valid, starts with a space!\n";

            
    // Nick is over 20 chars, truncate
            
    else if (sNick.length() > 20)
            {
                
    cout << "Input not valid, nick is too long! Max 20 chars\n";
                
    cout << "Only the first 20 will be kept.\n ";
                
    sNick sNick.erase(20);
                
    validInput 1;
            }
            
            
    // Nick is okay 
            
    else
                
    validInput 1;        
        }
        return 
    sNick;
    }

    int getNumber(int nMinint nMaxstring whatToGet)
    {
        
    bool validInput 0;
        
    string sNumber "";
        
    int nNumber;

        while (
    validInput == 0)
        {
            
    cout << "\nWhat's your " << whatToGet << "? ";
            
    getline(cinsNumber'\n');

            if (
    sNumber == "quit")
            {
                
    cout << "\n\nThank you, please come again";
                exit(
    0);
            }
            else 
                
    nNumber atoisNumber.c_str() );
        
            
    // Input valid...
            
    if (cin.good())
            {
                
    // ...but not in the range
                
    if (nNumber nMin || nNumber nMax)
                {
                    
    cout << "Input not valid, " << whatToGet << " between " 
                         
    << nMin << " and " << nMax << "\n";
                }
                
    // ...and here it is
                
    else
                    
    validInput 1;
            }
            else if (
    cin.fail())
            {
                
    cout << "That is not a valid number\n";
                
    cin.clear();
                
    cin.ignore(40'\n');
            }
        } 
        return 
    nNumber;
    }

    int main()
    {
        
    cout << "Welcome! Please supply some information about yourself\n\n";

        
    string sNick getNick();
        
    int nAge getNumber(1100"age");
        
    int nMemberID getNumber(1999999"memberID");

        
    cout << "You are " << sNick
             
    << ", aged " << nAge
             
    << ", next year you will be " << nAge+1
             
    << "\nUser id: " << nMemberID
             
    << " the next user is " << nMemberID+1;

        
    // Just to pause the program, before exiting
        
    cin.get();

        return 
    0;


Page 22 of 22 FirstFirst ... 12202122

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •