DISQUS

Tech-Recipes: Java switch/case statement syntax | Java programming | Tech-Recipes

  • Irene · 4 months ago
    Im a new learner of java. This example of switch case helped me to understand the syntax clearly. The program also provided more knowledge. I will visit this site whenever i get doubt.Thanks. Good work.
  • Akila · 3 months ago
    Inside the switch case program is it possible to access another program? how?
  • ktk · 3 months ago
    import java.io.*;
    import java.net.*;
    public class SvowelDPS
    {
    public static void main(String args[]) throws Exception
    {
    DatagramSocket ds=new DatagramSocket(40000);
    byte rb[]=new byte[100];
    System.out.println("Connection");

    DatagramPacket dp=new DatagramPacket(rb,rb.length);
    ds.receive(dp);
    System.out.println("Receive Data:"+new String(dp.getData()));
    String str=new String(dp.getData());
    String res="";
    str=str.trim();
    switch(str) //error on this point.How can i do?
    {
    case "a":
    res=("Vowel");
    break;
    case "A":
    res=("Vowel");
    break;
    case "e":
    res=("Vowel");
    break;
    case "E":
    res=("Vowel");
    break;
    case "i":
    res=("Vowel");
    break;
    case "I":
    res=("Vowel");
    break;
    case "o":
    res=("Vowel");
    break;
    case "O":
    res=("Vowel");
    break;
    case "U":
    res=("Vowel");
    break;
    case "o":
    res=("Vowel");
    break;
    default:
    res=("Not Vowel");
    break;
    }

    InetAddress cipadd=dp.getAddress();
    int cport=dp.getPort();
    byte sb[]=new byte[100];
    sb=res.getBytes();
    DatagramPacket dpsend=new DatagramPacket(sb,sb.length,cipadd,cport);
    ds.send(dpsend);
    System.out.println("Data send") ;
    }


    }
  • estiven · 2 months ago
    You cannot use strings on Swithc, you can only use int. So, it would be a better idea to capture the lettes ascii code and evaluate your switch accordingly.
  • mohd · 2 months ago
    since you are using characters try using ' ' (Single quotes) instead of using " " double quotes