New to dynamic class loading - could you help me?

Hi all!
Thanks so much for taking a minute to read my post.
I am a rookie at java and programming.
I have a program that needs to load a class (or java file) dynamically during runtime. (At least I think that is what it needs to do.)
I want the user of the program to be able to specify a .java or a .class file either somewhere on the local disk or network, but not necessarily in the same location as the program itself. Once that file is selected, I would like the program to be able to use that file as if it were a .class file created in the working directory when the program was compiled and created.
I have read a lot of the forums, and I think I need to write my own class loader. I tried creating a class loader, and the code is shown below. (I borrowed this code from some of the other forums I've read.)
Here is my problem.
1. Should I be trying to extend the ClassLoader class? Am I on the right track?
2. If I am on the right track, should I require the user of my program to select a previously compiled ".class" file? Or should I ask them to indicate a ".java" file, and try to compile the java file with the program?
3. I'm sure that if the above two questions are answered, the solution to this problem will become obvious. But for clarity, I should mention that with the current code (below), I keep getting a java.lang.NoClassDefFoundError inside the class FileClassLoader at the line:
c = defineClass (classname, buff, 0, buff.length); Obviously, I am not providing the right information to this FileClassLoader in order to create the class. Can you help me out?
Thank you in advance!
I really appreciate it!
Best Regards,
Julia
class SampleClass
  public void sampleMethod()
   final JFileChooser fc = new JFileChooser();
   int returnVal = fc.showOpenDialog(optionPane);
   if (returnVal == JFileChooser.APPROVE_OPTION) {
     File file = fc.getSelectedFile();
     try
        FileClassLoader loader = new FileClassLoader(file);
           Class cl = loader.loadClass(file.getName(),false);
        }catch ( ClassNotFoundException e ) {
       System.out.println("ClassNotFoundException");
     }catch (IllegalAccessException e) {
       System.out.println("IllegalAccess");      
     }catch( InstantiationException e) {
       System.out.println("Can't Instantiate That");
class FileClassLoader extends ClassLoader
     private File file;
     public FileClassLoader (File thisFile)
          this.file = thisFile;
     protected synchronized Class loadClass(String s, boolean bool) throws ClassNotFoundException
          Class c = null;
          try {
               int size = (int)file.length();
               byte buff[] = new byte[size];
               FileInputStream fis = new FileInputStream(file);
               DataInputStream dis = new DataInputStream (fis);
               dis.readFully (buff);
               dis.close();
               String classname = null;
               String filename = file.getName();
               int i = filename.lastIndexOf('.');
               if(i>0 && i<filename.length()-1)
                    classname = filename.substring(0,i);
               c = defineClass (classname, buff, 0, buff.length);
               resolveClass (c);
          } catch (java.io.IOException e) {
               e.printStackTrace();
          return c;
}

Hi!
If you really need to do that, you can give a look at my previous post at:
http://forum.java.sun.com/thread.jsp?forum=4&thread=285674
You can play with the code to suit your needs.
Hope this helps.

Similar Messages

  • TS3716 My relatively new ipod touch 16 gb either does not show up as a drive or everytime says it does not recognize my ipod when connected to add music.  I didn't have problems loading music originally, but this is a new occurrence.  Could you help?

    My relatively new ipod touch 16 gb either does not show up as a drive or everytime says it does not recognize my ipod when connected to add music.  I didn't have problems loading music originally, but this is a new occurrence.  Could you help?

    Hey, Thanks a lot.  It took quite a bit of time to resurrect this ipod.  I tried the upgrade again, but still would not recognize my ipod. So I went to the next step and reset my ipod, wiping of all of the information like it was new.  This helped my laptop see the ipod on itunes, but did not sync. So, I deleted the itunes off my computer completely, restarted and then reinstalled the newest itunes, and then restarted.  Finally, it recognized my ipod and started to download each song.  It took awhile as there was 602 songs, but finally it works.  Yea!!!  I never had any problem with my old nano, but this touch has been another animal for sure. Thank you again and also the community for information.  This was a helpful forum and will recommend to others if they get stuck with their ipod or iphone.  Take care, Karen

  • I moved to new house where I have wifi base station I made extension via TP-link power line adapter and connect my Airport utility 6.3.2, but I don't now how to set up as a second network with one IP address?Could you help me please?

    I moved to new house where I have wifi base station I made extension via TP-link power line adapter and connect my Airport utility 6.3.2, but I don't now how to set up as a second network with one IP address?Could you help me please?

    Urvergessen wrote:
    +You may have already done this, but do you have the first AirPort Express configured to "Allow this network to be extended"?+
    Could not find that setting anywhere.
    It's in AirPort Utility, AirPort panel, Wireless tab.
    When I'm within the range of the base station I connect normally, but further away the connection drops despite the fact that the other Airport is very close and light is green. Interestingly, my PB Pro has signal almost everywhere in the house, but my iPhone and Mac Mini don't. Most likely just a hardware difference?
    In AirPort Utility with the second Express, in the AirPort panel, Wireless tab, have you checked "Allow wireless clients"?
    The second AP does show an IP address: 10.0.1.3.
    With a "Configure IPv4" setting of "Using DHCP", that suggests that the second Express really is connecting to the first Express. In that case I have no other explanation of your your problem.

  • HT4623 I installed the new IOS 7 and now it asks me to inform a password, but I really do not know what password I need to inform. Could you help me:

    I installed the new IOS 7 and now it asks me to inform a password, but I really do not know what password I need to inform. Could you help me:

    if you mean it asks you to add a passcode to the device, you may say no.  It really tries to encourage you to put a code on, by asking twice.....

  • Hey sur. my name anas and am from morocco i've just got a new iMac 2011 with OSX 10.7 and i want to downgrade to 10.6 please could you help sur to solve this it

    hey sur. my name anas and am from morocco i've just got a new iMac 2011 with OSX 10.7 and i want to downgrade to 10.6 please could you help sur to solve this it

    anas guellaf wrote:
    it still make 3 bips before starting the IMAC.
    That is another problem not related to the Mac OS X version you are trying to use.
    Three beeps at startup means you have a bad ram module in the computer.  Did you install the ram or did it come from another owner this way?  The first problem you need to solve is the bad ram.
    When the iMac starts, go to the apple left side of the menu bar, About This Mac, More Info, System Report, Hardware, Memory and see what the report is on the memory...does the iMac report all memory modules that have been installed as OK or does it show bad memory?  If there is not any information, you then need to remove the memory modules and restart one at a time to see which is bad.
    On the bottom of the screen there should be a small door that you can remove with a small screw driver.  You need to lay the iMac flat, disconnect the power cord, remove that small door and remove the memory modules.  You can then put two in (if it has four) and see if it starts without the beeps.  Do that with each module so you find out which is bad.  Once you know the bad memory, you can buy a new module, just like the ones installed, so the iMac starts without the beeps.
    Next, you cannot use a DVD for another computer for your iMac unless it is from one that is identical to yours.  So, you need to talk to Apple and have them send the DVD for your particular iMac.

  • Dynamic class loading in J2ME

    Hi all,
    Couple of questions. Is dynamic class loading using classloaders supported in any, if not all versions of J2ME? I guess I should ask first, what exactly does J2ME cover? I see KVM, but do watches and PDA's, set top boxes, refrigerators and so forth all run the same J2ME JVM? Or are their "less feature full" versions? I was hoping the J2ME spec would be the "lowest common denominator" to program for, but I thought I read somewhere that small devices like watches may even have a "smaller" J2ME JVM or something, less capable. So can I write code for J2ME and it will run on all small devices like cell phones, pda's, and so forth? Or is there another J2ME version, perhaps small than J2ME.
    So, from what I have found so far, it appears dynamic class loading is done at startup from a DB (of sorts) as opposed to being able to dynamically find/load classes. If this is so, is there any way to support downloading and reloading new classes like you can with J2SE, such as the hot-swap feature of web servers? Does Class.forName() at least work in that you can "replace" a class with a new version, even if it is not able to have a separate classloader instance? My guess is that J2ME supports only a single classloader space, but I thought I read somewhere that Class.forName() is available. J2ME API shows it I believe, but I could be wrong.
    Any help on this topic would be appreciated.
    Thanks.

    Dynamic class loading is not available in most (if not all) J2ME profiles and configurations. Class.forName() is available (at least in the MID profile), but not to be used for dynamic class loading. It can be used when using device-specific APIs where you can try to load a class containing device specific methods (for example a class that works only on certain Nokia phones, and has methods playSound() and vibrate(), which are not available in MIDP), and if you catch a ClassNotFound exception you can load a class that doesn't use the device specific APIs and contains stubs of the methods, or you can disable certain features in you application that need those features. For an example implementation you can have a look at Nokia's Block Game example (available from their developer site - http://www.forum.nokia.com/main.html).
    As for your other more general questions about different JVM's and such, you should read all about the different configurations and profiles available in J2ME (plenty of information using in the J2ME link on this site).

  • Dynamic class loading over a network

    hi,
    Im tryin to run a simple little "Hello World" type app using RMI. What i want to know is what permissions i need to grant inorder to dynamically load (client side) the stubs and skeletons from my server. Currently i get an UnmarshalException with a nested ClassNotFoundException and the helpful message "access denied to class loader". Any help is appreciated.
    Thanks in advance,
    Alex

    It is hard to tell what the problem is with out a stack trace from the exception. Perhaps in the future you would be kind enough to supply one.

  • Dynamic class loading failed, why?

    Hi there!
    We are using WebLogic 5.1 togehter with Apache1.3.22/Tomcat4.01. It all worked
    fine for about 2 month. All of a sudden, dynamic class loading refuses to work.
    From one day to the other I got the excpetion: javax.naming.CommunicationException.
    Root exception is weblogic.rmi.UnmarshalException: Unmarshalling return
    - with nested exception:
    [java.lang.ClassNotFoundException: class com.dsh.egb.aks.betrieb.ejbs.AnmeldenEJBHomeImpl_ServiceStub
    previously not found]
    Why does this happen? I can not remember having touched any properties.
    Please help,
    Heiner

    If you were relying on client network classloading stubs from WebLogic, you
    can test if it still works by pointing your browser to
    htpp://yourweblogic:7001/classes/com/dsh/egb/aks/betrieb/ejbs/AnmeldenEJBHomeImpl_ServiceStub.class
    Heiner Amthauer <[email protected]> wrote:
    Hi there!
    We are using WebLogic 5.1 togehter with Apache1.3.22/Tomcat4.01. It all worked
    fine for about 2 month. All of a sudden, dynamic class loading refuses to work.
    From one day to the other I got the excpetion: javax.naming.CommunicationException.
    Root exception is weblogic.rmi.UnmarshalException: Unmarshalling return
    - with nested exception:
    [java.lang.ClassNotFoundException: class com.dsh.egb.aks.betrieb.ejbs.AnmeldenEJBHomeImpl_ServiceStub
    previously not found]
    Why does this happen? I can not remember having touched any properties.
    Please help,
    Heiner--
    Dimitri

  • Dynamic class loading when CODEBASE is unreachable. A bug?

    Let us suppose that we have a large-scale distributed application with ca. 1000 participants communicating via RMI and utilizing dynamic class loading. As we all know, a HTTP code server must be available for this purpose in order to provide dynamically downloaded code, usually the communication proxy code of remote objects. In a real-world scenario, the HTTP server will never be 100% available, so that we will have cases that a Java process will not be able to download the necessary Java classes, causing the RMI communication to fail with a ClassNotFoundException or similar exception. In such a case, a robust application would perform some recovery activities and retry the remote call. Eventually, the HTTP server becomes available again and the distributed system recovers automatically. This seems to work fine with J2SE 1.4.2_10, but not with 1.4.2_11 and newer versions. Considering Java 5, the Update 9 exhibits the same problem.
    For tracking down the problem, I've written a simple distributed test application, consisting of a client and a server. A server listens on a port, and sends a MarshalledObject to the client. The code of the MarshalledObject is annotated with the value of the "java.rmi.server.codebase" system property. The annotation contains an URL of the JAR file containing the code of the original object. The client connects to the server, reads data form the socket and unmarshalls the original object. This is basically the same procedure as when objects are accross the wire as arguments/return values/exceptions by the RMI/JRMP engine. This procedure is repeated forever in the loop. Due to the fact that the client's CLASSPATH doesn't contain the code of the original object, this code should dynamically be loaded from the HTTP server using the appropriate annotation provided by the server.
    If we start the client while the HTTP server is down, the client will keep generating the ClassNotFoundException over and over again, as expected. So far, so good. If we now start the HTTP server while the client is still running, we will observe different behaviors, depending on the version of the client's JVM:
    1. In J2SE 1.4.2_10, the client will download the code from the HTTP server and successfully unmarshal the original object sent by the server. ClassNotFoundExceptions will not be generated again.
    2. In J2SE 1.4.2_11, 1.4.2_12 and 1.4.2_13 as well as in J2SE 5.0 Update 9, the client will continue generating ClassNotFoundExceptions. Analysis of the HTTP server's access log shows that there were no attempts to download the JAR file required for unmarshaling the object sent by the server.
    It seems that in the newer JVM versions the RMI engine remembers URLs which have failed and does not attempt to access them anymore. Althogh this may have some advantages considering the overall network load, the dynamical class loading becomes practically useless in productive large distributed systems. The very first attempt to load the codebase of the communication peer must succeed, otherwise the whole process must be restarted for the communication to work, which is a very expensive (and for most customers unacceptable) operation in terms of preformance and resources usage.
    Should this be seen as a bug or a feature of the JVM? What do you think?
    Regards,
    Miran
    Here is the code to reproduce:
    Server code
    package server;
    import java.net.*;
    import java.rmi.*;
    import java.io.*;
    public class Server implements Serializable {
      private int value = 42;
      public Server() {
      public String toString() {
        return "The Answer is " + value;
      public static void main( String[] args ) {
        if( args.length!=1 ) {
          System.out.println( "Usage: server.Server <port>" );
          System.exit( 1 );
        try {
          MarshalledObject data = new MarshalledObject( new Server() );
          int port = Integer.parseInt( args[0] );
          ServerSocket serverSocket = new ServerSocket( port );
          System.out.println( "Accepting connections..." );
          while( true ) {
            Socket s = serverSocket.accept();
            new Thread( new SocketHandler( s, data ) ).start();
        } catch( Exception ex ) {
          ex.printStackTrace();
        System.exit( 0 );
      public static class SocketHandler implements Runnable {
        private Socket s;
        private Serializable data;
        public SocketHandler( Socket s, Serializable data ) {
          this.s = s;
          this.data = data;
        public void run() {
          try {
            OutputStream os = s.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream( os );
            oos.writeObject( data );
            oos.close();
            os.close();
            s.close();
            System.out.println( "Serving socket succeeded" );
          } catch( Exception ex ) {
            System.out.println( "Serving socket failed" );
            ex.printStackTrace();
    Client code
    package client;
    import java.rmi.*;
    import java.net.*;
    import java.io.*;
    public class Client {
      public static void main( String[] args ) {
        if( args.length!=1 ) {
          System.out.println( "Usage: client.Client <port>" );
          System.exit( 1 );
        try {
          if( System.getSecurityManager()==null ) {
            System.setSecurityManager( new RMISecurityManager() );
          int port = Integer.parseInt( args[0] );
          for( int i = 1; true; ++i ) {
            try {
              Socket s = new Socket( "localhost", port );
              InputStream is = s.getInputStream();
              ObjectInputStream ois = new ObjectInputStream( is );
              Object o = ois.readObject();
              ois.close();
              is.close();
              s.close();
              Object umo = ((MarshalledObject) o).get();
              System.out.println( i + ". Retreiving MarshalledObject succeeded: "
                                  + umo );
            } catch( Exception ex ) {
              System.out.println( i + ". Retreiving MarshalledObject failed" );
              ex.printStackTrace();
            System.out.println( i + ". Waiting for 10 sec" );
            Thread.sleep( 10000 );
        } catch( Exception ex ) {
          ex.printStackTrace();
        System.exit( 0 );
    Start command for the server
    java -cp server.jar -Djava.rmi.server.codebase="http://localhost/playground/server.jar" server.Server 33933
    Start command for the client
    java -cp client.jar -Djava.security.policy=all.policy client.Client 33933
    The policy.all file should look as follows
    // All permissions
    grant {
       permission java.security.AllPermission;
    };The server.jar file should only contain the classes from the server package. This file should also be made accessible via HTTP (e.g. by using the Apache HTTP server).
    The client.jar file should only contain the classes from the client package.

    no body know about this??

  • Dynamic Class Loading with interface

    Hello
    I would appreciate any help on the following problem.
    I need to load all classes in a particular directory and its subdirectories (top directory is known but not in the classpath) which implement a predefined interface. At the moment I am using a lot of reflection to accomplish this and believe it can be avoided somehow using the fact that I know these classes have to implement a predefined interface.
    At the moment, I am searching through the directory and subdirectory, loading all names of classes into a vector using a custom URLClassloader, and then load all classes in the vector into modulecontainers to populate a defaultmutabletree which is displayed on the gui.
    I'm sure that knowing the interface means there's a more straightforward way.
    Thanks in advance.

    Finally i've found out myself, i've read some postings in this forum and put them all together, so that my webstart-application finally works the way i want...
    That was the topic:
    Downloading a jar-file and starting a class from this jar-file within a webstart application (dynamic class loading).
    I'll post my final solution for this problem, may be it would be useful in future for anyone else.
    //grant all permissions on the clientside
    Policy.setPolicy( new Policy() {
    public PermissionCollection getPermissions(CodeSource codesource) {
    Permissions perms = new Permissions();
    perms.add(new AllPermission());
    return(perms);
    public void refresh(){
    //get the current classloader
    ClassLoader cl = MyLoadedClass.class.getClassLoader();
    //create a new url-classloader while using the current classloader
    URL[] urls = new URL[1];
    File f = new File(new String(jarName));
    urls[0] = f.toURL();
    URLClassLoader ul = new URLClassLoader(urls, cl);
    //load a class from jarfile
    Class c = ul.loadClass(new String(className));
    //get an object from loaded class
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof KnownInterface){
    // Yep, lets call a method we know about. */
    KnownInterface client = (KnownInterface) o;
    client.doAnything();

  • Dynamic class loading with Webstart

    Hello !
    //within the jar-file at the webstart-directory
    public interface MyFrame{
    public void createFrame();
    //within the jar-file dynamically downloaded
    public class MyExtFrame extends JFrame implements MyFrame{
    String className = "MyExtFrame";
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    JarClassLoader jarLoader = new JarClassLoader (cl, jarFile));
    /* Load the class from the jar file and resolve it. */
    Class c = jarLoader.loadClass (className, true);
    /* Create an instance of the class.
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof MyFrame){
    // Yep, lets call a method we know about. */
    MyFrame client=(MyFrame) o;
    //call a class-method (here creates the whole gui-object at once)
    client.createFrame();
    This is the code i'm using and i've encountered following problem, if i put this code into an application without webstart, anything works fine, but with webstart i'll get a: java.lang.NoClassDefFoundError
    Then i've put the MyFrame-classes into the downloaded jar-file, but this won't work either, i'll get a ClassCastException.
    What do i have to do, to become it working ?
    Thanks for any conclusions and help.
    Michael

    Finally i've found out myself, i've read some postings in this forum and put them all together, so that my webstart-application finally works the way i want...
    That was the topic:
    Downloading a jar-file and starting a class from this jar-file within a webstart application (dynamic class loading).
    I'll post my final solution for this problem, may be it would be useful in future for anyone else.
    //grant all permissions on the clientside
    Policy.setPolicy( new Policy() {
    public PermissionCollection getPermissions(CodeSource codesource) {
    Permissions perms = new Permissions();
    perms.add(new AllPermission());
    return(perms);
    public void refresh(){
    //get the current classloader
    ClassLoader cl = MyLoadedClass.class.getClassLoader();
    //create a new url-classloader while using the current classloader
    URL[] urls = new URL[1];
    File f = new File(new String(jarName));
    urls[0] = f.toURL();
    URLClassLoader ul = new URLClassLoader(urls, cl);
    //load a class from jarfile
    Class c = ul.loadClass(new String(className));
    //get an object from loaded class
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof KnownInterface){
    // Yep, lets call a method we know about. */
    KnownInterface client = (KnownInterface) o;
    client.doAnything();

  • Dynamic class loading from String name

    Hello all,
    I have a question for dynamic class loading:
    If I have a String variable that represents a class name, how can i use it to make dynamically an object of the class tha the string variable represents?
    For example i have a string like this
    String classname="String";
    Using this i want to make a new String object .
    Can anyone tell me how can i do this(example plz)?

    I have worked out the code and this works fine:
    import java.lang.*;
    class dynamictestname{
         public dynamictestname() {
        public static Class test(String objname){
             try{
             Class theClass = Class.forName(objname);
                 return theClass;
            } catch (ClassNotFoundException e)
                throw new NoClassDefFoundError (e.getMessage());
         public static void main (String [] args){
              String classname="java.lang.String";
              Class thisClass=dynamictestname.test(classname);
              try{
              Object instance = thisClass.newInstance();
              }catch(InstantiationException e){
              }catch(IllegalAccessException ie){
    }The new problem i 've faced is that i can't instatiate a new object by the class i have created.I saw some examples with use of the java.lang.reflect but this class i used with user created classes which have methods that the user wants to run dynamically.
    I just want to make an object from the class and give it a value.
    For example if the object i have created with the
    Object instance = thisClass.newInstance();is an object of java.lang.String class
    how can i do something like this below dynamically from instance object :
    String x="TEST ";
    Thanks for the help..

  • "Open-code" statements / dynamic class-loading

    Hi!
    I am using reflection to dynamically load classes in an application where the classes are read dynamically from a text-box (or a file) in a running Java-session. When a class is loaded, instances can be made. All this works fine.
    Now consider the following example:
    1. First a class Sample1 is loaded:
    public class Sample1 {
    public int i;
    Sample1() {
    i=5;
    2. I want to make an instance of Sample1 like:
    Sample1 s1=new Sample1();
    To use dynamic load, this "open-code" statement needs (?) to be put in a class Sample2. This works fine, and the method()-method can be invoked (using reflection):
    public class Sample2 {
    public Sample1 s1;
    public void method(String args[]) { 
    s1=new Sample1();
    System.out.println(s1.i);
    3. At last I want to refer (print) to s1.i (and again the code is wrapped in a class), but this doesn't work:
    public class Sample3 {
    public void method(String args[]) { 
    System.out.println(s1.i);
    The problem is how the statement:
    Sample1 s1=new Sample1();
    can be executed so that s1 can be referenced in the running Java-session.
    Any suggestions how to solve this design-problem? What I want to do is make "open-code" statements that can be referenced in the running Java-session.
    Regards,
    Jesper

    Typically, your 'open code statements' would be wrapped in a class that implements a suitable interface. If you wish to have state shared between your generated classes, then some form of common store (such as a Map) needs to be used to hold the state, and this made accessible to the implementations.
    eg:interface PluginMethod { void apply (Map state) ;}
    public class Sample2 implements PluginMethod {
      public void apply (Map state) {
         state.put("s1", new Sample1());
    public class Sample3 implements PluginMethod {
      public void apply (Map state) {
         System.out.println(((Sample1)state.get("s1")).i);
    }Alternatively, any of the normal methods of sharing state between objects can be used if closer coupling is desired. Dynamic class loading doen't really come into it- you use the same techniques as you normally do.
    Pete

  • From Sweeden - could you help me please ( i've tryed to do that for almost one day)

    i thing i have aloop problem, could you help me please. i trying to do if user not put in correct value (number instead of a letter or vice versa ) how can the program go back to first menu ( i have been studying for 3 weeks)
        enter code here
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace @break
        class Program
            static void Main(string[] args)
                //Meny
                Console.WriteLine("\n HÄNGA GUBBE\n");
                Console.WriteLine(" 1) Lägg till ord");
                Console.WriteLine(" 2) Lista alla ord");
                Console.WriteLine(" 3) Spela");
                Console.WriteLine(" 4) Avsluta");
                int Valet;
                Console.Write("\n\tVälj 1-4:  ");
                Valet = int.Parse(Console.ReadLine());
                switch (Valet)
                    case 1:
                        Console.WriteLine("\n lägg ett till ord! ");
                        break;
                    case 2:
                         Console.WriteLine("\n Lista med alla ord :\n");
                         string[] array = { " Lev", " Skratta", " Gledje", " Gråt", " Njut" };
                         Array.Sort<string>(array);
                         foreach (var c in array)
                             Console.WriteLine(c);
                         Console.WriteLine("\n");
                         break;
                    case 3:
                        string guesses, bokstäver;
                        Console.Write("\n Hur många fel får man ha? ");
                        guesses = (Console.ReadLine());
                        Console.WriteLine(" Utmärkt, då spelar vi!\n");
                        Console.WriteLine(" Felgisningar :" + "0/" + guesses);
                        Console.Write(" Gissade bokstäver " );
                        bokstäver = (Console.ReadLine());
                        Console.WriteLine("Aktuellt ord");
                        Console.Write("Gissa bokstav : "+bokstäver+" \n");
                        break;
                    case 4:
                        Console.WriteLine("\n  HEJ DÅ! \n");
                        Console.Beep();
                        break;
                    //avbryter while loopen, avslutar spelet
                  

    What do you mean by "lots of problem"? The code I posted certainly compiles and runs just fine. Copy the following code into your Program.cs file in Visual Studio and run it and you will see that it works:
    using System;
    namespace ConsoleApplication1
    class Program
    static void Main(string[] args)
    //Meny
    Console.WriteLine("\n HÄNGA GUBBE\n");
    Console.WriteLine(" 1) Lägg till ord");
    Console.WriteLine(" 2) Lista alla ord");
    Console.WriteLine(" 3) Spela");
    Console.WriteLine(" 4) Avsluta");
    bool exit = false;
    do
    int Valet;
    Console.Write("\n\tVälj 1-4: ");
    try
    Valet = int.Parse(Console.ReadLine());
    catch (Exception)
    Console.WriteLine("Error....!");
    continue;
    switch (Valet)
    case 1:
    Console.WriteLine("\n lägg ett till ord! ");
    break;
    case 2:
    Console.WriteLine("\n Lista med alla ord :\n");
    string[] array = { " Lev", " Skratta", " Gledje", " Gråt", " Njut" };
    Array.Sort<string>(array);
    foreach (var c in array)
    Console.WriteLine(c);
    Console.WriteLine("\n");
    break;
    case 3:
    string guesses, bokstäver;
    Console.Write("\n Hur många fel får man ha? ");
    guesses = (Console.ReadLine());
    Console.WriteLine(" Utmärkt, då spelar vi!\n");
    Console.WriteLine(" Felgisningar :" + "0/" + guesses);
    Console.Write(" Gissade bokstäver ");
    bokstäver = (Console.ReadLine());
    Console.WriteLine("Aktuellt ord");
    Console.Write("Gissa bokstav : " + bokstäver + " \n");
    break;
    case 4:
    Console.WriteLine("\n HEJ DÅ! \n");
    Console.Beep();
    exit = true;
    break;
    //avbryter while loopen, avslutar spelet
    } while (!exit);
    If you can't get this to work despite someone actually giving the exact code you should probably ask some developer to help you.
    If you have some logical issues in your code that's another issue. Please start a new thread if you have a new question.
    Note that the forums are not for anyone else to write an entire application or class for you though :)
    Please remember to close your threads by marking helpful posts as answer.

  • TS1453 Hi, I bought Apple tv traying to rent a movie but there problem with itunes, and there is on apple tv don't have my country. could you help me please how can I solve this problem?

    Hi, I bought Apple tv traying to rent a movie but there problem with itunes, and there is on apple tv don't have my country. could you help me please how can I solve this problem?

    Whinston,
    I live in Azerbaijan. Recently I bought apple tv in New York. When I come back to my country tried to rent movies from my country but couldn't find my country name on apple tv menu, so there is a problem I don't know how to fix it. is there have another way to take a rent movies?

Maybe you are looking for

  • Install BOE on 64 bit OS

    I have windows server 2008 (64 bit), can I install Crystal Reports & BOE XI 3.1 on the server, will it work without any issue. Reason for asking this is, I installed Oracle 10g Client (32 bit) on the server and stated getting problems, it didn't crea

  • How do you delete your verizon wireless community profile?

    How do you delete a profile on this thing?

  • Win2000 System Log Error caused by NI-Serial

    I've installed a PCI-485/2 board into my computer along with NI-Serial 1.45. The board passes diagnostics and works properly, but every time I reboot my Win2000 computer I get a System Error log entry ID 18: "No Parameters subkey was found for user d

  • Disabling Distinct Feature in Answers

    Hi All, I'm having a hard time to figure out the way of diabling Distinct values in Answers. I have 2 tables Dim and a Fact. The Sql generated in Answers is perfect. I executed this query in SQL database and it gave proper results(30400 rows). But th

  • Space Designer Surround Bug

    I'm pretty sure this a new bug... In a surround session choosing a Surround IR in Space Designer results in a significant delay to the reverb. (not the case with a stereo IR) ... Anyone? Logic 9.1 Snow Leopard 10.6.2 Keith Moore