• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

I started to learn to program 4 days ago. I made a few programs. What do you think?

Status
Not open for further replies.

hwateber

Member
Pretty good for four days man, keep it up! I think my biggest thing with Java was accidentally typing "pubic class" lol.
 

RedShift

Member
Maybe this won't be a huge amount of help but I made a quick mock up of the questionnaire program rewritten in a more object oriented way that might help show you how it'll make your code much more maintainable and reusable.

The basic idea is to move the storing of questions and their answers, and the process of asking the user into a Question class, and to move the logic of storing a list of questions and counting a users score into a Questionnaire class.

AskProgram.java:
Code:
public class AskProgram
{
  public static void main(String[] args) {
    Questionnaire questionnaire = new Questionnaire();

    questionnaire.addQuestion(
      "What is an animal that purrs?",
      "Cat"
    );
    questionnaire.addQuestion(
      "What is 12 times 12?",
      "144"
    );

    questionnaire.play();
  }
}

Questionnaire.java:
Code:
import java.util.ArrayList;
import java.util.List;

public class Questionnaire {
  private List<Question> questions = new ArrayList<Question>();

  public void addQuestion(String question, String answer) {
    questions.add(new Question(question, answer));
  }

  public void play() {
    int correctAnswers = 0;

    for (Question question : questions) {
      if (question.userAnswersCorrectly()) {
        correctAnswers++;
      }
    }

    System.out.println(
            "You answered " + correctAnswers + " out of "
          + questions.size() + " questions correctly."
    );
  }
}

Question.java:
Code:
import java.util.Scanner;

public class Question {
  private String question;
  private String answer;

  public Question(String question, String answer) {
    this.question = question;
    this.answer = answer;
  }


  public boolean userAnswersCorrectly() {
    System.out.println(question);

    Scanner scanner = new Scanner(System.in);
    String theirAnswer = scanner.nextLine();

    return theirAnswer.toUpperCase().equals(answer.toUpperCase());
  }
}

This might seem like a more complicated way of doing this at first, but now adding questions is as easy as adding the line:

questionnaire.addQuestion("What is the meaning of life, the universe and everything?", "42");

You seem to really have got the hang of writing programs in a non object oriented style (I can't remember the name for it), so I'd definitely recommend starting to practice using classes and objects to break your code up into smaller chunks.

The other thing in there you might not have seen yet is Lists. They're also a good thing for you to look at now as well, and collections in general.
 

mclem

Member
can someone program a program where you can just write what you want it to do and it will program it for you?

Well, high-level programming languages are already abstractions of lower-level languages which are in turn abstractions of "machine language", so in a way, that already is the case. It's just that we haven't reached that high a level as to be able to use natural language quite yet :p

Natural language also depends on cultural context, has many multiple ways to express ideas, and can often be kinda imprecise. You'd need some crazy AI to parse it, or impose so many rules where it's not really " natural " language anymore.

Inform is a programming language to create text adventures (compiled to the same format Infocom used). Inform 7, however, is a major overhaul to a natural-language programming style. It's still got hard rules, of course, but it's really quite readable, even to a non-programmer.

Here's a snippet of code from an earlier version of Inform:

Code:
! ! ============================================================================ !
!   Cloak of Darkness - a simple demonstration of Interactive Fiction
!       This version for Inform written by Roger Firth on 17Sep99
! ============================================================================ !

Constant Story      "Cloak of Darkness";
Constant Headline   "^A basic IF demonstration.^";
Constant MANUAL_PRONOUNS;
Constant MAX_SCORE  2;

Include "Parser";
Include "VerbLib";

! ============================================================================ !

Object  foyer "Foyer of the Opera House"
  with  description
           "You are standing in a spacious hall, splendidly decorated in red
            and gold, with glittering chandeliers overhead. The entrance from
            the street is to the north, and there are doorways south and west.",
        s_to  bar,
        w_to  cloakroom,
        n_to
           "You've only just arrived, and besides, the weather outside
            seems to be getting worse.",
  has   light;

Object  cloakroom "Cloakroom"
  with  description
           "The walls of this small room were clearly once lined with hooks,
            though now only one remains. The exit is a door to the east.",
        e_to  foyer,
  has   light;

Object  hook "small brass hook" cloakroom
  with  name 'small' 'brass' 'hook' 'peg',
        description [;
            print "It's just a small brass hook, ";
            if (self == parent(cloak)) "with a cloak hanging on it.";
            "screwed to the wall.";
            ],
  has   scenery supporter;

(...)

And here's roughly the same code in Inform 7.

Code:
"Cloak of Darkness"

The story headline is "A basic IF demonstration."

The maximum score is 2.

[Whatever room we define first becomes the starting room of the game,
in the absence of other instructions:]

Foyer of the Opera House is a room.  "You are standing in a spacious hall,
splendidly decorated in red and gold, with glittering chandeliers overhead.
The entrance from the street is to the north, and there are doorways south and west."

Instead of going north in the Foyer, say "You've only just arrived, and besides,
the weather outside seems to be getting worse."

[We can add more rooms by specifying their relation to the first room.
Unless we say otherwise, the connection will automatically be bidirectional,
so "The Cloakroom is west of the Foyer" will also mean "The Foyer is east of the Cloakroom":]

The Cloakroom is west of the Foyer.
"The walls of this small room were clearly once lined with hooks, though now only one remains.
The exit is a door to the east."

In the Cloakroom is a supporter called the small brass hook.
The hook is scenery. Understand "peg" as the hook.

[Inform will automatically understand any words in the object definition
("small", "brass", and "hook", in this case), but we can add extra synonyms
with this sort of Understand command.]

The description of the hook is "It's just a small brass hook,
[if something is on the hook]with [a list of things on the hook]
hanging on it[otherwise]screwed to the wall[end if]."

[This description is general enough that, if we were to add other hangable items
to the game, they would automatically be described correctly as well.]

The Bar is south of the Foyer. The printed name of the bar is "Foyer Bar".

(...)

There's something a bit beautiful about Inform 7 code, I think.
 

FoxSpirit

Junior Member
If you really want to learn about proper programming structure, do this:

https://class.coursera.org/programdesign-002

Don't be fooled about how easy this looks at first and that the method seems a bit unintuitive and overdone for small programs.
By week 8, there is blood on your keyboard.

You will learn designing programs of arbitrary length and complexity and doing it in a way that it always remains structured, reviewable and editable.
Also, Gregor Kiczales is a great lecturer, I loved listening to him in the videos.
 

Lagamorph

Member
I remember hating Java at University....

Work have got me learning up on Powershell scripting now though which I'm enjoying much more.
 
Try to get into the habit of naming your classes, variables, and methods (functions) in a specific style. Sure, it's only cosmetic, but I think it really helps in the long run.

For example, if you follow Java coding conventions, there's a big difference between Random, random, and random(). If you look at a lot of code, you will probably encounter all three of those. A programmer can immediately tell the difference between all three just by looking at the name, and it helps with understanding the code.


I only mentioned that because your variable names were not in camelCase, which isn't a big deal, but I think it's a good idea to get into the habit of consistent naming early.
 

jon bones

hot hot hanuman-on-man action
Try to get into the habit of naming your classes, variables, and methods (functions) in a specific style. Sure, it's only cosmetic, but I think it really helps in the long run.

For example, if you follow Java coding conventions, there's a big difference between Random, random, and random(). If you look at a lot of code, you will probably encounter all three of those. A programmer can immediately tell the difference between all three just by looking at the name, and it helps with understanding the code.


I only mentioned that because your variable names were not in camelCase, which isn't a big deal, but I think it's a good idea to get into the habit of consistent naming early.

This is a good post - naming conventions are important! Get into the habit of keeping methods small and naming them for exactly what they do:

AddNumbers()
SaveFileToDatabase()
etc

And your variables, too:
FirstName
StreetAddress
etc
 

mclem

Member
i don't know, it seems awfully verbose. i like python's style of blending readability with the flexibility of low-level code.

Verbosity is generally regarded as a positive in the world of IF!

(To the extent that one of the controls for a user is to determine the amount of text displayed on entering a room. SUPERBRIEF would be just the name, BRIEF is the full description first time, name subsequent times. VERBOSE is full description every time. Pretty much any IF user would turn on VERBOSE straight away!)
 

Relix

he's Virgin Tight™
This is a good post - naming conventions are important! Get into the habit of keeping methods small and naming them for exactly what they do:

AddNumbers()
SaveFileToDatabase()
etc

And your variables, too:
FirstName
StreetAddress
etc

Variables should be camel case though (firstName, lastName, etc)
 

Palculator

Unconfirmed Member
Small tip: I see you do
Code:
if (userunits.equalsIgnoreCase("millimeters")) {...}
Quite often. Problem is that userunits, the variable, might be null in some cases and you'd get the dreaded NullPointerException. To prevent this you can just do:
Code:
if ("millimeters".equalsIgnoreCase(userunits)) {...}
Since you're using the string literal "milimeters" it's guaranteed to be non-null.

For the generic case there's also Objects.equals(a, b) that performs checks using the .equals-method and doesn't fail if either is null.
 
Status
Not open for further replies.
Top Bottom