The Artima Developer Community
Sponsored Link

Java Answers Forum
Switch Statement

1 reply on 1 page. Most recent reply: May 8, 2006 10:48 PM by Matthias Neumair

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
kat ta

Posts: 6
Nickname: codekat
Registered: Apr, 2006

Switch Statement Posted: May 8, 2006 6:29 PM
Reply to this message Reply
Advertisement
Hi guys,
Im having trouble with my switch statement..

i have this so far:

import javax.swing.*;

public class Lab4Switch {

public static void main ( String[] args){
String mark_string;

mark_string = JOptionPane.showInputDialog(null, "Enter your mark: ");

int mark = Integer.parseInt(mark_string);

switch(mark){

case (mark < 84):JOptionPane.showInputDialog(null, "Grade is HD");
break;
case (mark < 74): JOptionPane.showMessageDialog(null, "Grade is D");
break;
case (mark < 64): JOptionPane.showMessageDialog(null, "Grade is P");
break;
case (mark < 54): JOptionPane.showMessageDialog(null, "Grade is F");
break;
default:
System.exit(0);
}
}


Im not sure how to make it work... i think there is something wrong with my expression..

any thoughts?

thanks


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: Switch Statement Posted: May 8, 2006 10:48 PM
Reply to this message Reply
Switch only accepts constants, not conditions. It can only check if values are equal, not if one is bigger or smaller than another.
    switch (n) {
        case 1:
            break;
        case 2:
            break;
        default:
    }
 

In your case you have to use
    if (mark < 84) {
    } else if(mark < 74)) {
    } else if(mark < 64)) {
    } else {//error case, mark is >= 84
    }


You can write it also like this:

String grade = "Grade is " + mark < 84 ? "HD"
    : mark < 74 ? "D"
    : mark < 64 ? "P"
    : mark < 54 ? "F"
    : "INVALID"; //case mark >= 85


This is a if-then-else statement which allows only one assignment.
a = (condition) ? value1 : value2;
I just replaced value2 with another statement.
Sometimes you have to add brackets for the compiler to understand it. In this case it should work just fine.

Flat View: This topic has 1 reply on 1 page
Topic: CAISI Project: Can developers end homelessness? Previous Topic   Next Topic Topic: string to int

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use