+ Konu Cevaplama Paneli
2. Sayfa - Toplam 2 Sayfa var BirinciBirinci 1 2
Gösterilen sonuçlar: 11 ile 13 ve 13

Konu: HTML-WEB Programlama ve Java Script

  1. #11
    Ehil Üye zeet06 - ait Kullanıcı Resmi (Avatar)
    Üyelik tarihi
    Jul 2008
    Mesajlar
    1.022

    Standart

    Yukarıdaki yayınların dökümanlarını indir:
    http://rapidshare.com/files/31762449...umant.rar.html

    Rapidshare premium bekletme sorununu çözünüz:



    Bu Program ile rapidden beklemeden sınırsız bi şelikde indrime yapabileceksiniz
    bilmem kaç dolar veripde rapid premium almanıza hiç gerek yok
    rapidle birlikte bir çok dowload upload sitesini destekleyen bu program
    sadece burda indir lingleri kopyala otomatil ling algılamasıda var olmaktadır
    kurmanıza gerek yok rardan çıkarın içindeki CryptLoad bu dosyaya tıklayıp
    hemen indirmeye başlayabilirsiniz. Bu program Son sürümdür...
    hemde FULL
    Not Programı Tam Olarak Kullanabilmeniz için :
    Microsoft .NET Framework Version 2.0 programına ihtiyacınız olacaktır.
    Ling : http://www.microsoft.com/downloads/d...displaylang=en
    İşde ling İndirin Rapidin Açıklarından faydalanın,
    http://rapidshare.com/files/24951057...1.1.6.rar.html

  2. #12
    Ehil Üye zeet06 - ait Kullanıcı Resmi (Avatar)
    Üyelik tarihi
    Jul 2008
    Mesajlar
    1.022

    Lightbulb

    The Java interpreter patternbuilt
    computer programming, the interpreter pattern is a particular design pattern. The interpreter pattern specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence.[
    Türkçe:
    Içinde bilgisayar programlama, tercüman desen belirli bir is tasarım deseni. Tercüman deseni nasıl bir dilde cümle değerlendirmek belirtir. Temel fikir bir olmasıdır sınıf Her sembol için (terminali veya nonterminal) Bir de özel bilgisayar dili. sözdizim ağacı dilde bir cümlenin bir örnektir kompozit desen ve değerlendirmek () cümle yorumlamak kullanılır.[1
    Structure:Yapı
    Interpreter UML class diagram


    Uses for the Interpreter pattern
    Specialized database query languages such as SQL.
    Specialized computer languages which are often used to describe communication protocols
    Most general-purpose computer languages actually incorporate several specialized languages.
    Examples
    The following Reverse Polish notation example illustrates the interpreter pattern. The grammar
    expression ::= plus | minus | variable
    plus ::= expression expression '+'
    minus ::= expression expression '-'
    variable ::= 'a' | 'b' | 'c' | ... | 'z'

    defines a language which contains reverse polish expressions like:
    a b +
    a b c + -
    a b + c a - -

    Following the interpreter pattern there is a class for each grammar rule.

    Tercüman deseni için kullanır
    Uzman veritabanı sorgulama dilleri gibi SQL.
    Özel bilgisayar dilleri genellikle iletişim protokolleri tanımlamak için kullanılır
    En genel amaçlı bilgisayar dilleri aslında bazı özel dil dahil.
    Örnekler
    Aşağıdaki Polish notation Ters Örneğin tercüman deseni göstermektedir. Dilbilgisi
    ifade:: = artı | eksi | değişken
    artı:: = ifade ifade '+'
    eksi:: = ifade ifade '-'
    değişken:: = 'a' | 'b' | 'c' | ... | 'Z'

    ters lehçe gibi ifadeler içeren bir dil tanımlar:
    a b +
    a b c + --
    a b c a + - --

    Tercüman kalıp orada her gramer kural için bir sınıftır ardından.
    Java
    import java.util.*;

    interface Expression {
    public int interpret(HashMap<String,Integer> variables);
    }

    class Number implements Expression {
    private int number;
    public Number(int number) { this.number = number; }
    public int interpret(HashMap<String,Integer> variables) { return number; }
    }

    class Plus implements Expression {
    Expression leftOperand;
    Expression rightOperand;
    public Plus(Expression left, Expression right) {
    leftOperand = left;
    rightOperand = right;
    }

    public int interpret(HashMap<String,Integer> variables) {
    return leftOperand.interpret(variables) + rightOperand.interpret(variables);
    }
    }

    class Minus implements Expression {
    Expression leftOperand;
    Expression rightOperand;
    public Minus(Expression left, Expression right) {
    leftOperand = left;
    rightOperand = right;
    }

    public int interpret(HashMap<String,Integer> variables) {
    return leftOperand.interpret(variables) - rightOperand.interpret(variables);
    }
    }

    class Variable implements Expression {
    private String name;
    public Variable(String name) { this.name = name; }
    public int interpret(HashMap<String,Integer> variables) {
    return variables.get(name);
    }
    }
    While the interpreter pattern does not address parsing[2] a parser is provided for completeness.
    class Evaluator {
    private Expression syntaxTree;

    public Evaluator(String expression) {
    Stack<Expression> expressionStack = new Stack<Expression>();
    for (String token : expression.split(" ")) {
    if (token.equals("+")) {
    Expression subExpression = new Plus(expressionStack.pop(), expressionStack.pop());
    expressionStack.push( subExpression );
    }
    else if (token.equals("-")) {
    Expression subExpression = new Minus(expressionStack.pop(), expressionStack.pop());
    expressionStack.push( subExpression );
    }
    else
    expressionStack.push( new Variable(token) );
    }
    syntaxTree = expressionStack.pop();
    }

    public int evaluate(HashMap<String,Integer> context) {
    return syntaxTree.interpret(context);
    }
    }
    Finally evaluating the expression "w x z - +" with w = 5, x = 10, and z = 42.
    public class InterpreterExample {
    public static void main(String[] args) {
    String expression = "w x z - +";
    Evaluator sentence = new Evaluator(expression);
    HashMap<String,Integer> variables = new HashMap<String,Integer>();
    variables.put("w", 5);
    variables.put("x", 10);
    variables.put("z", 42);
    int result = sentence.evaluate(variables);
    System.out.println(result);
    }
    }
    ---------------------------------------
    java.util.regex
    Class Pattern
    java.lang.Object
    FPRIVATE "TYPE=PICT;ALT=extended by"java.util.regex.Pattern
    All Implemented Interfaces:
    Serializable

    public final class Pattern
    extends
    Object
    implements
    Serializable
    A compiled representation of a regular expression.
    A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a
    Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.
    A typical invocation sequence is thus
    Pattern p = Pattern.compile("a*b");
    Matcher m = p.
    matcher("aaaaab");
    boolean b = m.
    matches();
    A matches method is defined by this class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement
    boolean b = Pattern.matches("a*b", "aaaaab");
    is equivalent to the three statements above, though for repeated matches it is less efficient since it does not allow the compiled pattern to be reused.
    Instances of this class are immutable and are safe for use by multiple concurrent threads. Instances of the
    Matcher class are not safe for such use.
    Summary of regular-expression constructs

    Construct

    Matches

    Characters

    x
    The character x
    \\
    The backslash character
    \0n
    The character with octal value 0n (0 <= n <= 7)
    \0nn
    The character with octal value 0nn (0 <= n <= 7)
    \0mnn
    The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)
    \xhh
    The character with hexadecimal value 0xhh
    \uhhhh
    The character with hexadecimal value 0xhhhh
    \t
    The tab character ('\u0009')
    \n
    The newline (line feed) character ('\u000A')
    \r
    The carriage-return character ('\u000D')
    \f
    The form-feed character ('\u000C')
    \a
    The alert (bell) character ('\u0007')
    \e
    The escape character ('\u001B')
    \cx
    The control character corresponding to x

    Character classes

    [abc]
    a, b, or c (simple class)
    [^abc]
    Any character except a, b, or c (negation)
    [a-zA-Z]
    a through z or A through Z, inclusive (range)
    [a-d[m-p]]
    a through d, or m through p: [a-dm-p] (union)
    [a-z&&[def]]
    d, e, or f (intersection)
    [a-z&&[^bc]]
    a through z, except for b and c: [ad-z] (subtraction)
    [a-z&&[^m-p]]
    a through z, and not m through p: [a-lq-z](subtraction)

    Predefined character classes

    .
    Any character (may or may not match line terminators)
    \d
    A digit: [0-9]
    \D
    A non-digit: [^0-9]
    \s
    A whitespace character: [ \t\n\x0B\f\r]
    \S
    A non-whitespace character: [^\s]
    \w
    A word character: [a-zA-Z_0-9]
    \W
    A non-word character: [^\w]

    POSIX character classes

    (US-ASCII only)

    \p{Lower}
    A lower-case alphabetic character: [a-z]
    \p{Upper}
    An upper-case alphabetic character:[A-Z]
    \p{ASCII}
    All ASCII:[\x00-\x7F]
    \p{Alpha}
    An alphabetic character:[\p{Lower}\p{Upper}]
    \p{Digit}
    A decimal digit: [0-9]
    \p{Alnum}
    An alphanumeric character:[\p{Alpha}\p{Digit}]
    \p{Punct}
    Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
    \p{Graph}
    A visible character: [\p{Alnum}\p{Punct}]
    \p{Print}
    A printable character: [\p{Graph}]
    \p{Blank}
    A space or a tab: [ \t]
    \p{Cntrl}
    A control character: [\x00-\x1F\x7F]
    \p{XDigit}
    A hexadecimal digit: [0-9a-fA-F]
    \p{Space}
    A whitespace character: [ \t\n\x0B\f\r]

    Classes for Unicode blocks and categories

    \p{InGreek}
    A character in the Greek block (simple block)
    \p{Lu}
    An uppercase letter (simple category)
    \p{Sc}
    A currency symbol
    \P{InGreek}
    Any character except one in the Greek block (negation)
    [\p{L}&&[^\p{Lu}]]
    Any letter except an uppercase letter (subtraction)

    Boundary matchers

    ^
    The beginning of a line
    $
    The end of a line
    \b
    A word boundary
    \B
    A non-word boundary
    \A
    The beginning of the input
    \G
    The end of the previous match
    \Z
    The end of the input but for the final terminator, if any
    \z
    The end of the input

    Greedy quantifiers

    X?
    X, once or not at all
    X*
    X, zero or more times
    X+
    X, one or more times
    X{n}
    X, exactly n times
    X{n,}
    X, at least n times
    X{n,m}
    X, at least n but not more than m times

    Reluctant quantifiers

    X??
    X, once or not at all
    X*?
    X, zero or more times
    X+?
    X, one or more times
    X{n}?
    X, exactly n times
    X{n,}?
    X, at least n times
    X{n,m}?
    X, at least n but not more than m times

    Possessive quantifiers

    X?+
    X, once or not at all
    X*+
    X, zero or more times
    X++
    X, one or more times
    X{n}+
    X, exactly n times
    X{n,}+
    X, at least n times
    X{n,m}+
    X, at least n but not more than m times

    Logical operators

    XY
    X followed by Y
    X|Y
    Either X or Y
    (X)
    X, as a capturing group

    Back references

    \n
    Whatever the nth capturing group matched

    Quotation

    \
    Nothing, but quotes the following character
    \Q
    Nothing, but quotes all characters until \E
    \E
    Nothing, but ends quoting started by \Q

    Special constructs (non-capturing)

    (?:X)
    X, as a non-capturing group
    (?idmsux-idmsux)
    Nothing, but turns match flags on - off
    (?idmsux-idmsux:X)
    X, as a non-capturing group with the given flags on - off
    (?=X)
    X, via zero-width positive lookahead
    (?!X)
    X, via zero-width negative lookahead
    (?<=X)
    X, via zero-width positive lookbehind
    (?<!X)
    X, via zero-width negative lookbehind
    (?>X)
    X, as an independent, non-capturing group



    Backslashes, escapes, and quoting
    The backslash character (
    '\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and \{ matches a left brace.
    It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.
    Backslashes within string literals in Java source code are interpreted as required by the
    Java Language Specification as either Unicode escapes or other character escapes. It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.
    Character Classes
    Character classes may appear within other character classes, and may be composed by the union operator (implicit) and the intersection operator (
    &&). The union operator denotes a class that contains every character that is in at least one of its operand classes. The intersection operator denotes a class that contains every character that is in both of its operand classes.
    The precedence of character-class operators is as follows, from highest to lowest:

    1

    Literal escape
    \x

    2

    Grouping
    [...]

    3

    Range
    a-z

    4

    Union
    [a-e][i-u]

    5

    Intersection
    [a-z&&[aeiou]]

    Note that a different set of metacharacters are in effect inside a character class than outside a character class. For instance, the regular expression
    . loses its special meaning inside a character class, while the expression - becomes a range forming metacharacter.
    Line terminators
    A line terminator is a one- or two-character sequence that marks the end of a line of the input character sequence. The following are recognized as line terminators:
    A newline (line feed) character (
    '\n'),
    A carriage-return character followed immediately by a newline character (
    "\r\n"),
    A standalone carriage-return character (
    '\r'),
    A next-line character (
    '\u0085'),
    A line-separator character (
    '\u2028'), or
    A paragraph-separator character (
    '\u2029).
    If
    UNIX_LINES mode is activated, then the only line terminators recognized are newline characters.
    The regular expression
    . matches any character except a line terminator unless the DOTALL flag is specified.
    By default, the regular expressions
    ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence. If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input. When in MULTILINE mode $ matches just before a line terminator or the end of the input sequence.
    Groups and capturing
    Capturing groups are numbered by counting their opening parentheses from left to right. In the expression
    ((A)(B(C))), for example, there are four such groups:

    1

    ((A)(B(C)))

    2

    (A)

    3

    (B(C))

    4

    (C)

    Group zero always stands for the entire expression.
    Capturing groups are so named because, during a match, each subsequence of the input sequence that matches such a group is saved. The captured subsequence may be used later in the expression, via a back reference, and may also be retrieved from the matcher once the match operation is complete.
    The captured input associated with a group is always the subsequence that the group most recently matched. If a group is evaluated a second time because of quantification then its previously-captured value, if any, will be retained if the second evaluation fails. Matching the string
    "aba" against the expression (a(b)?)+, for example, leaves group two set to "b". All captured input is discarded at the beginning of each match.
    Groups beginning with
    (? are pure, non-capturing groups that do not capture text and do not count towards the group total.
    Unicode support
    This class follows
    Unicode Technical Report #18: Unicode Regular Expression Guidelines, implementing its second level of support though with a slightly different concrete syntax.
    Unicode escape sequences such as
    \u2014 in Java source code are processed as described in ?3.3 of the Java Language Specification. Such escape sequences are also implemented directly by the regular-expression parser so that Unicode escapes can be used in expressions that are read from files or from the keyboard. Thus the strings "\u2014" and "\\u2014", while not equal, compile into the same pattern, which matches the character with hexadecimal value 0x2014.
    Unicode blocks and categories are written with the
    \p and \P constructs as in Perl. \p{prop} matches if the input has the property prop, while \P{prop} does not match if the input has that property. Blocks are specified with the prefix In, as in InMongolian. Categories may be specified with the optional prefix Is: Both \p{L} and \p{IsL} denote the category of Unicode letters. Blocks and categories can be used both inside and outside of a character class.
    The supported blocks and categories are those of
    The Unicode Standard, Version 3.0. The block names are those defined in Chapter 14 and in the file Blocks-3.txt of the Unicode Character Database except that the spaces are removed; "Basic Latin", for example, becomes "BasicLatin". The category names are those defined in table 4-5 of the Standard (p. 88), both normative and informative.
    Comparison to Perl 5
    Perl constructs not supported by this class:
    The conditional constructs
    (?{X}) and (?(condition)X|Y),
    The embedded code constructs
    (?{code}) and (??{code}),
    The embedded comment syntax
    (?#comment), and
    The preprocessing operations
    \l\u, \L, and \U.
    Constructs supported by this class but not by Perl:
    Possessive quantifiers, which greedily match as much as they can and do not back off, even when doing so would allow the overall match to succeed.
    Character-class union and intersection as described
    above.
    Notable differences from Perl:
    In Perl,
    \1 through \9 are always interpreted as back references; a backslash-escaped number greater than 9 is treated as a back reference if at least that many subexpressions exist, otherwise it is interpreted, if possible, as an octal escape. In this class octal escapes must always begin with a zero. In this class, \1 through \9 are always interpreted as back references, and a larger number is accepted as a back reference if at least that many subexpressions exist at that point in the regular expression, otherwise the parser will drop digits until the number is smaller or equal to the existing number of groups or it is one digit.
    Perl uses the
    g flag to request a match that resumes where the last match left off. This functionality is provided implicitly by the Matcher class: Repeated invocations of the find method will resume where the last match left off, unless the matcher is reset.
    In Perl, embedded flags at the top level of an expression affect the whole expression. In this class, embedded flags always take effect at the point at which they appear, whether they are at the top level or within a group; in the latter case, flags are restored at the end of the group just as in Perl.
    Perl is forgiving about malformed matching constructs, as in the expression
    *a, as well as dangling brackets, as in the expression abc], and treats them as literals. This class also accepts dangling brackets but is strict about dangling metacharacters like +, ? and *, and will throw a PatternSyntaxException if it encounters them.
    For a more precise description of the behavior of regular expression constructs, please see
    Mastering Regular Expressions, 2nd Edition, Jeffrey E. F. Friedl, O'Reilly and Associates, 2002.
    Since:
    1.4
    See Also:
    String.split(String, int), String.split(String), Serialized Form


    Field Summary

    static int

    CANON_EQ
    Enables canonical equivalence.

    static int

    CASE_INSENSITIVE
    Enables case-insensitive matching.

    static int

    COMMENTS
    Permits whitespace and comments in pattern.

    static int

    DOTALL
    Enables dotall mode.

    static int

    MULTILINE
    Enables multiline mode.

    static int

    UNICODE_CASE
    Enables Unicode-aware case folding.

    static int

    UNIX_LINES
    Enables Unix lines mode.

    Method Summary

    static

    Pattern

    compile(String regex)
    Compiles the given regular expression into a pattern.

    static

    Pattern

    compile(String regex, int flags)
    Compiles the given regular expression into a pattern with the given flags.

    int

    flags()
    Returns this pattern's match flags.

    Matcher

    matcher(CharSequence input)
    Creates a matcher that will match the given input against this pattern.

    static boolean

    matches(String regex, CharSequence input)
    Compiles the given regular expression and attempts to match the given input against it.

    String

    pattern()
    Returns the regular expression from which this pattern was compiled.

    String[]

    split(CharSequence input)
    Splits the given input sequence around matches of this pattern.

    String[]

    split(CharSequence input, int limit)
    Splits the given input sequence around matches of this pattern.

    Methods inherited from class java.lang.Object
    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    Field Detail


    UNIX_LINES
    public static final int UNIX_LINES
    Enables Unix lines mode.
    In this mode, only the
    '\n' line terminator is recognized in the behavior of ., ^, and $.
    Unix lines mode can also be enabled via the embedded flag expression
    (?d).
    See Also:
    Constant Field Values


    CASE_INSENSITIVE
    public static final int CASE_INSENSITIVE
    Enables case-insensitive matching.
    By default, case-insensitive matching assumes that only characters in the US-ASCII charset are being matched. Unicode-aware case-insensitive matching can be enabled by specifying the
    UNICODE_CASE flag in conjunction with this flag.
    Case-insensitive matching can also be enabled via the embedded flag expression
    (?i).
    Specifying this flag may impose a slight performance penalty.
    See Also:
    Constant Field Values


    COMMENTS
    public static final int COMMENTS
    Permits whitespace and comments in pattern.
    In this mode, whitespace is ignored, and embedded comments starting with
    # are ignored until the end of a line.
    Comments mode can also be enabled via the embedded flag expression
    (?x).
    See Also:
    Constant Field Values


    MULTILINE
    public static final int MULTILINE
    Enables multiline mode.
    In multiline mode the expressions
    ^ and $ match just after or just before, respectively, a line terminator or the end of the input sequence. By default these expressions only match at the beginning and the end of the entire input sequence.
    Multiline mode can also be enabled via the embedded flag expression
    (?m).
    See Also:
    Constant Field Values


    DOTALL
    public static final int DOTALL
    Enables dotall mode.
    In dotall mode, the expression
    . matches any character, including a line terminator. By default this expression does not match line terminators.
    Dotall mode can also be enabled via the embedded flag expression
    (?s). (The s is a mnemonic for "single-line" mode, which is what this is called in Perl.)
    See Also:
    Constant Field Values


    UNICODE_CASE
    public static final int UNICODE_CASE
    Enables Unicode-aware case folding.
    When this flag is specified then case-insensitive matching, when enabled by the
    CASE_INSENSITIVE flag, is done in a manner consistent with the Unicode Standard. By default, case-insensitive matching assumes that only characters in the US-ASCII charset are being matched.
    Unicode-aware case folding can also be enabled via the embedded flag expression
    (?u).
    Specifying this flag may impose a performance penalty.
    See Also:
    Constant Field Values


    CANON_EQ
    public static final int CANON_EQ
    Enables canonical equivalence.
    When this flag is specified then two characters will be considered to match if, and only if, their full canonical decompositions match. The expression
    "a\u030A", for example, will match the string "?" when this flag is specified. By default, matching does not take canonical equivalence into account.
    There is no embedded flag character for enabling canonical equivalence.
    Specifying this flag may impose a performance penalty.
    See Also:
    Constant Field Values
    Method Detail


    compile
    public static Pattern compile(String regex)
    Compiles the given regular expression into a pattern.
    Parameters:
    regex - The expression to be compiled
    Throws:
    PatternSyntaxException - If the expression's syntax is invalid


    compile
    public static Pattern compile(String regex,
    int flags)
    Compiles the given regular expression into a pattern with the given flags.
    Parameters:
    regex - The expression to be compiled
    flags - Match flags, a bit mask that may include CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, and CANON_EQ
    Throws:
    IllegalArgumentException - If bit values other than those corresponding to the defined match flags are set in flags
    PatternSyntaxException - If the expression's syntax is invalid


    pattern
    public String pattern()
    Returns the regular expression from which this pattern was compiled.
    Returns:
    The source of this pattern


    matcher
    public Matcher matcher(CharSequence input)
    Creates a matcher that will match the given input against this pattern.
    Parameters:
    input - The character sequence to be matched
    Returns:
    A new matcher for this pattern


    flags
    public int flags()
    Returns this pattern's match flags.
    Returns:
    The match flags specified when this pattern was compiled


    matches
    public static boolean matches(String regex,
    CharSequence input)
    Compiles the given regular expression and attempts to match the given input against it.
    An invocation of this convenience method of the form
    Pattern.matches(regex, input);
    behaves in exactly the same way as the expression
    Pattern.compile(regex).matcher(input).matches()
    If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than invoking this method each time.
    Parameters:
    regex - The expression to be compiled
    input - The character sequence to be matched
    Throws:
    PatternSyntaxException - If the expression's syntax is invalid


    split
    public String[] split(CharSequence input,
    int limit)
    Splits the given input sequence around matches of this pattern.
    The array returned by this method contains each substring of the input sequence that is terminated by another subsequence that matches this pattern or is terminated by the end of the input sequence. The substrings in the array are in the order in which they occur in the input. If this pattern does not match any subsequence of the input then the resulting array has just one element, namely the input sequence in string form.
    The
    limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
    The input
    "boo:and:foo", for example, yields the following results with these parameters:
    Regex
    Limit
    Result
    :
    2
    { "boo", "and:foo" }
    :
    5
    { "boo", "and", "foo" }
    :
    -2
    { "boo", "and", "foo" }
    o
    5
    { "b", "", ":and:f", "", "" }
    o
    -2
    { "b", "", ":and:f", "", "" }
    o
    0
    { "b", "", ":and:f" }

    Parameters:

    input - The character sequence to be split
    limit - The result threshold, as described above
    Returns:
    The array of strings computed by splitting the input around matches of this pattern


    split
    public String[] split(CharSequence input)
    Splits the given input sequence around matches of this pattern.
    This method works as if by invoking the two-argument
    split method with the given input sequence and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
    The input
    "boo:and:foo", for example, yields the following results with these expressions:
    Regex
    Result
    :
    { "boo", "and", "foo" }
    o
    { "b", "", ":and:f" }

    Parameters:

    input - The character sequence to be split
    Returns:
    The array of strings computed by splitting the input around matches of this pattern

    ___________________________________________
    "O zaman vecd ile bin secde eder -varsa- taşım."
    -Vücuda verilen kuvvet, Hak’ka ibadet, halka hizmet içindir.

  3. #13
    Ehil Üye zeet06 - ait Kullanıcı Resmi (Avatar)
    Üyelik tarihi
    Jul 2008
    Mesajlar
    1.022

    Standart

    / *
    Design Patterns Java Companion

    Copyright (C) 1998, James W. Cooper

    IBM Thomas J. Watson Araştırma Merkezi

    * /
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.util.StringTokenizer;
    import java.util.Vector;

    import javax.swing.AbstractListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;

    //-----------------------------------
    public class InterpDemo extends JFrame implements ActionListener {
    JButton Go;

    JTextField tx;

    KidData kdata;

    JawtList ptable;

    public InterpDemo() {
    super("Interpreter Demo");
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    }
    });

    tx = new JTextField(20);
    Go = new JButton("Go");

    JPanel p = new JPanel();
    getContentPane().add(p);
    p.setLayout(new BorderLayout());
    JPanel np = new JPanel();
    p.add("North", np);
    np.add(tx);
    np.add(Go);
    Go.addActionListener(this);
    ptable = new JawtList(20);
    p.add("Center", ptable);

    kdata = new KidData("50free.txt");

    setSize(new Dimension(400, 200));
    setVisible(true);
    }

    //----------------------------------------
    public void actionPerformed(ActionEvent e) {
    Parser p = new Parser(tx.getText());
    p.setData(kdata, ptable);
    p.Execute();
    }

    //----------------------------------------
    static public void main(String argv[]) {
    new InterpDemo();
    }
    }

    interface Command {
    public void Execute();
    }
    //this class is just a simple collection of arrays
    //of the data which has been selected

    class Data {
    Kid[] kids;

    public Data(Kid[] kd) {
    kids = kd;
    }

    public Kid[] getData() {
    return kids;
    }
    }

    class ParseVar extends ParseObject {
    static final int FRNAME = 0, LNAME = 1, AGE = 2, CLUB = 3, TIME = 4,
    tabMAX = 5;

    public ParseVar(String s) {
    s = s.toLowerCase();
    value = -1;
    type = VAR;
    if (s.equals("frname"))
    value = FRNAME;
    if (s.equals("lname"))
    value = LNAME;
    if (s.equals("age"))
    value = AGE;
    if (s.equals("club"))
    value = CLUB;
    if (s.equals("time"))
    value = TIME;
    }

    //--------------------------------------
    public boolean isLegal() {
    return (value >= 0);
    }
    }

    class Parser implements Command {
    Stack stk;

    Vector actionList;

    KidData kdata;

    Data data;

    //PrintTable ptable;
    JawtList ptable;

    public Parser(String line) {
    stk = new Stack();
    actionList = new Vector();

    StringTokenizer tok = new StringTokenizer(line);
    while (tok.hasMoreElements()) {
    ParseObject token = tokenize(tok.nextToken());
    if (token != null)
    stk.push(token);
    }
    }

    //----------------------------------------
    public void setData(KidData k, JawtList pt) {
    data = new Data(k.getData());
    ptable = pt;
    }

    //----------------------------------------
    //executes parse of command line
    public void Execute() {

    while (stk.hasMoreElements()) {

    if (topStack(ParseObject.VAR, ParseObject.VAR)) {
    //reduce (Var Var) to Multvar
    ParseVar v = (ParseVar) stk.pop();
    ParseVar v1 = (ParseVar) stk.pop();
    MultVar mv = new MultVar(v1, v);
    stk.push(mv);
    }
    //reduce MULTVAR VAR to MULTVAR
    if (topStack(ParseObject.MULTVAR, ParseObject.VAR)) {
    MultVar mv = new MultVar();
    MultVar mvo = (MultVar) stk.pop();
    ParseVar v = (ParseVar) stk.pop();
    mv.add(v);
    Vector mvec = mvo.getVector();
    for (int i = 0; i < mvec.size(); i++)
    mv.add((ParseVar) mvec.elementAt(i));
    stk.push(mv);
    }
    if (topStack(ParseObject.VAR, ParseObject.MULTVAR)) {
    //reduce (Multvar Var) to Multvar
    ParseVar v = (ParseVar) stk.pop();
    MultVar mv = (MultVar) stk.pop();
    mv.add(v);
    stk.push(mv);
    }
    //reduce Verb Var to Verb containing vars
    if (topStack(ParseObject.VAR, ParseObject.VERB)) {
    addArgsToVerb();
    }
    //reduce Verb MultVar to Verb containing vars
    if (topStack(ParseObject.MULTVAR, ParseObject.VERB)) {
    addArgsToVerb();
    }
    //move top verb to action list
    if (stk.top().getType() == ParseObject.VERB) {
    actionList.addElement(stk.pop());
    }

    }//while
    //now execute the verbs
    //data.setData(kdata.getData());
    //for (int i = actionList.size() -1; i >= 0; i--)
    for (int i = 0; i < actionList.size(); i++) {
    Verb v = (Verb) actionList.elementAt(i);
    v.setData(data, ptable);
    v.Execute();
    }
    }

    //----------------------------------------
    private void addArgsToVerb() {
    ParseObject v = stk.pop();
    ParseVerb verb = (ParseVerb) stk.pop();
    verb.addArgs(v);
    stk.push(verb);
    }

    //----------------------------------------
    private boolean topStack(int c1, int c2) {
    return (stk.top().getType() == c1) && (stk.nextTop().getType() == c2);
    }

    //----------------------------------------
    private ParseObject tokenize(String s) {
    ParseObject obj = getVerb(s);
    if (obj == null)
    obj = getVar(s);
    return obj;
    }

    //----------------------------------------
    private ParseVerb getVerb(String s) {
    ParseVerb v;
    v = new ParseVerb(s);
    if (v.isLegal())
    return v.getVerb(s);
    else
    return null;
    }

    //----------------------------------------
    private ParseVar getVar(String s) {
    ParseVar v;
    v = new ParseVar(s);
    if (v.isLegal())
    return v;
    else
    return null;
    }

    }

    class Kid {
    String frname, lname, club;

    int age;

    float time;

    //-------------------------------------
    public Kid(String line) {
    StringTokenizer tok = new StringTokenizer(line);

    String lnum = tok.nextToken();
    frname = tok.nextToken();
    lname = tok.nextToken();
    age = new Integer(tok.nextToken()).intValue();
    club = tok.nextToken();
    time = new Float(tok.nextToken()).floatValue();
    }

    //-------------------------------
    public Object getData(int key) {
    switch (key) {
    case ParseVar.FRNAME:
    return frname;
    case ParseVar.LNAME:
    return lname;
    case ParseVar.CLUB:
    return club;
    case ParseVar.AGE:
    return new Integer(age);
    case ParseVar.TIME:
    return new Float(time);
    }

    return null;
    }

    //--------------------------------
    public int getAge() {
    return age;
    }

    public float getTime() {
    return time;
    }

    public String getFrname() {
    return frname;
    }

    public String getLname() {
    return lname;
    }

    public String getClub() {
    return club;
    }
    }

    interface awtList {
    public void add(String s);

    public void remove(String s);

    public String[] getSelectedItems();

    }

    //this is a simple adapter class to
    //convert List awt methods to Swing methods

    class JawtList extends JScrollPane implements ListSelectionListener, awtList {
    private JList listWindow;

    private JListData listContents;

    //-----------------------------------------
    public JawtList(int rows) {
    listContents = new JListData();
    listWindow = new JList(listContents);
    listWindow.setPrototypeCellValue("Abcdefg Hijkmnop");
    getViewport().add(listWindow);

    }

    //-----------------------------------------
    public void add(String s) {
    listContents.addElement(s);
    }

    //-----------------------------------------
    public void remove(String s) {
    listContents.removeElement(s);
    }

    //-----------------------------------------
    public void clear() {
    listContents.clear();
    }

    //-----------------------------------------
    public String[] getSelectedItems() {
    Object[] obj = listWindow.getSelectedValues();
    String[] s = new String[obj.length];
    for (int i = 0; i < obj.length; i++)
    s[i] = obj[i].toString();
    return s;
    }

    //-----------------------------------------
    public void valueChanged(ListSelectionEvent e) {
    }

    }
    // =========================================

    class JListData extends AbstractListModel {
    private Vector data;

    //-----------------------------------------
    public JListData() {
    data = new Vector();
    }

    //-----------------------------------------
    public int getSize() {
    return data.size();
    }

    //-----------------------------------------
    public Object getElementAt(int index) {
    return data.elementAt(index);
    }

    //-----------------------------------------
    public void addElement(String s) {
    data.addElement(s);
    fireIntervalAdded(this, data.size() - 1, data.size());
    }

    //-----------------------------------------
    public void removeElement(String s) {
    data.removeElement(s);
    fireIntervalRemoved(this, 0, data.size());
    }

    //-----------------------------------------
    public void clear() {
    int size = data.size();
    data = new Vector();
    fireIntervalRemoved(this, 0, size);
    }
    }

    class ParseObject {
    public static final int VERB = 1000, VAR = 1010, MULTVAR = 1020;

    protected int value;

    protected int type;

    public int getValue() {
    return value;
    }

    public int getType() {
    return type;
    }
    }

    class ParseVerb extends ParseObject {
    static public final int PRINT = 100, SORTBY = 110, THENBY = 120;

    protected Vector args;

    public ParseVerb(String s) {
    args = new Vector();
    s = s.toLowerCase();
    value = -1;
    type = VERB;
    if (s.equals("print"))
    value = PRINT;
    if (s.equals("sortby"))
    value = SORTBY;
    }

    //-----------------------------------
    public ParseVerb getVerb(String s) {
    switch (value) {
    case PRINT:
    return new Print(s);
    case SORTBY:
    return new Sort(s);
    }
    return null;
    }

    //-----------------------------------
    public void addArgs(MultVar mv) {
    args = mv.getVector();
    }

    //-----------------------------------
    public void addArgs(ParseObject p) {
    args.addElement(p);
    }

    //-----------------------------------
    public boolean isLegal() {
    return (value >= 0);
    }

    //-----------------------------------
    }

    class Sort extends Verb {
    Kid[] kids;

    int pindex;

    public Sort(String s) {
    super(s);
    value = SORTBY;
    }

    //-----------------------------------

    public void Execute() {
    int sortKey;

    kids = data.getData();

    for (int a = 0; a < args.size(); a++) {
    ParseVar v = (ParseVar) args.elementAt(a);
    if (v instanceof MultVar) {
    MultVar mv = (MultVar) v;
    Vector mvec = mv.getVector();
    for (int k = mvec.size() - 1; k >= 0; k--) {
    ParseVar pv = (ParseVar) mvec.elementAt(k);
    sortKey = pv.getValue();
    sortByKey(sortKey);
    }
    } else {
    sortKey = v.getValue();
    sortByKey(sortKey);
    }
    }

    }

    //----------------------------------------
    private void sortByKey(int sortkey) {
    System.out.println(sortkey);
    for (int i = 0; i < kids.length; i++)
    for (int j = i + 1; j < kids.length; j++)
    if (compare(i, j, sortkey)) {
    Kid tmp = kids[i];
    kids[i] = kids[j];
    kids[j] = tmp;
    }
    }

    //----------------------------------------
    private boolean compare(int i, int j, int key) {
    boolean cval;

    switch (key) {
    case ParseVar.FRNAME:
    cval = kids[i].getFrname().compareTo(kids[j].getFrname()) > 0;
    break;
    case ParseVar.LNAME:
    cval = kids[i].getLname().compareTo(kids[j].getLname()) > 0;
    break;
    case ParseVar.CLUB:
    cval = kids[i].getClub().compareTo(kids[j].getClub()) > 0;
    break;
    case ParseVar.AGE:
    cval = kids[i].getAge() > kids[j].getAge();
    break;
    case ParseVar.TIME:
    cval = kids[i].getTime() > kids[j].getTime();
    break;
    default:
    cval = false;
    }
    return cval;
    }

    }

    class Verb extends ParseVerb implements Command {
    protected Data data;

    protected JawtList ptable;

    public Verb(String s) {
    super(s);
    }

    public void Execute() {
    }

    public void setData(Data dt, JawtList pt) {
    data = dt;
    ptable = pt;
    }
    }

    class Print extends Verb {
    Kid[] kids;

    public Print(String s) {
    super(s);
    value = PRINT;
    }

    //-----------------------------------
    public void Execute() {
    String pline;

    kids = data.getData();
    //ptable.setDims(kids.length, args.size());
    ptable.clear();

    for (int i = 0; i < kids.length; i++) {
    pline = ""; //line in output list
    for (int j = 0; j < args.size(); j++) {

    ParseVar v = (ParseVar) args.elementAt(j);
    if (v instanceof MultVar) {
    MultVar mv = (MultVar) v;
    Vector vlist = mv.getVector();
    for (int k = 0; k < vlist.size(); k++) {
    ParseVar pv = (ParseVar) vlist.elementAt(k);
    //System.out.print(kids[i].getData(pv.getValue())+" ");
    pline += kids[i].getData(pv.getValue()) + " ";
    }
    } else {
    // System.out.print(kids[i].getData(v.getValue())+" ");
    //ptable.setValueAt( kids[i].getData(v.getValue()), i, j);
    pline += kids[i].getData(v.getValue()) + " ";
    }
    }
    ptable.add(pline);
    //System.out.println();
    }
    ptable.validate();
    ptable.repaint();
    }
    //-----------------------------------

    }

    class MultVar extends ParseVar {
    Vector multVec;

    public MultVar(ParseObject v1, ParseObject v2) {
    super("");
    multVec = new Vector();
    multVec.addElement(v1);
    multVec.addElement(v2);
    type = MULTVAR;
    }

    public MultVar() {
    super("");
    multVec = new Vector();
    type = MULTVAR;

    }

    public void add(ParseObject v1) {
    multVec.addElement(v1);
    }

    public Vector getVector() {
    return multVec;
    }

    }

    class KidData {
    Vector kids;

    //------------------------------------------
    public KidData(String filename) {
    kids = new Vector();
    InputFile f = new InputFile(filename);
    String s = f.readLine();
    while (s != null) {
    if (s.trim().length() > 0) {
    Kid k = new Kid(s);
    kids.addElement(k);
    }
    s = f.readLine();
    }
    }

    //--------------------------------
    public Kid[] getData() {
    Kid[] kd = new Kid[kids.size()];
    for (int i = 0; i < kids.size(); i++)
    kd[i] = (Kid) kids.elementAt(i);
    return kd;
    }

    //--------------------------------

    public int size() {
    return kids.size();
    }

    //--------------------------------
    public Kid getKid(int i) {
    return (Kid) kids.elementAt(i);
    }

    //--------------------------------
    public Vector getKidData(int key) {
    Vector v = new Vector();
    for (int i = 0; i < kids.size(); i++)
    v.addElement(getKid(i).getData(key));
    return v;
    }

    //--------------------------------
    public int getTableKey(String tabName) {
    int key = -1;
    tabName = tabName.toLowerCase();
    if (tabName.equals("frname"))
    key = ParseVar.FRNAME;
    if (tabName.equals("lname"))
    key = ParseVar.LNAME;
    if (tabName.equals("age"))
    key = ParseVar.AGE;
    if (tabName.equals("club"))
    key = ParseVar.CLUB;
    if (tabName.equals("time"))
    key = ParseVar.TIME;

    return key;
    }

    //----------------------------
    public String getTableName(int i) {
    String name = "";
    switch (i) {
    case ParseVar.FRNAME:
    name = "frname";
    case ParseVar.LNAME:
    name = "lname";
    case ParseVar.AGE:
    name = "age";
    case ParseVar.CLUB:
    name = "club";
    case ParseVar.TIME:
    name = "time";
    }
    return name;
    }
    //----------------------------

    }

    class InputFile {
    RandomAccessFile f = null;

    boolean errflag;

    String s = null;

    public InputFile(String fname) {
    errflag = false;
    try {
    //open file
    f = new RandomAccessFile(fname, "r");
    } catch (IOException e) {
    //print error if not found
    System.out.println("no file found");
    errflag = true; //and set flag
    }
    }

    //-----------------------------------------
    public boolean checkErr() {
    return errflag;
    }

    //-----------------------------------------
    public String read() {
    //read a single field up to a comma or end of line
    String ret = "";
    if (s == null) //if no data in string
    {
    s = readLine(); //read next line
    }
    if (s != null) //if there is data
    {
    s.trim(); //trim off blanks
    int i = s.indexOf(","); //find next comma
    if (i <= 0) {
    ret = s.trim(); //if no commas go to end of line
    s = null; //and null out stored string
    } else {
    ret = s.substring(0, i).trim(); //return left of comma
    s = s.substring(i + 1); //save right of comma
    }
    } else
    ret = null;
    return ret; //return string
    }

    //-----------------------------------------
    public String readLine() {
    //read in a line from the file
    s = null;
    try {
    s = f.readLine(); //could throw error
    } catch (IOException e) {
    errflag = true;
    System.out.println("File read error");
    }
    return s;
    }

    //-----------------------------------------
    public void close() {
    try {
    f.close(); //close file
    } catch (IOException e) {
    System.out.println("File close error");
    errflag = true;
    }
    }
    //-----------------------------------------
    }

    class Stack {
    Vector stk;

    public Stack() {
    stk = new Vector();
    }

    //----------------------------------------
    public void push(Object obj) {
    stk.addElement(obj);
    }

    //----------------------------------------
    public ParseObject pop() {
    ParseObject obj = (ParseObject) stk.lastElement();
    int i = stk.size() - 1;
    stk.removeElementAt(i);
    return obj;
    }

    //----------------------------------------
    public void dump(String s) {
    System.out.println(s);
    dump();
    }

    //----------------------------------------

    public void dump() {
    for (int i = 0; i < stk.size(); i++) {
    ParseObject p = (ParseObject) stk.elementAt(i);
    System.out.println(i + " " + p.getType());
    }
    }

    //----------------------------------------
    public ParseObject top() {
    return (ParseObject) stk.lastElement();
    }

    //----------------------------------------
    public boolean hasMoreElements() {
    return (stk.size() > 0);
    }

    //----------------------------------------
    public ParseObject nextTop() {
    int i = stk.size();
    if (i > 1) {
    return (ParseObject) stk.elementAt(i - 2);
    } else
    return null;
    }

    //----------------------------------------
    public void pop2Push(ParseObject p) {
    int i = stk.size();
    if (i >= 2) {
    pop();
    pop();
    push(p);
    } else
    push(p);
    }
    }
    //50free.txt
    /*

    1 Amanda McCarthy 12 WCA 29.28
    2 Jamie Falco 12 HNHS 29.80
    3 Meaghan O'Donnell 12 EDST 30.00
    4 Greer Gibbs 12 CDEV 30.04
    5 Rhiannon Jeffrey 11 WYW 30.04
    6 Sophie Connolly 12 WAC 30.05
    7 Dana Helyer 12 ARAC 30.18
    8 Lindsay Marotto 12 OAK 30.23
    9 Sarah Treichel 12 WYW 30.35
    10 Ashley McEntee 12 RAC 30.47
    11 Rachel Brookman 12 CAT 30.51
    12 Michelle Ducharme 12 LEHY 30.51
    13 Karleen Danais 12 NES 30.70
    14 Megan Loock 12 WAC 30.90
    15 Kaitlyn Ament 12 HNHS 30.93
    16 Tara Schoen 12 WYW 31.01
    17 Kate Olshefski 12 NCY 31.01
    18 Emma Zuidema 12 HMST 31.07
    19 Katie Persing 12 OAK 31.14
    20 Christina Monsees 11 RAC 31.27
    21 Kimberly Watcke 12 CDEV 31.50
    22 Colleen Smith 12 AJSC 31.52
    23 Chloe Osborne 12 GYWD 31.74
    24 Natalia Fugate 12 WAC 31.75
    25 Lisa McHale 11 RAC 31.76
    26 Lindsay Cowles 11 NES 31.79
    27 Jacquelyn Yavarone 12 HNHS 31.83
    28 Molly Fenn 12 WRAT 31.84
    29 Karin Brudvig 12 HMST 31.84
    30 Annie Duffy 12 MGAT 31.90
    31 Nicole Coia 11 WCA 31.94
    32 Elizabeth Rice 12 WYW 31.96
    33 Yvette Landwehr 12 WRAT 32.00
    34 Ashley Recklet 12 SHEL 32.24
    35 Lauren McKenna 11 PSDY 32.27
    36 Kristen Fontaine 12 EDST 32.28
    37 Diana Cooke 12 ZEUS 32.33
    38 Kimberly Gambino 11 NES 32.43
    39 Jenny Morgan 11 NES 32.49
    40 Colleen Coelho 12 CDEV 32.50
    41 Leigh Gordon 12 CDEV 32.62
    42 Caitlin Gillen 12 WYW 32.75
    43 Kristen Skroski 12 HNHS 32.91
    44 Sarah Greenberg 11 CDEV 32.97
    45 Kathy Collins 12 EHBB 33.11
    46 Morgan Bullock 12 ICSC 33.33
    47 Brittany Medlin 12 CAT 33.33
    48 Haley Ottenbreit 12 HNHS 33.35
    49 Laura Kunces 11 WAC 33.64
    50 Hayley Wolfgruber 12 WYW 33.73
    51 Katie Duffy 12 MGAT 34.24


    */


    ---------------
    Before
    01
    This is an adaptation of a design that appeared in a Pascal data structures book. The intent was to use stacks to convert normal “infix” syntax into “postfix” notation with operator precedence already handled.
    02
    public class InterpreterDemo
    {
    public static boolean precedence(char a, char b)
    {
    String high = "*/", low = "+-";
    if (a == '(')
    return false;
    if (a == ')' && b == '(')
    {
    System.out.println(")-(");
    return false;
    }
    if (b == '(')
    return false;
    if (b == ')')
    return true;
    if (high.indexOf(a) > - 1 && low.indexOf(b) > - 1)
    return true;
    if (high.indexOf(a) > - 1 && high.indexOf(b) > - 1)
    return true;
    if (low.indexOf(a) > - 1 && low.indexOf(b) > - 1)
    return true;
    return false;
    }
    public static String convert_to_postfix(String expr)
    {
    Stack < Character > op_stack = new Stack < Character > ();
    StringBuffer out = new StringBuffer();
    String opers = "+-*/()";
    char top_sym = '+';
    boolean empty;
    String[] tokens = expr.split(" ");
    for (int i = 0; i < tokens.length; i++)
    if (opers.indexOf(tokens[i].charAt(0)) == - 1)
    {
    out.append(tokens[i]);
    out.append(' ');
    }
    else
    {
    while (!(empty = op_stack.isEmpty()) && precedence(top_sym =
    op_stack.pop(), tokens[i].charAt(0)))
    {
    out.append(top_sym);
    out.append(' ');
    }
    if (!empty)
    op_stack.push(top_sym);
    if (empty || tokens[i].charAt(0) != ')')
    op_stack.push(tokens[i].charAt(0));
    else
    top_sym = op_stack.pop();
    }
    while (!op_stack.isEmpty())
    {
    out.append(op_stack.pop());
    out.append(' ');
    }
    return out.toString();
    }
    public static double process_postfix(String postfix, HashMap < String,
    Integer > map)
    {
    Stack < Double > stack = new Stack < Double > ();
    String opers = "+-*/";
    String[] tokens = postfix.split(" ");
    for (int i = 0; i < tokens.length; i++)
    // If token is a number or variable
    if (opers.indexOf(tokens[i].charAt(0)) == - 1)
    {
    double term = 0.;
    try
    {
    term = Double.parseDouble(tokens[i]);
    }
    catch (NumberFormatException ex)
    {
    term = map.get(tokens[i]);
    }
    stack.push(term);
    // If token is an operator
    }
    else
    {
    double b = stack.pop(), a = stack.pop();
    if (tokens[i].charAt(0) == '+')
    a = a + b;
    else if (tokens[i].charAt(0) == '-')
    a = a - b;
    else if (tokens[i].charAt(0) == '*')
    a = a * b;
    else if (tokens[i].charAt(0) == '/')
    a = a / b;
    stack.push(a);
    }
    return stack.pop();
    }
    public static void main(String[] args)
    {
    String infix = "C * 9 / 5 + 32";
    String postfix = convert_to_postfix(infix);
    System.out.println("Infix: " + infix);
    System.out.println("Postfix: " + postfix);
    HashMap < String, Integer > map = new HashMap < String, Integer > ();
    for (int i = 0; i <= 100; i += 10)
    {
    map.put("C", i);
    System.out.println("C is " + i + ", F is " + process_postfix
    (postfix, map));
    }
    }
    }
    Infix: C * 9 / 5 + 32 Postfix: C 9 * 5 / 32 + C is 0, F is 32.0 C is 10, F is 50.0 C is 20, F is 68.0 C is 30, F is 86.0 C is 40, F is 104.0 C is 50, F is 122.0 C is 60, F is 140.0 C is 70, F is 158.0 C is 80, F is 176.0 C is 90, F is 194.0 C is 100, F is 212.0

    After
    03
    This is a refactoring that follows the intent of the Interpreter design pattern. All classes in the Operand hierarchy: implement the evaluate(context), digest some piece of the context argument, and return their contribution to the recursive traversal. Applying the Interpreter pattern in this domain is probably inappropriate.
    04
    interface Operand
    {
    double evaluate(HashMap < String, Integer > context);
    void traverse(int level);
    }
    class Expression implements Operand
    {
    private char m_operator;
    public Operand left, rite;
    public Expression(char op)
    {
    m_operator = op;
    }
    public void traverse(int level)
    {
    left.traverse(level + 1);
    System.out.print("" + level + m_operator + level + " ");
    rite.traverse(level + 1);
    }
    public double evaluate(HashMap < String, Integer > context)
    {
    double result = 0.;
    double a = left.evaluate(context);
    double b = rite.evaluate(context);
    if (m_operator == '+')
    result = a + b;
    else if (m_operator == '-')
    result = a - b;
    else if (m_operator == '*')
    result = a * b;
    else if (m_operator == '/')
    result = a / b;
    return result;
    }
    }
    class Variable implements Operand
    {
    private String m_name;
    public Variable(String name)
    {
    m_name = name;
    }
    public void traverse(int level)
    {
    System.out.print(m_name + " ");
    }
    public double evaluate(HashMap < String, Integer > context)
    {
    return context.get(m_name);
    }
    }
    class Number implements Operand
    {
    private double m_value;
    public Number(double value)
    {
    m_value = value;
    }
    public void traverse(int level)
    {
    System.out.print(m_value + " ");
    }
    public double evaluate(HashMap context)
    {
    return m_value;
    }
    }
    public class InterpreterDemo
    {
    public static boolean precedence(char a, char b)
    {
    String high = "*/", low = "+-";
    if (a == '(')
    return false;
    if (a == ')' && b == '(')
    {
    System.out.println(")-(");
    return false;
    }
    if (b == '(')
    return false;
    if (b == ')')
    return true;
    if (high.indexOf(a) > - 1 && low.indexOf(b) > - 1)
    return true;
    if (high.indexOf(a) > - 1 && high.indexOf(b) > - 1)
    return true;
    if (low.indexOf(a) > - 1 && low.indexOf(b) > - 1)
    return true;
    return false;
    }
    public static String convert_to_postfix(String expr)
    {
    Stack < Character > op_stack = new Stack < Character > ();
    StringBuffer out = new StringBuffer();
    String opers = "+-*/()";
    char top_sym = '+';
    boolean empty;
    String[] tokens = expr.split(" ");
    for (int i = 0; i < tokens.length; i++)
    if (opers.indexOf(tokens[i].charAt(0)) == - 1)
    {
    out.append(tokens[i]);
    out.append(' ');
    }
    else
    {
    while (!(empty = op_stack.isEmpty()) && precedence(top_sym =
    op_stack.pop(), tokens[i].charAt(0)))
    {
    out.append(top_sym);
    out.append(' ');
    }
    if (!empty)
    op_stack.push(top_sym);
    if (empty || tokens[i].charAt(0) != ')')
    op_stack.push(tokens[i].charAt(0));
    else
    top_sym = op_stack.pop();
    }
    while (!op_stack.isEmpty())
    {
    out.append(op_stack.pop());
    out.append(' ');
    }
    return out.toString();
    }
    public static Operand build_syntax_tree(String tree)
    {
    Stack < Operand > stack = new Stack < Operand > ();
    String opers = "+-*/";
    String[] tokens = tree.split(" ");
    for (int i = 0; i < tokens.length; i++)
    // If token is a number or variable
    if (opers.indexOf(tokens[i].charAt(0)) == - 1)
    {
    Operand term = null;
    try
    {
    term = new Number(Double.parseDouble(tokens[i]));
    }
    catch (NumberFormatException ex)
    {
    term = new Variable(tokens[i]);
    }
    stack.push(term);
    // If token is an operator
    }
    else
    {
    Expression expr = new Expression(tokens[i].charAt(0));
    expr.rite = stack.pop();
    expr.left = stack.pop();
    stack.push(expr);
    }
    return stack.pop();
    }
    public static void main(String[] args)
    {
    System.out.println("celsi * 9 / 5 + thirty");
    String postfix = convert_to_postfix("celsi * 9 / 5 + thirty");
    System.out.println(postfix);
    Operand expr = build_syntax_tree(postfix);
    expr.traverse(1);
    System.out.println();
    HashMap < String, Integer > map = new HashMap < String, Integer > ();
    map.put("thirty", 30);
    for (int i = 0; i <= 100; i += 10)
    {
    map.put("celsi", i);
    System.out.println("C is " + i + ", F is " + expr.evaluate(map));
    }
    }
    }
    _____________________
    "O zaman vecd ile bin secde eder -varsa- taşım."
    -Vücuda verilen kuvvet, Hak’ka ibadet, halka hizmet içindir.

+ Konu Cevaplama Paneli

Konu Bilgileri

Users Browsing this Thread

Şu an 1 kullanıcı var. (0 üye ve 1 konuk)

     

Benzer Konular

  1. Risale-i Nurlar (Cep Telefonu İçin, Java - Kitaplar)
    By fbsamet in forum Mobil Paylaşım
    Cevaplar: 63
    Son Mesaj: 01.09.09, 17:10
  2. C Programlama
    By zeet06 in forum Bilişim Haberleri ve Bilimsel Makaleler
    Cevaplar: 13
    Son Mesaj: 14.01.09, 14:59
  3. Java Yardımı
    By Lebid24 in forum Bilişim Haberleri ve Bilimsel Makaleler
    Cevaplar: 1
    Son Mesaj: 18.11.08, 20:14
  4. Java Script Öğreniyorum...
    By zeet06 in forum Bilgisayar ve İnternet Sorunları
    Cevaplar: 2
    Son Mesaj: 01.11.08, 20:02

Bu Konudaki Etiketler

Yetkileriniz

  • Konu Acma Yetkiniz Yok
  • Cevap Yazma Yetkiniz Yok
  • Eklenti Yükleme Yetkiniz Yok
  • Mesajınızı Değiştirme Yetkiniz Yok
Google Grupları
RisaleForum grubuna abone ol
E-posta:
Bu grubu ziyaret et

Search Engine Friendly URLs by vBSEO 3.6.0