Questions about a MasterQuize program

Hi, everyone.
I got a in-class case study program like this in the class:
* This class stores/represents a question that has one of two
* answers: True or False.
* <p></p>
* It needs to track the following information:
* <ul>
* <li>Question text</li>
* <li>Correct answer</li>
* <li>The user's answer to the question</li>
* <li>Points value</li>
* <li>Category</li>
* <li>Difficulty rating</li>
* </ul>
// Our question should allow us to do the following:
// - Create question (constructor) -- may be overloaded
// - Print (display) question
// - Check client's answer for correctness
// - Get points value for question (0 or max)
//   - Add "No-BS" grading option
// - Getting client's answer
// - Check to see if answered by client
public class TrueFalseQuestion
    // Class constants (to simplify changes to common values)
    public static final int MIN_DIFFICULTY_LEVEL = 1;
    public static final int MAX_DIFFICULTY_LEVEL = 5;
    public static final int DEFAULT_DIFFICULTY_LEVEL = 1;
    public static final int DEFAULT_POINT_VALUE = 1;
    public static final String DEFAULT_CATEGORY_VALUE = "none";
    // Class instance variables
    private String questionText;
    private String correctAnswer;
    private String userAnswer;
    private int pointsValue;
    private String category;
    private int difficultyLevel; // TODO: Set a range for difficulty levels
     * @param text The literal wording of this question
     * @param answer The correct answer for this question
     * @param pts The total points available for this question
     * @param ctgry Category keyword for this question
     * @param level The perceived/intended difficulty level of this question
     * <p></p>
     * Defines a TrueFalseQuestion object.
    public TrueFalseQuestion (String text, String answer, int pts, String ctgry, int level)
        // Set starting values for all instance variables
        questionText = text.trim();
        correctAnswer = answer.trim();
        userAnswer = null; // No user answer supplied yet
        if (pts >= 1) // We assume that every problem is worth at least 1 point
            pointsValue = pts;
        else
            pointsValue = DEFAULT_POINT_VALUE;
        category = ctgry.trim();
        if (level >= MIN_DIFFICULTY_LEVEL && level <= MAX_DIFFICULTY_LEVEL) // within range
            difficultyLevel = level;
        else
            difficultyLevel = DEFAULT_DIFFICULTY_LEVEL;
    // Simplified (overloaded) constructors
     * @param text The literal wording of this question
     * @param answer The correct answer for this question
     * @param pts The total points available for this question
     * <p></p>
     * Defines a TrueFalseQuestion with default values for category and difficulty level.
    public TrueFalseQuestion (String text, String answer, int pts)
        // Call pre-existing constructor with default category and difficulty
        this(text, answer, pts, DEFAULT_CATEGORY_VALUE, DEFAULT_DIFFICULTY_LEVEL);
     * @param text The literal wording of this question
     * @param answer The correct answer for this question
     * <p></p>
     * Defines a TrueFalseQuestion with the default point value, default category,
     * and default difficulty level.
    public TrueFalseQuestion (String text, String answer)
        // Call pre-existing constructor with default points, category and difficulty
        this(text, answer, DEFAULT_POINT_VALUE, DEFAULT_CATEGORY_VALUE,
             DEFAULT_DIFFICULTY_LEVEL);
     * @param text The literal wording of this question
     * @param answer The correct answer for this question
     * @param pts The total points available for this question
     * @param ctgry Category keyword for this question
     * <p></p>
     * Defines a TrueFalseQuestion with the default difficulty level.
    public TrueFalseQuestion (String text, String answer, int pts, String ctgry)
        // Call pre-existing constructor with default points, category and difficulty
        this(text, answer, pts, ctgry,
             DEFAULT_DIFFICULTY_LEVEL);
     * @param text The literal wording of this question
     * @param answer The correct answer for this question
     * @param ctgry Category keyword for this question
     * <p></p>
     * Defines a TrueFalseQuestion with the default point value and the default
     * difficulty level.
    public TrueFalseQuestion (String text, String answer, String ctgry)
        // Use default points and difficulty
        this(text, answer, DEFAULT_POINT_VALUE, ctgry, DEFAULT_DIFFICULTY_LEVEL);
     * @param text The literal wording of this question
     * @param answer The correct answer for this question
     * @param pts The total points available for this question
     * @param level The perceived/intended difficulty level of this question
     * <p></p>
     * Defines a TrueFalseQuestion with the default value for the question category.
    public TrueFalseQuestion (String text, String answer, int pts, int level)
        // Use default category
        this(text, answer, pts, DEFAULT_CATEGORY_VALUE, level);
    // Clients can invoke this method to retrieve the text of the current question.
    // We chose to return the text instead of printing it; this allows the client
    // to decide how it should be presented (via a GUI, over a network, etc.)
    public String getQuestion ()
        return questionText;
    // This method allows the client to store the user's answer inside the
    // TrueFalseQuestion object for easy comparison
    public void submitAnswer (String ans)
        userAnswer = ans;
    // This method reports whether the submitted answer matches the correct answer
    public boolean answerIsCorrect(String userAns) // This version does all the work
        if (userAns == null) // No response from user (yet)
            return false;
        else
            // Normalize and compare answers
            char key = normalize(correctAnswer); // Get 't' or 'f'
            char ans = normalize(userAns); // Get 't' or 'f'
            return (key == ans);
    public boolean answerIsCorrect ()
        return answerIsCorrect(userAnswer); // Call previously-defined version
    public int getPointsValue()
        return pointsValue;
    // Return the points awarded for the user's answer. This method does
    // NOT support partial credit; answers are either correct or incorrect.
    // If the "No-BS" option is selected, blank (unanswered) questions receive
    // 1 point automatically; otherwise, the score will be either 0 or the
    // question's normal points value.
    public int getPointsEarned(boolean useNoBSRule)
System.out.println("useNoBS: " + useNoBSRule + "\tuserAnswer: " + userAnswer + "\tcorrectAnswer: " + correctAnswer);
        if (useNoBSRule && (userAnswer == null))
            return 1;
        else if (userAnswer == null)
            return 0; // Without "No-BS", treat blank problems as incorrect
        if (answerIsCorrect() == false)
            return 0;
        else
            return pointsValue;
    // This method returns true if the user has submitted an answer
    // for this question (regardless of whether that answer is correct)
    public boolean hasBeenAnswered ()
        return (userAnswer != null);
    // Private helper method to convert all answers to single lowercase
    // letters (in this case, 't' for TRUE and 'f' for FALSE)
    private char normalize (String input)
         if (input != null)
              input = input.trim(); // Remove leading whitespace
              input = input.toLowerCase();
              return input.charAt(0);
         else
              return ' ';
import java.util.*;
* This class represents a complete test or quiz.
* Data stored:
* - List of questions
* - Total score earned
* - Total score possible
* - Name/title of test
* - Instructions
*  - Category/class assignment
*  - Student (test-taker) name
*  - Date test is/was taken
*  - Time started
*  - Time completed
*  - Maximum time allotted
*  - (List of) Maximum attempts per question
*  - List of attempts per question
*  - List of difficulty ratings per question
*  - Assignment weight
* Methods:
* - Constructor
* - Add question
* - Display question
* - Display test
* - Display instructions
*      - Generate random exam
* - Take/administer test
* - Get score
* STUFF TO DO:
* - Add time/date restrictions
* - Add network access restrictions
* - Add other restrictions/allowances?
* @author (your name)
* @version (a version number or a date)
public class Test
    // Class constant
    public static final int MAX_NUMBER_OF_QUESTIONS = 10;
    // Class instance variables
    private String testName;
    private int scoreEarned; // What the student earned on the exam
    private int scorePossible; // Total point values of all questions
    private String instructions; // Exam header text
    private ArrayList<TrueFalseQuestion> questions; // Create inside constructor
    // Methods
    public Test (String name, String instr)
        testName = name;
        scoreEarned = 0;
        scorePossible = 0;
        instructions = instr;
        questions = new ArrayList<TrueFalseQuestion>(); //[MAX_NUMBER_OF_QUESTIONS];
    public String getInstructions()
        return instructions;
    public int getScore()
        return scoreEarned;
    public void addQuestion (TrueFalseQuestion q)
        scorePossible += q.getPointsValue();
        questions.add(q); // Automatically append question to end of test
    public String displayQuestion (int position)
        if (position < questions.size())
            return (position+1) + ". " + questions.get(position).getQuestion();
        else
            return null;
    public String displayTest ()
        String result = "";
        for (int i = 0; i < questions.size(); i++)
            result += (i+1) + ". (";
            TrueFalseQuestion t = questions.get(i);
            result += t.getPointsValue();
            result += " points)\n\n" + displayQuestion(i);
            result += "\n\n";
        return result;
    // Get test length (number of questions)
    public int length ()
         return questions.size();
    // Submit answer to a specific question
    public boolean answer(int number, String a)
         // Question numbers run from 0-(max-1) -- THIS WAS AN OFF-BY-ONE ERROR AT FIRST
         if (number >= 0 && number < questions.size())
              TrueFalseQuestion t = questions.get(number);
              t.submitAnswer(a);
              return true; // Question was answered
         else
              return false; // Unable to answer (nonexistent) question
    // Score exam
    public void scoreExam (boolean useNoBS)
         scoreEarned = 0;
         for (int i = 0; i < questions.size(); i++) // For each question in exam
              TrueFalseQuestion t = questions.get(i); // get current question
              scoreEarned += t.getPointsEarned(useNoBS);
}// Test harness for the Test and *Question classes
import java.util.*;
public class QuizDriver
     public static void main(String[] args)
          // Create a new Test object
          Test exam = new Test("Sample Exam", "Select the correct answer for each question");
          setUp(exam);
          Scanner sc = new Scanner(System.in);
          System.out.println(exam.getInstructions());
          // Administer exam
          for (int i = 0; i < exam.length(); i++)
               // Print out current question
               System.out.println(exam.displayQuestion(i));
               // Get user answer
               System.out.print("Your answer: ");
               String ans = sc.nextLine();
               if (ans.equals("")) // Handle blank responses for unanswered questions
                    ans = null;
               exam.answer(i, ans);
          // Get exam results
          exam.scoreExam(true);
          System.out.println("Your final score was " + exam.getScore() + " points.");
     private static void setUp (Test t)
          TrueFalseQuestion x = new TrueFalseQuestion("The sky is blue.", "true", 2);
          t.addQuestion(x);
          x = new TrueFalseQuestion("The first FORTRAN compiler debuted in 1957", "true", 5);
          t.addQuestion(x);
          x = new TrueFalseQuestion("Spock was a Vulcan", "false", 3);
          t.addQuestion(x);
}This program is far from finishing.
I have many questions about this program, but let me ask this one first:
In the TrueFalseQeustion class, why are there so many constructors? What is the purpose of setting some of the variables to default values?
Thank you very much!!!
Edited by: Terry001 on Apr 16, 2008 10:02 AM

newark wrote:
Stop ignoring the error messages. You seem to think that an error message means you're doing the assignment wrong. It's probably a simple fix. Post the exact error messages, as well as the code that corresponds to them. The error message will tell you exactly what line the problem occurs on, so you know right where to look.Hi,
After some modifications, the program now gives me the result the assignment wants when I run it. But I still have trouble with the MultipleChoiceQuestion class
Here is the complete program
QuizDriver class
// Test harness for the Test and *Question classes
import java.util.*;
public class QuizDriver
     public static void main(String[] args)
          // Create a new Test object
          Test exam = new Test("Sample Exam", "Select the correct answer for each question");
          setUp(exam);
          Scanner sc = new Scanner(System.in);
          System.out.println(exam.getInstructions());
          // Administer exam
          for (int i = 0; i < exam.length(); i++)
               // Print out current question
               System.out.println(exam.displayQuestion(i));
               // Get user answer
               System.out.print("Your answer: ");
               String ans = sc.nextLine();
               if (ans.equals("")) // Handle blank responses for unanswered questions
                    ans = null;
               exam.answer(i, ans);
          // Get exam results
          exam.scoreExam(true);
          System.out.println("Your final score was " + exam.getScore() + " points.");
     private static void setUp (Test t)
                               Question x;
          x = new TrueFalseQuestion("The sky is blue.", "true", 2);
          t.addQuestion(x);
          x = new TrueFalseQuestion("The first FORTRAN compiler debuted in 1957", "true", 5);
          t.addQuestion(x);
          x = new TrueFalseQuestion("Spock was a Vulcan", "false", 3);
          t.addQuestion(x);
          x = new MultipleChoiceQuestion("What is the color of the car\na.Red\nb.Green", "a. Red", 3);
          t.addQuestion(x);
          x = new MultipleChoiceQuestion("What is the name of this class\na.CSE110\nb.CSE114", "b, CSE114", 3);
          t.addQuestion(x);
}Test
public class Test
    // Class constant
    public static final int MAX_NUMBER_OF_QUESTIONS = 10;
    // Class instance variables
    private String testName;
    private int scoreEarned; // What the student earned on the exam
    private int scorePossible; // Total point values of all questions
    private String instructions; // Exam header text
    private ArrayList<Question> questions; // Create inside constructor
    // Methods
    public Test (String name, String instr)
        testName = name;
        scoreEarned = 0;
        scorePossible = 0;
        instructions = instr;
        questions = new ArrayList<Question>(); //[MAX_NUMBER_OF_QUESTIONS];
    public String getInstructions()
        return instructions;
    public int getScore()
        return scoreEarned;
    public void addQuestion (Question q)
        scorePossible += q.getPointsValue();
        questions.add(q); // Automatically append question to end of test
    public String displayQuestion (int position)
        if (position < questions.size())
            return (position+1) + ". " + questions.get(position).getQuestion();
        else
            return null;
    public String displayTest ()
        String result = "";
        for (int i = 0; i < questions.size(); i++)
            result += (i+1) + ". (";
            Question t = questions.get(i);
            result += t.getPointsValue();
            result += " points)\n\n" + displayQuestion(i);
            result += "\n\n";
        return result;
    // Get test length (number of questions)
    public int length ()
         return questions.size();
    // Submit answer to a specific question
    public boolean answer(int number, String a)
         // Question numbers run from 0-(max-1) -- THIS WAS AN OFF-BY-ONE ERROR AT FIRST
         if (number >= 0 && number < questions.size())
              Question t = questions.get(number);
              t.submitAnswer(a);
              return true; // Question was answered
         else
              return false; // Unable to answer (nonexistent) question
    // Score exam
    public void scoreExam (boolean useNoBS)
         scoreEarned = 0;
         for (int i = 0; i < questions.size(); i++) // For each question in exam
              Question t = questions.get(i); // get current question
              scoreEarned += t.getPointsEarned(useNoBS);
}Question
public class Question
// Class constants
  public static final int MIN_DIFFICULTY_LEVEL = 1;
  public static final int MAX_DIFFICULTY_LEVEL = 5;
  public static final int DEFAULT_DIFFICULTY_LEVEL = 1;
  public static final int DEFAULT_POINT_VALUE = 1;
  public static final String DEFAULT_CATEGORY_VALUE = "none";
  // Class instance variables
  protected String questionText;
  protected String correctAnswer;
  protected String userAnswer;
  protected int pointsValue;
  protected String category;
  protected int difficultyLevel; //TODO: set a range for difficulty levels
  // Constructors
  public Question (String text, String answer, int pts, String ctgry, int level)
      questionText = text.trim();
      correctAnswer = answer.trim();
      userAnswer = null;
      if (pts >= 1)
          pointsValue = pts;
        else
            pointsValue = DEFAULT_POINT_VALUE;
        category = ctgry.trim();
        if (level >= MIN_DIFFICULTY_LEVEL && level <= MAX_DIFFICULTY_LEVEL)
            difficultyLevel = level;
        else
            difficultyLevel = DEFAULT_DIFFICULTY_LEVEL;
    // Overloaded (simplied) constructors
    public Question (String text, String answer, int pts)
        this(text, answer, pts, DEFAULT_CATEGORY_VALUE, DEFAULT_DIFFICULTY_LEVEL);
    public Question (String text, String answer, int pts, String ctgry)
        this(text, answer, pts, ctgry, DEFAULT_DIFFICULTY_LEVEL);
    public Question (String text, String answer, String ctgry)
        this(text, answer, DEFAULT_POINT_VALUE, ctgry, DEFAULT_DIFFICULTY_LEVEL);
    public Question (String text, String answer, int pts, int level)
        this(text, answer, pts, DEFAULT_CATEGORY_VALUE, level);
    // Methods
    public String getQuestion ()
        return questionText;
    // Use this method to store user answers
    public void submitAnswer (String ans)
        userAnswer = ans;
    public boolean answerIsCorrect (String userAns)
        if (userAns == null)
            return false;
        else
            // Normalize and compare answers
            char key = normalize (correctAnswer); //Get the first letter of an answer
            char ans = normalize (userAns); //Get the first letter of an answer
            return (key == ans);
    public boolean answerIsCorrect ()// Why do we need two answerisCorrect() methods?
        return answerIsCorrect (userAnswer);
    public int getPointsValue ()
        return pointsValue;
    public int getPointsEarned (boolean userNoBSRule)
        System.out.println ("useNoBS: " + userNoBSRule + "\tuseAnswer: " + userAnswer + "\tcorrectAnswer: " + correctAnswer);
        if (userNoBSRule && (userAnswer == null))
            return 1;
        else if (userAnswer == null)
            return 0;
        if (answerIsCorrect() == false)
            return 0;
        else
            return pointsValue;
    public String getCorrectAnswer ()
        return correctAnswer;
    public boolean hasBeenAnswered ()
        return (userAnswer != null);
    private char normalize (String input)
        if (input != null)
            input = input.trim();
            input = input.toLowerCase();
            return input.charAt(0);
        else
            return ' ';
       TrueFalseQuestion
public class TrueFalseQuestion extends Question
  public TrueFalseQuestion (String text, String answer, int pts, String ctgry, int level)
      super(text, answer, pts, ctgry, level);
    public TrueFalseQuestion (String text, String answer, int pts)
        super(text, answer, pts, DEFAULT_CATEGORY_VALUE, DEFAULT_DIFFICULTY_LEVEL);
    public TrueFalseQuestion (String text, String answer, int pts, String ctgry)
        super(text, answer, pts, ctgry, DEFAULT_DIFFICULTY_LEVEL);
    public TrueFalseQuestion (String text, String answer, String ctgry)
        super(text, answer, DEFAULT_POINT_VALUE, ctgry, DEFAULT_DIFFICULTY_LEVEL);
    public TrueFalseQuestion (String text, String answer, int pts, int level)
        super(text, answer, pts, DEFAULT_CATEGORY_VALUE, level);
    // Methods
    public String[] getPossibleAnswerChoice ()
        String[] possibleAnswerChoice = {"true", "false"};
        return possibleAnswerChoice;
} MultipleChoiceQuestion
public class MultipleChoiceQuestion extends Question
   public MultipleChoiceQuestion (String text, String answer, int pts, String ctgry, int level)
       super(text, answer, pts, ctgry, level);
    public MultipleChoiceQuestion (String text, String answer, int pts)
        super(text, answer, pts, DEFAULT_CATEGORY_VALUE, DEFAULT_DIFFICULTY_LEVEL);
    public MultipleChoiceQuestion (String text, String answer, int pts, String ctgry)
        super(text, answer, pts, ctgry, DEFAULT_DIFFICULTY_LEVEL);
    public MultipleChoiceQuestion (String text, String answer, String ctgry)
        super(text, answer, DEFAULT_POINT_VALUE, ctgry, DEFAULT_DIFFICULTY_LEVEL);
    public MultipleChoiceQuestion (String text, String answer, int pts, int level)
        super(text, answer, pts, DEFAULT_CATEGORY_VALUE, level);
    // Methods
    String possibleAnswers;
    public String getPossibleAnswers ()
        return possibleAnswers;
    public void addAnswerChoice (String answerChoice)
        String ansChoice = answerChoice;
        questionText += "\nansChoice";
        possibleAnswers = answerChoice;
    public void printAnswerChoice ()
        System.out.println (questionText);
} I don't understand why the assignment wants me to build a method in the MultpleChoiceQuestion class to store the potential answer choices, I can make the program display the potential answer choices by including them in the questionText as following in the QuizDriver class
Question x;
x = new MultipleChoiceQuestion("What is the color of the car\na.Red\nb.Green", "a. Red", 3);
t.addQuestion(x); I don't know how to allow the client to construct the list of answer choices one at a time(add one potential answer choice by calling the addAsnwerChoices() method once)
Here are a few original sentences of my assignment which describe what I should do with the MultipleChoiceQuestion class
Using TrueFalseQuestion as a model, develop a new MultipleChoiceQuestion class that can be used to represent a problem where the user must select one of several answer choices (e.g., "Select answer (a), (b), (c), or (d)."). This new question type should have all of the same externally-visible functionality as TrueFalseQuestion, except that it must:
maintain a list of potential answer choices
provide a method that allows the client to construct the list of answer choices one at a time (i.e., the client should be able to call an addAnswerChoice() method to pass a new answer option to the MultipleChoiceQuestion.)
display (as part of the question text) the list of answer choices with appropriate letters ("abcd" instead of "0123") I don't understand what these sentences mean.
1. "Maintain a list of potential answer choices"-- this reminds me of the getPossibleAnswerChoice() method in the TrueFalseQuestion class
public String[] getPossibleAnswerChoice ()
        String[] possibleAnswerChoice = {"true", "false"};
        return possibleAnswerChoice;
    }I wonder that if the potential answer choices I have to store in the MultipleChoiceQuestion class are only letters "a", "b", "c", "d", etc, or include the answer text coming after the letters(eg. a.Red, b.Green)
2. "provide a method that allows the client to construct the list of answer choices one at a time". How do I achieve the functionality "one at a time"? Do I need to pass the input of the client (a potential answer choice) to the variable of the method which stores the list of potential answers?
3. "display (as part of the question text) the list of answer choices with appropriate letters". My question here is that: When the client type in one possible answer, should I append it to the variable questionText? (So I use the questionText variable in the methods of the first and second steps)
Thank you very much for your nice help!
Edited by: Terry001 on Apr 21, 2008 8:01 AM

Similar Messages

  • Round trip workflow with proxies between Premiere and AE / a more general question about how these programs work?

    Hi all,
    I'm new to editing with proxies in Premiere and have some questions about how to handle the relationship with After Effects. Say I have a rough cut (with proxies) and I want to send it to AE to do some effects. The simplest thing to do seems to be to replace the proxies with the originals in Premiere, send the project to AE and do my thing. But if I then want to send the project back to Premiere, it will involve the original files, which are too machine-intensive for me to edit. In theory, it seems like there should be a way to send the project with original footage to AE, do effects, send it back to Premiere, and then replace it with proxies to do further editing while retaining the effects.
    This leads to a confusion about how AE works. When I do an effect, am I correct in assuming that it does nothing to the original file? If that's the case, it seems like it shouldn't matter (in the editing stage) what file AE "applies" an effect to (proxy or original). But I feel like there's a hitch in this workflow. The same question could also be asked about going back and forth in Speed Grade.
    Perhaps there is no real answer to this and the best option is to save effects and grading for after I have picture lock, but sometimes that's not entirely possible or convenient, etc.
    Hopefully this makes some sense—It's a little hard to explain.
    Thanks.

    Hi Mark,
    Here are the specific sections of the manual that should give you the best explanation regarding the Check out/in workflow for FCP projects in Final Cut Server:
    Check out:
    http://documentation.apple.com/en/finalcutserver/usermanual/#chapter=7%26section =5
    Editing:
    http://documentation.apple.com/en/finalcutserver/usermanual/#chapter=7%26section =6
    Check in:
    http://documentation.apple.com/en/finalcutserver/usermanual/#chapter=7%26section =7
    -Daniel

  • [SOLVED]Questions about a shell program and about shell: files, regexp

    Hello, I'm writing this little program in shell:
    #!/bin/bash
    # Synopsis:
    # Read from an inputfile each line, which has the following format:
    # lllnn nnnnnnnnnnnnllll STRING lnnnlll n nnnn nnnnnnnnn nnnnnnnnnnnnnnnnnnnn ll ll
    # where:
    # n is a <positive int>
    # l is a <char> (no special chars)
    # the last set of ll ll could be:
    # - NV
    # - PV
    # Ex:
    # AVO01 000060229651AVON FOOD OF ARKHAM C A S060GER 0 1110 000000022 00031433680006534689 NV PV
    # The program should check, for each line of the file, the following:
    # I) If the nn of character lllnn (beggining the line) is numeric,
    # this is, <int>
    # II) If the character ll ll is NV (just one set of ll) then
    # copy that line in an outputfile, and add one to a counter.
    # III) If the character ll ll is NP (just one set of ll) then
    # copy that line in an outputfile, and add one to a counter.
    # NOTICE: could be just one ll. Ex: [...] NV [...]
    # [...] PV [...]
    # or both Ex: [...] NV PV [...]
    # Execution (after generating the executable):
    # ./ inputfile outputfileNOM outputfilePGP
    # Check the number of arguments that could be passed.
    if [[ ${#@} != 3 ]]; then
    echo "Error...must be: myShellprogram <inputfile> <outputfileNOM> <outputfilePGP>\n"
    exit
    fi
    #Inputfile: is in position 1 on the ARGS
    inputfile=$1
    #OutputfileNOM: is in position 2 on the ARGS
    outputfileNOM=$2
    #OutputfilePGP: is in position 3 on the ARGS
    outputfilePGP=$3
    #Main variables. Change if needed.
    # Flags the could appear in the <inputfile>
    # ATTENTION!!!: notice that there is a white space
    # before the characters, this is important when using
    # the regular expression in the conditional:
    # if [[ $line =~ $NOM ]]; then [...]
    # If the white space is NOT there it would match things like:
    # ABCNV ... which is wrong!!
    NOM=" NV"
    PGP=" PV"
    #Counters of ocurrences
    countNOM=0;
    countPGP=0;
    #Check if the files exists and have the write/read permissions
    if [[ -r $inputfile && -w $outputfileNOM && -w $outputfilePGP ]]; then
    #Read all the lines of the file.
    while read -r line
    do
    code=${line:3:2} #Store the code (the nnn) of the "llnnn" char set of the inputfile
    #Check if the code is numeric
    if [[ $code =~ ^[0-9]+$ ]] ; then
    #Check if the actual line has the NOM flag
    if [[ $line =~ $NOM ]]; then
    echo "$line" >> "$outputfileNOM"
    (( ++countNOM ))
    fi
    #Check if the actual line has the PGP flag
    if [[ $line =~ $PGP ]]; then
    echo "$line" >> "$outputfilePGP"
    (( ++countPGP ))
    fi
    else
    echo "$code is not numeric"
    exit
    fi
    done < "$inputfile"
    echo "COUN NON $countNOM"
    echo "COUN PGP $countPGP"
    else
    echo "FILE: $inputfile does not exist or does not have read permissions"
    echo "FILE: $outputfileNOM does not exist or does not have write permissions"
    echo "FILE: $outputfilePGP does not exist or does not have write permissions"
    fi
    I have some questions:
    I) When I do:
    if [[ -r $inputfile && -w $outputfileNOM && -w $outputfilePGP ]]; then
    else
    echo "FILE: $inputfile does not exist or does not have read permissions"
    echo "FILE: $outputfileNOM does not exist or does not have write permissions"
    echo "FILE: $outputfilePGP does not exist or does not have write permissions"
    fi
    I would like to print the things on the else, accordingly, this is, print the right message. Ex: if "$outputfileNOM" did not have the write permission, just print that error. BUT, I don't want to put a lot of if/else, Ex:
    if [[ -r $inputfile ]]; then
    if [[-w $outputfileNOM ]] then
    else
    For the READ permission, and the other for the WRITE
    Is there a way to do it, without using a nesting approach, and that maintains the readability. 
    II) About the:
    if [[ -r $inputfile && -w $outputfileNOM && -w $outputfilePGP ]]
    is OK if I use the flag "-x" instead of -r or -w. I don;t have a clear definition of what is the meaning of:
    -x FILE
    FILE exists and execute (or search) permission is granted
    III) Notice the ATTENTION label in my code. I notice that there are some possibilities, for ex: having white spaces before, after or before or after. I'm believing in the consistency of the input files, but if they change, it will explode. What could I do in this case? Is there an elegant way to manage it? (exceptions?)
    Thank you very much!
    EDIT: corrected what rockin turtle wrote bellow about the format. Thank you.
    Last edited by gromlok (2011-10-09 18:39:03)

    I) Regarding your if statement, you could do something like this:
    estr='FILE: %s does not exist or does not have %s permissions.\n'
    [ -r $inputfile ] || ( printf "$estr" "$inputfile" "read" && exit 1 )
    [ -w $outputfileNOM ] || ( printf "$estr" "$outputfileNOM" "write" && exit 1 )
    [ -w $outputfilePGP ] || ( printf "$estr" "$outputfilePGP" "write" && exit 1 )
    II)The -r/-w/-x mean that the file has the read/write/execute bit set. Do a
    $ man chmod
    for details.
    III) You should be able to do
    if [[ "$line" =~ .*\<NV\> ]]; then
    echo "..."
    (( countNOM++ ))
    fi
    but that didn't work for me when I tried it.  I don't know if this is a bug in bash, or (more likely) something that I am doing wrong.
    Regardless, I would write your script like this:
    #!/bin/bash
    file=$(egrep '^[A-Z]..[0-9]{2}' "$1")
    grep '\<NV\>' <<< "$file" > "$2"
    grep '\<PV\>' <<< "$file" > "$3"
    echo 'Count NON:' $(wc -l < "$2")
    echo 'Count PGP:' $(wc -l < "$3")
    Note: In reading your script, your comments imply that each line of the input file starts with 'llnnn' but the example line you gave starts with 'lllnn'.  That is, there are 3 letters (AVO) followed by 2 numbers (01). The above script assumes that lines start with 'lllnn'

  • Question about automatic payment program

    Hi Experts,
    Need your help to solve below issue.
    Compmnay code "1111" is central compasny code,which is making payments to vendor "dddd" through automatic payment program on behalf of other company codes(2222 and 3333).
    Issue1:Company code "1111" has open item 1000 with respect to vendor "dddd" and company code "2222" has open item 3000 with respect to same vendor.
    when i  execute APP it is issuing two different checks though vendor is same.Single check should be issued as per my requirement.
    Let me know about the configuration.
    issue2: Compnay code has "1111"credit memo amount 10000(debit balance) in vendor "yyyy" in the year 2010 and since 2010 no invoices in comopany code "1111" but company code "2222" has invoice amount 15000 for the same vendor.
    My requireemnt is check shoud be issued for the amount ( after diducting credit memo amount  from invoice amount) in APP.
    Please let me know about configuration.
    Regards,
    Uma

    Hi Expert,
    To pay with one check, you need to the below configuration. Go to T-Code:OBVU and do the below steps, according to your requirement.
    and Select payment method supplement (check box)
    Specify the sending company code if you want to pay using a cross-company code transaction but do not want to pay the items of all participating company codes together.
    Examples
    Example 1:
    Company code 0001 pays its own items and the items of company codes 0002 and 0003. All items are grouped into one payment.
    Company code Paying company code Sending company code
    0001  0001  0001
    0002  0001  0001
    0003  0001  0001
    Example 2:
    Company code 0001 pays its own items and the items of company codes 0002 and 0003. However, a separate payment is created for each company code.
    Company code Paying company code Sending company code
    0001  0001  0001
    0002  0001  0002
    0003  0001  0003
    Regards,
    GK
    SAP

  • Question About Installing Individual Programs in Final Cut Studio 2

    I recently installed Final Cut Studio 2, but I chose not to install Livetype on the initial setup. Now I would like to install it, but was curious why it seems to be installing all the information from the other programs I installed last week. Only Livetype was available on the "Custom Install" screen, it was blue and checked. Everything else was greyed out, but still checked. However, it seems to be repeating the same install process I did previously; and I am curious if this is going to create any redundancies on my computer. Any help?

    Thank you for your quick response David!
    1. Great! Glad that worked out.
    2. When I say FCS 2 I mean the suite that came with Final Cut Pro 6, DVD Studio Pro 4, Motion 3, LiveType 2, Soundtrack Pro 2, Color, Compressor 3. I'm pretty sure it will play nicely with a new intel machine.  
    When I say FCS HD I mean the suite that came with Final Cut Pro (5.1.4), DVD Studio Pro, Motion 2, and Soundtrack Pro, and Compressor 2. This version (5.1) was made to work with intel machines.
    3. Thank you also for providing the link! I definitely want to make sure this is legal. 
    Much appreciated
    ~JoeA

  • Question about java threads programming

    Hi
    I have to develop a program where I need to access data from database, but I need to it using multithreading, currently I go sequentially to each database to access data which is slow
    I have a Vector called systemnames, this one has list of all the systems I need to access.
    Here is my current code, some thing like this
    Vector masterVector = new Vector();
    GetData data = new GetData();
    For(int i =0; i < systemnames.size(); i++)
    masterVector.add(data.getData((String)systemnames.get(i));
    public class GetData
    private Vector getData(String ipaddress)
    //process SQL here
    return data;
    how do i convert this to multithread application, so there will be one thread running for each system in vector, this is speed up the process of extracting data and displaying it
    has any one done this kind of program, what are the precautions i need to take care of
    Ashish

    http://www.google.com/search?q=java+threads+tutorial&sourceid=opera&num=0&ie=utf-8&oe=utf-8
    http://java.sun.com/docs/books/tutorial/essential/threads/
    http://www.javaworld.com/javaworld/jw-04-1996/jw-04-threads.html
    http://www.cs.clemson.edu/~cs428/resources/java/tutorial/JTThreads.html
    http://www-106.ibm.com/developerworks/edu/j-dw-javathread-i.html
    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].

  • Another question about running old programs on new macs

    I'm a little confused and was wondering if someone can help me out.
    From what I've read I cannot find any options for me to run an old programs for OS with my intel-based MacBook. Just in case I've tried downloading a bunch of different things (OS 9.2.2 which won't run, sheepshaver which I can't figure out how to use even it it might work). IS there anything that I can do?

    Welcome to Apple Discussions!
    1. Buy an older PowerPC Mac used or refurbished as my FAQ* explains how to do:
    http://www.macmaps.com/usedrefurbished.html
    2. Contact the developer of the said software and ask a Mac OS X version be published of their software.
    3. Politely ask Apple develop a virtualization program through AppleCare's Customer Relations department, http://www.apple.com/macosx/feedback/ and if you want a free developer account go to http://bugreporter.apple.com/ and submit it as an enhancement request.
    4. Tell us what software you want to run that you found is 9 only, and maybe we can tell you an alternative that can open the same documents, play the same style game that is Mac OS X native, or will run under Windows or Linux on your Mac?
    - * Links to my pages may give me compensation.
    Message was edited by: a brody

  • Question about simple Hibernate Programming

    I am trying to use the following Java code to hibernate some
    Java object to a MySQL relational table.
    I wish to avoid the use altogether of *.cfg.xml and *.hbm.xml
    files.
    -Does the following ignore any .cfg.xml file lying present
    under the compiled class?
    -How does one add a property to a Properties object
    to reference the Mappings Object?
    -How does one configure object/method data
    to the fetched Mappings object, as a replacement
    for *.hbm.xml for the corresponding Java object?
    public class TestClass {
    import org.hibernate.cfg.Configuration;.
    import org.hibernate.cfg..Mappings;
    import java.util.Properties;
    //SessionFactory automatically sees Configuraiton.
    public static void main (String [] args)
    Configuration config = new Configuration();
    Properties prop = new Properties();
    prop.setProperty(“hibernate.connection.driver_class”,”com.mysql.jdbc.Drive”);//or other.
    prop.setProperty(“hibernate.connection.username”,”username”;
    prop.setProperty(“hibernate.connection.password”,”password”);
    prop.setProperty(“hibernate.connection.poolsize”,”10”);
    prop.setProperty(“dialect”,”org.hibernate.dialect.MySQLDialect”);
    config.addProperties(prop);
    config.addResource(“/path/to/class/hbm/xml/file/Class.hbm.xml”);
    //If using the object equivalent, what property do I use to
    //refer to the object mappings from the configuration Object?
    Mappings maps = config.createMappings();
    config.buildMappings();
    config.configure();
    //****************************************************************************************************

    corlettk wrote:
    You'll struggle a lot more with the programatic config, coz it's relatively poorly documented (and tested), because you're supposed to just use config files.
    We have to use it to achieve the level of portability required by our tech-arc boffins... and trust me, you don't want to go down that path without a good reason.Plus, of course, if you configure in code, you have to re-compile to re-configure. And if, like us, you have different configs and different domains depending upon where in the world you're deploying, you're a bit stuffed

  • General question about thread-safe program

    Obviously in multi-user application, especially web-based application, we will need to consider thread safety. However, modern web servers and DBMS are already threaded, so to what extent the application programmer are freed from this worrying, and in what situation we must consider thread-safe in our code?
    Thanks

    if you use a J2EE compliant application server and write custom business object as enterprise beans, all concurrent access is handled by the server. however, if you code accesses resources concurrently, you need to handle this yourself. e.g. if a business class write to a file and multiple instances of this class in multiplt threads are running, you need to handle the access of these resources in your code (e.g. keyword "synchronized" or custom locking mechanisms).

  • A question about BC 400 training program

    Dear all,
    I have a question about SAP taining program for ABAP. My manager will soon register me for the training program BC 400, which seems to be the start point for those who don't know anything about ABAP. I was looking at the course description page and I saw that the course is provided as VLC (Virtual Class). As I understood is that the student connects from his workstation to the training center, so it is distant training program.
    I think it would be more interesting for me to be directly in the classroom with teacher face-to-face.
    Therefore, my qestion is the fact that a training program is VLC, does it mean that it is no more possible to attend directly in classes ? or is just for those who may not want for some reason attend directly to the class?
    Thanks in advance,
    Dariyoosh
    Moderator message: moved to S & C.
    Edited by: Thomas Zloch on Sep 6, 2010 2:33 PM

    This is forum for general abap problems.but to answer your question
    check this link from sap site
    http://www.sap.com/usa/services/education/tabbedcourse.epx?context=[[|bc400||1|063|us|]]|
    Thanks
    Bala Duvvuri

  • Question about PHP

    I am completely new to programming and have enjoyed Linux so much, that I would like to go into PHP next. Currently I am a University student with a dead end major (Russian Studies). I am looking to get a certificate in PHP over the course of this next year and to find a little better job with it than I could get with my current degree. I would do a Google search for this, however, I have come to like Arch and the community that surrounds it and wanted to know if any you fine web programmers out there, had any suggestions for free online courses in PHP or book that could be purchased. I was also wondering what a good PHP certification exam to take would be. I have seen the Zend exam and was considering doing a test prep for this after I learn a little more about PHP and SQL. Thank you for your help and suggestions!

    Berticus wrote:
    As  I said, to most people, taxonomy doesn't matter.  It does matter to other people, and I don't mean people like me who have these little pet peeves.
    It matters to people who know a lot of languages who need to know when to use what language.  There isn't a single programming or scripting language that can be everything, so it's important for people, mostly software engineers, to know taxonomy, so they can pick a language most optimal for what they need to get done.  Most of the time, when you're dealing with very complex systems.  Instead of using one language for the whole system, you'll find out you'll be using COBRA to handle hardware, C++ to handle interface and C to tie everything together or something like that.
    I mean when you're differentiating between an interpretted language (script) and a program, the issue is efficiency and speed.  No matter what you do, an interpretted language is inherently slower and less efficient than a programming language.  Even Java that is compiled, is compiled to Java Native Language or something like that, and requires the Java Virtual Machine to interpret it (that's why Java gets it's own branch).  I believe it's the fastest interpretted language, but how does it compare to a natively compiled program?  It's still slower.
    Even when you know you're going to use a programming language, you still have choices, because each programming language can be split into a high, middle, and low level language.  Reasons for using different levels are due to how quickly do you need to write the program, how portable does the program need to be, how easy should other people be able to read the program, does it need to have low level abilities such as handling memory directly.  Then there's also the question about how your program is going to flow.  Is it functional or object oriented?
    It's not so much an opionated matter when you think about it.  It's more along the lines of do you need this knowledge or not?  For most people, I'm willing to bet that's everybody who posts in this thread, that information is not important, they don't need to know it, because they handle very, very simple applications compared to the complex systems that do indeed require the programmer or scripter to know the difference.
    Actually, the difference between interpreted and compiled (and faux-compiled) languages is different from the difference between programming and scripting languages, interpreted languages can also be programming languages, and compiled languages can be scripting (although this happens very little and is really pointless and tedious to do )
    'Scripting' usually refers to code meant to extend upon a framework or program separate from the script itself, whereas 'programming' is creating applications that are on their own, separate applications, regardless of whether they're run though an interpreter at runtime. The difference is a bit vague, and you are right in that interpreted languages are often used for scripting, but it is not necessary, look at something like python, this can be used both as scripting for automating tasks quickly by using it's immense library, as well as for creating stand alone applications, which would be programming. (PHP is virtually always scripting, though)
    Either way I prefer the term 'coding'

  • A question about comments

    Hi, all,
    I have a question about the comments:
    Program function comments should be included on the block diagram or Front panel, or both. Thanks.

    Many good things have already been mentioned.
    For the Front panel, there should be a clear distinction between toplevel VIs (or any subVIs where the user must interact with the front panel), and subVIs where the front panel is only of interest to the programmer. The needs here are quite different:
    User Interface VIs
    The front panel should be clear and easy to use. All "help" elements, tip strips, etc are geared towards the end user. The icon is irrelevant, because it is typically not even shown. Everything of interest to code maintenance should be on the diagram.
    subVIs
    Here, the front panel can contain a description of what the subVI does, who created it, company and copyright information, version information, limitations (e.g. input A must be >0), URLs or literature references to the algorithm, etc. (Have a look at any of the openG tools!). The "VI properties...documentation" section should be populated. The icon should be descriptive. All controls and indicators should have intuitive names (not just "Numeric 4", or "Array" )
    Comments specific to certain areas of the code should be placed where they apply, especially if the code uses some exotic algorithm that would make the code hard to interpret.
    Use a programming style that is self-documenting. (e.g. Don't unbundle the error cluster check for "equal zero" to switch a case statement. Wire the error cluster directly to the case so you'll get a red/green error case structure. Much more obvious!)
    If these are proprietary VIs with password protected diagrams You should split the comments: Anything of interest to the non-privileged user goes on the front panel, anything else on the diagram.
    In the end, it does not really matters where you place the comments as long as they are easy to find later and still make sense to somebody else 10 years from now. Message Edited by altenbach on 05-30-2005 01:13 PM
    LabVIEW Champion . Do more with less code and in less time .

  • I have questions about language translator (Bing translator)

    hi, I have questions about language translator. few days ago, I use Bing translator. But, Some different results are displayed,, I did want to read  japan's news. But translator's results was different news, example is game, lee sun sin, and
    so on,, But, sometime,,, correct results were displayed,, technical problem?? or network problem?? or hacking? If you want to see problem result, I give you a picture of incorrect problem 

    Hi,
    This forum is discuss and ask questions about the C# programming language, IDE, libraries, samples, and tools. I am afraid this issue is out of topic.
    Please repost this issue to Machine Translation and Language Tools      >  
    Microsoft Translator User Forum (Including Bing Translator) forum.
    Now I will move your thread to "off-topic" forum. Thanks for your understanding.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Questions about the Apple Developer Enterprise Program

    Hi there,
    i got some questions about the Apple Developer Enterprise Program:
    - is there a way a company can create their own "AppStore" with only the APPs the employees should use?
    - when I developed the enterprise app are the install files on a apple hosted server or do i need my own infrastructure to distribute my app?
    Thanks in advance for answers!

    Google: MDM

  • Question about the programming of a legend

    Hello everybody,
    I have a question about the programming of a waveform's legend. I
    already asked here in this forum about the legend programming (03)
    months ago.
    I went satisfied but I ve just noticed that this code
    (See Code old_legend_test.llb with main.vi as main function) operates a
    little different from my expectances.
    Therefore I have a new question and I want to know if it
    is possible by labview programming to plot and show, on a waveform
    chart, a signal with activ plot superior to zero (0) without to be
    obliged to plot and show a signal with activ plot equal to zero (0) or
    inferior to the desired activ plot.
    I give you an example
    of what I m meaning. I have by example 4 signals (Signal 0, 1, 2 and 3)
    and each signal corresponds respectively to a channel (Chan1, Chan2,
    Chan3, Chan4). I want to control the legend (activ plot, plot name and
    plot color) programmatically. Is it possible with labview to plot signal
    1 or 2 or 3 or (1, 3) or (2,3) or (1,2,3) or other possible combination
    without to active the signal with the corresponding activ plot zero
    (0)?
    Let see the labview attached data
    (new_legend_test.llb with main.vi as main function). When I try to
    control the input selected values again I get them back but I don't
    understand why they have no effect on the legend of my waveform chart.
    Could somebody explain me what I m doing wrong or show me how to get a
    correct legend with desired plots? Thank by advance for your assistance.
    N.B.
    The
    both attached data are saved with labview 2009.
    Sincerly,PrinceJack
    Attachments:
    old_legend_test.llb ‏65 KB
    new_legend_test.llb ‏65 KB

    Hi
    princejack,
    Thanks for
    posting on National Instruments forum.
    The behavior
    you have is completely normal. You can control the number of row displayed in
    the legend and this rows are linked to the data you send to your graph. Thus,
    if you have 3 arrays of data, let say chan1, chan2 and chan3, you can choose
    which data you want to display in your graph using the property node (Active
    plot and visible). But for the legend as you send 3 plots there is an array of
    the plot name [chan1, chan2, chan3] and you can display 0, 1, 2 or 3 rows of
    this array but you cannot control the order in this array! So, to be able to
    change this array you have to only send data you need to you graph. I'm not
    sure my explanations are clear so I have implemented a simple example doing
    that.
    Benjamin R.
    R&D Software Development Manager
    http://www.fluigent.com/
    Attachments:
    GraphLegend.vi ‏85 KB

Maybe you are looking for