Results 1 to 15 of 15
Like Tree2Likes
  • 1 Post By pbrockway2
  • 1 Post By Hibernate

Thread: (i%5=0)?System.out.println():System.out.print(" "); does not work!

  1. #1
    oszc is offline Member
    Join Date
    Aug 2011
    Posts
    20
    Rep Power
    0

    Default (i%5=0)?System.out.println():System.out.print(" "); does not work!

    Java Code:
    public class test {
    
    	public static void main(String[] args) {
    		int i =0 ;
    		for( i =0 ; i<=25; i++)
    		{
    			System.out.printf("%d", i);
    			(i%5==0)?System.out.println():System.out.print(" ");
    			
    		}
    	}
    output i want to generate:
    0 1 2 3 4
    5 6 7 8 9
    ...

    P.S. sorry the title is incorrect, it should be (i%5==0) instead
    Last edited by oszc; 08-07-2011 at 04:27 AM. Reason: Added code tags.

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    What exactly do you mean, "doesn't work"?

    Errors? if so paste them, incorrect output? Post the given output.

  3. #3
    oszc is offline Member
    Join Date
    Aug 2011
    Posts
    20
    Rep Power
    0

    Default

    sorry ,i don't express well .

    this statement (i%5==0)?System.out.println():System.out.print(" ");
    the compiler shows the message " The left-hand side of an assignment must be a variable"

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    The message you get is not very clear. And neither is Oracle's Tutorial statement that ?: "can be thought of as shorthand for an if-then-else statement" because it is a little more limited.

    From the JLS, 15.25 Conditional Operator ? : "Note that it is a compile-time error for either the second or the third operand expression to be an invocation of a void method." So the bpttom line is that if you want to conditionally evaluate one of two void methods, then you have to use if/else.

    (A general point - which you should feel free to ignore for now - is that ?: will form an expression which always has a type. if/else on the other hand forms a statement that has no type associated with it.)
    Last edited by pbrockway2; 08-07-2011 at 04:35 AM.
    sunde887 likes this.

  5. #5
    Hibernate's Avatar
    Hibernate is offline Senior Member
    Join Date
    Dec 2010
    Location
    Stockholm, Sweden
    Posts
    222
    Blog Entries
    9
    Rep Power
    4

    Default

    Quote Originally Posted by oszc View Post
    Java Code:
    public class test {
    
    	public static void main(String[] args) {
    		int i =0 ;
    		for( i =0 ; i<=25; i++)
    		{
    			System.out.printf("%d", i);
    			(i%5==0)?System.out.println():System.out.print(" ");
    			
    		}
    	}
    output i want to generate:
    0 1 2 3 4
    5 6 7 8 9
    ...

    P.S. sorry the title is incorrect, it should be (i%5==0) instead
    In the statement [a ? b : c] (without [ ]), a most return boolean (which your does), and b and c most return then same data type (or same class),
    System.out.println and System.out.print does not return anything (void). (you should be able to use methods returning Void, but not void).

    So you must use regular [outline] if-statements, or:

    Java Code:
    System.out.print((i % 5 == 0) ? '\n' : ' ');
    Last edited by Hibernate; 08-07-2011 at 04:52 AM.
    Ex animo! Hibernate
    Java, Arch Linux, C, GPL v3, Bash, Eclipse, Linux VT, GNOME 2 and many buttons on windows.

  6. #6
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    One comment I'd like to add:

    With some thought you can accomplish this(hint: System.out.print(...), can take an argument). Although this works, you should favor clarity over brevity.

    Using the ternary operator may indeed save you a couple of lines of code, however; it could also increase the complexity of the code. If you are insistent on using the clever styled ternary operator you should be sure to comment what the code is doing(which forfeits the brevity the operator saved you).

    That being said, this is not a rule, but something to keep in mind when deciding whether or not to use the ternary operator.
    Last edited by sunde887; 08-07-2011 at 06:15 AM.

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    I don't think ?: expressions are OS dependent are they? It would seem rather unjavalike if they were.

    The second and third expressions don't have to be the same type - numeric promotion, boxing conversion, capture conversion can all go on (as detailed in the link I gave). And subclasses and nulls can be present. All of which gives plenty of scope: for good or ill.

    (favor clarity over brevity)++

  8. #8
    Hibernate's Avatar
    Hibernate is offline Senior Member
    Join Date
    Dec 2010
    Location
    Stockholm, Sweden
    Posts
    222
    Blog Entries
    9
    Rep Power
    4

    Default

    Well, they only need to be castable to the same type without loss if data, i.e. implicitly castable, which includes subclasses. But you can not write

    ? true : 1
    ? "hello" : 'w' //note that one of them is a String, and the other is a char (character).
    And so on.

    But why go into the complex when we are just describing the basics, implicitly castable is one of the things beginners usually have problems with.


    And I think ?: is less OS dependent then +, which I believe is processor dependent and behaves exactly the same for all processors.
    Ex animo! Hibernate
    Java, Arch Linux, C, GPL v3, Bash, Eclipse, Linux VT, GNOME 2 and many buttons on windows.

  9. #9
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Perhaps I am wrong, but I thought '\n' was an os dependent character.

  10. #10
    Hibernate's Avatar
    Hibernate is offline Senior Member
    Join Date
    Dec 2010
    Location
    Stockholm, Sweden
    Posts
    222
    Blog Entries
    9
    Rep Power
    4

    Default

    Quote Originally Posted by sunde887 View Post
    Perhaps I am wrong, but I thought '\n' was an os dependent character.
    No, it is not.

    \n = 10
    \r = 13
    \f = ? //I can't bother to look it up

    Unix standard for new lines: \n (Mac OS X is Unix-like)
    Mac standard for new lines: \r (Mac OS X is not included, see above)
    Windows standard for new lines: \r\n
    (There are more, but less common, variants.)

    However all of them generally accepts \n as a new line character as it is programming standard, but text editor, might not.

    So \n is not OS dependent.

    However [the result of printing] \eE is shell dependent.


    Yet another edit:
    I'm not sure if this is for Java, but I think it is. In text mode (not the binary mode which is standard) in file writing/reading \n gets converted to the OS default new line character sequence.
    Last edited by Hibernate; 08-07-2011 at 08:14 AM. Reason: Missed ”are” and a dot.
    sunde887 likes this.
    Ex animo! Hibernate
    Java, Arch Linux, C, GPL v3, Bash, Eclipse, Linux VT, GNOME 2 and many buttons on windows.

  11. #11
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Perhaps I am wrong, but I thought '\n' was an os dependent character.
    Oh I see! Yes, to properly replicate the intent of being like println() you would have to append line.separator rather than \n.

    Well, they only need to be castable to the same type without loss if data, i.e. implicitly castable, which includes subclasses. But you can not write

    ? true : 1
    ? "hello" : 'w' //note that one of them is a String, and the other is a char (character).
    And so on.

    But why go into the complex when we are just describing the basics, implicitly castable is one of the things beginners usually have problems with.
    My reason for citing the JLS in the first place was to give authority for the simple statement about the second and third expressions of the ternary operator. I referred to it again only to reject the erroneous assertion that those expressions have to have the same type. I'll cite it again for anyone interested in deciding whether it's a matter of castibility. The following compiles fine:

    Java Code:
    public class Test {
    	public static void main(String[] args) {
    		Object foo = true ? "hello" :'w';
    		System.out.println(foo);
    		foo = false ? true : 1;
    		System.out.println(foo);
    	}
    }
    I don't mean to be argumentative (and hope you don't take it that way, Hibernate) but I think what the ternary operator does is complex in a way that if-then-else statements are not. The ternary operator provides brevity and, used simply, is clear. In less simple circumstances its meaning may not be clear. I think Sunde had it right (without telling the OP what to do): favour clarity over brevity.

    -----

    But where is the most important person in the thread? All the variants mentioned start with a new line: is that intended? Again whether they end with a new line depends on the number of things being printed. Perhaps it would make more sense to print the separators *before* the data elements.

  12. #12
    Hibernate's Avatar
    Hibernate is offline Senior Member
    Join Date
    Dec 2010
    Location
    Stockholm, Sweden
    Posts
    222
    Blog Entries
    9
    Rep Power
    4

    Default

    Quote Originally Posted by pbrockway2 View Post
    Java Code:
    public class Test {
    	public static void main(String[] args) {
    		Object foo = true ? "hello" :'w';
    		System.out.println(foo);
    		foo = false ? true : 1;
    		System.out.println(foo);
    	}
    }
    Dude that is auto-boxing (ugly!), making both expressions Object.
    But I do think you can do that without declaring foo, at least not in Java 6.

    And no I do not that it as that you are argumentative.


    But shouldn't you can't a compiler warning, or maybe error, from
    foo = true ? "hello" :'w';
    and
    foo = false ? true : 1;
    since they use constant booleans (in this case literals) as conditions, making it always give the same output?
    Ex animo! Hibernate
    Java, Arch Linux, C, GPL v3, Bash, Eclipse, Linux VT, GNOME 2 and many buttons on windows.

  13. #13
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,371
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Hibernate View Post
    Dude that is auto-boxing (ugly!), making both expressions Object.
    But I do think you can do that without declaring foo, at least not in Java 6.

    And no I do not that it as that you are argumentative.


    But shouldn't you can't a compiler warning, or maybe error, from
    foo = true ? "hello" :'w';
    and
    foo = false ? true : 1;
    since they use constant booleans (in this case literals) as conditions, making it always give the same output?
    The only warning you'll (probably) get is "dead code" but autoboxing makes those expressions perfectly valid (although highly cryptic). Had Gosling decided that Java should have no primitives he would've defend himself on attacks arguing about speed reasons; but I agree, autoboxing can be ugly and just a mixed blessing.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  14. #14
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Dude that is auto-boxing (ugly!), making both expressions Object.
    Exactly. And whether ugly or not it is certainly complex (which was my only point really).

    Using constants for the condition doesn't elicit any warning or anything. I only did it that way to make a brief example. Likewise declaring foo: you have to do that if the ?: is to be an expression-statement (or whatever the term is). But the ?: expressions you originally came up with can both be used without having to declare anything:

    Java Code:
    import java.util.Scanner;
    
    public class Test {
    	public static void main(String[] args) {
    		Scanner in = new Scanner(System.in);
    		boolean cond = in.nextLine().isEmpty();
    			// we'll declare foo so we can assign the ternary expression to something
    		Object foo = cond ? "hello" :'w';
    		System.out.println(foo);
    			// here another ugly ternary is used without any declaration
    		System.out.println(cond ? true : 1);
    	}
    }
    Running it by Eclipse, I see it does warn of "dead code" when boolean literals are used. But beware of thinking that true will always return the first alternative!

    Java Code:
    public class Test {
    	public static void main(String[] args) {
    		boolean cond = 666 > 0;
    		System.out.println(cond ? 1 : 1.0);
    		System.out.println(cond ? 1 : "one");
    	}
    }
    (As discussed too many years ago at Sun's forum.)

  15. #15
    Hibernate's Avatar
    Hibernate is offline Senior Member
    Join Date
    Dec 2010
    Location
    Stockholm, Sweden
    Posts
    222
    Blog Entries
    9
    Rep Power
    4

    Default

    Using ?: in multiple languages must have gotten me confused on this.
    Ex animo! Hibernate
    Java, Arch Linux, C, GPL v3, Bash, Eclipse, Linux VT, GNOME 2 and many buttons on windows.

Similar Threads

  1. System.out.println("Hi.");
    By xCiro in forum Introductions
    Replies: 1
    Last Post: 12-11-2009, 03:23 PM
  2. System.out.println("Hello Java-Forums!");
    By Arsenic in forum Introductions
    Replies: 0
    Last Post: 03-05-2009, 05:39 PM
  3. System.out.println("Hi!");
    By Inks in forum Introductions
    Replies: 0
    Last Post: 02-20-2009, 01:46 PM
  4. System.out.print("Hello!")
    By Console in forum Introductions
    Replies: 6
    Last Post: 09-22-2008, 12:09 AM
  5. Replies: 11
    Last Post: 08-19-2008, 11:29 AM

Posting Permissions

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