Need help with java file scanner and objects

Hi, i've got an assignment that asks me to do these, but i cant seem to get around in solving it. Any help will be much appreciated. TYVM!
Create a class called TVProgram that can store some important details of a television program:
- name of the show
- the channel the show is on
- the start time (in 24-hour format)
- the end time (in 24-hour format)
Write a program that uses this class.
Your program will read a list of TV programs, making up a schedule for an evening's TV: for you convenience, you will be able to download a sample file listing. The listing will consist of one line for each of the above fields, in the above order, for each program, followed by a line containing only the "#" character. For example, here is the start of such a file.
At the Movies
ABC
1800
1830
The Einstein Factor
ABC
1830
1900
Your program should start with a little menu to prompt whether to read from standard input or a file:
Please choose a number for the way you will input the TV schedule:
1. Read from standard input
2. Input from a file
Your program should first read the complete schedule, then loop through all the programs in the schedule and prompt the user as to whether they want to record the program or not. For example, the program should print:
At the Movies is showing on ABC from 1800 to 18.30.
Do you want to record it: type Y or N.
If the user types Y then the program sets this T Vprogram to be recorded. If the user types N, the program goes to the next entry and prompts the user again. If the user types something other than a Y or N (or y or n), then the program should prompt for a proper answer:
Do you want to record it: type Y or N.
Once the complete schedule has been shown to the user, the program loops through those that the user has said they want to record and checks for any clashes---i.e. any times at which the user wants to record two programs at the same time. For any clashes, your program should show these to the user and insist that only one be selected for being recorded. For example:
At 1830 you want to record both 1. The Einstein Factor on ABC and 2. The Biggest Loser on Ten.
Please pick option 1 or 2 to record.
Again, if the user selects an option other than 1 or 2 in the above, then the program should make the user to make another selection until they type a legal value.
If the schedule is in time-start order (see "Assumptions" below), then a simple way to check for clashes is:
- as you loop through the schedule of shows, keep track of the latest end-time the user wants to record;
- if any program the user says they want to record has a start-time before this latest end-time, then this is a clash.
There are different ways to keep track of clashes: you can keep an array (a list of clashes) of arrays (each of these is the list of clashing programs); you could create a Clash class.
Finally, after going through all clashes, print out the list of programs that the user still wants recorded.
Here is the list of programs that will be recorded for you:
From 1830 to 1930, The Biggest Loser, on Ten.
From 1930 to 2030, Who Do You Think You Are, on SBS
-----

* @(#)TVProgram.java
* @author      Okky Satya
* @version 1.00 2008/3/29
import java.util.*;
import java.io.*;
public class TVProgram {
     private String name;
     private String chnl;
     private int strt;
     private int ends;
     public TVProgram(String showName, String channel, int start, int end ){
          this.name = showName;
          this.chnl = channel;
          this.strt = start;
          this.ends = end;
    public static void readFileInput() {
    List prog = new ArrayList();
    Scanner inputFile = null;
     try
    inputFile = new Scanner(new File("tv_schedule"));
     catch (FileNotFoundException fe)
    System.out.println("File not found!");
    System.exit(0);
    while(inputFile.hasNext()== true){
         while (inputFile.nextLine()!="##")
              new TVProgram;
    public static void readInput(){
    public static void loopInput(){
    public static void showList(){
    public static void checkUserList(){
    public static void main(String[] args){
         int menuChoice = 0;
         System.out.println("Please choose a number for the way you will input the TV schedule:\n  1. Read from standard input\n  2. Input from a file");
         switch(menuChoice){
              case 1:
                   readInput();
                   break;
              case 2:
                   readFileInput();
                   break;
         loopInput();
         checkUserList();
         showList();
}

Similar Messages

  • Need help with java File IO ( Removing the first line from a file )

    Hi guys ,
    I am currently doing a project in which I need to extract out the values from the second line of a file to the end. The question is how do I ignore the first line ??
    I thought of two possible answers myself. One is to use randomaccessfile to read and rewrite. But the file may be HUGE so storing the whole file in memory is not a very good idea.
    Second is to jump to second line before doing while ((str = in.readLine()) != EOL) ... or just delete the first line from the file. Can anyone suggest a better solution or show me some sample codes ? Thanks.
    regards
    billyam

    Just skip the first line (bufferedReader.readLine()), add a comment, and then handle the rest of your file

  • Need help with my iPhone 5 and my Macbook Pro.

    Need help with my iPhone 5 and my Macbook Pro.  I was purchased some music on itunes at my mac. Some reason I deleted those music from both on Mac and iPhone 5.  Today, I went to my iPhone iTunes store inside of iCloud to redownload my puchased. But those song won't able to sync back to my iTunes library on my Mac.  Can anyone help me with that ??....
    iPhone 5, iOS 6.0.1

    You've posted to the iTunes Match forum, which your question does not appear to be related to. You'll get better support responses by posting to either the iTunes for Mac or iTunes for Windows forum. Which ever is more appropriate for your situation.

  • Need help with connecting file inputs to arrays

    In this assignment I have a program that will do the following: display a list of names inputed by the user in reverse order, display any names that begin with M or m, and display any names with 5 or more letters. This is all done with arrays.
    That was the fun part. The next part requires me to take the names from a Notepad file, them through the arrays and then output them to a second Notepad file.
    Here is the original program: (view in full screen so that the code doesn't get jumbled)
    import java.io.*;       //Imports the Java library
    class progB                    //Defines class
        public static void main (String[] arguments) throws IOException
            BufferedReader keyboard;                                  //<-
            InputStreamReader reader;                                 //  Allows the program to
            reader = new InputStreamReader (System.in);               //  read the the keyboard
            keyboard = new BufferedReader (reader);                  //<-
            String name;                 //Assigns the name variable which will be parsed into...
            int newnames;               //...the integer variable for the amount of names.
            int order = 0;              //The integer variable that will be used to set the array size
            String[] array;             //Dynamic array (empty)
            System.out.println (" How many names do you want to input?");   //This will get the number that will later define the array
            name = keyboard.readLine ();
            newnames = Integer.parseInt (name);                                         // Converts the String into the Integer variable
            array = new String [newnames];                                               //This defines the size of the array
            DataInput Imp = new DataInputStream (System.in);       //Allows data to be input into the array
            String temp;                                       
            int length;                                                                  //Defines the length of the array for a loop later on
                for (order = 0 ; order < newnames ; order++)                                //<-
                {                                                                           //  Takes the inputed names and
                    System.out.println (" Please input name ");                            //  gives them a number according to
                    temp = keyboard.readLine ();                                           //  the order they were inputed in
                    array [order] = temp;                                                  //<-
                for (order = newnames - 1 ; order >= 0 ; order--)                                //<-
                {                                                                                //  Outputs the names in the reverse 
                    System.out.print (" \n ");                                                   //  order that they were inputed
                    System.out.println (" Name " + order + " is " + array [order]);             //<-
                for (order = 0 ; order < newnames ; order++)                                  //<-
                    if (array [order].startsWith ("M") || array [order].startsWith ("m"))     //  Finds and outputs any and all
                    {                                                                         //  names that begin with M or m
                        System.out.print (" \n ");                                            //
                        System.out.println (array [order] + (" starts with M or m"));         //
                    }                                                                         //<-
                for (order = 0 ; order < newnames ; order++)                                            //<-
                    length = array [order].length ();                                                   //
                    if (length >= 5)                                                                    //  Finds and outputs names
                    {                                                                                  //  with 5 or more letters
                        System.out.print (" \n ");                                                      //
                        System.out.println ("Name " + array [order] + " have 5 or more letters ");      //<-
    }The notepad file contains the following names:
    jim
    laruie
    tim
    timothy
    manny
    joseph
    matty
    amanda
    I have tried various methods but the one thing that really gets me is the fact that i can't find a way to connect the names to the arrays. Opening the file with FileInputStream is easy enough but using the names and then outputing them is quite hard. (unless i'm thinking too hard and there really is a simple method)

    By "connect", do you just mean you want to put the names into an array?
    array[0] = "jim"
    array[1] = "laruie"
    and so on?
    That shouldn't be difficult at all, provided you know how to open a file for reading, and how to read a line of text from it. You can just read the line of text, put it in the array position you want, until the file is exhausted. Then open a file for writing, loop through the array, and write a line.
    What part of all that do you need help with?

  • Need Help with .nnlp File.............A.S.A.P.

    I'm having a problem also with my JNLP file. I have downloaded the program onto one computer and that computer is using j2re1.4.2_04
    The other computers I believe are all running j2re 1.4.2_05
    I'm not sure if that's make a difference, but on the computer with j2re 1.4.2_05 when going to the site where the .jnlp file is located, the application comes up and says Starting Application. After it gets to that screen it just stays there. I really need help with this as soon as possible.
    Here is my .jnlp file listed below:
    <?xml version="1.0" encoding="utf-8"?>
    <jnlp
      spec="1.0+"
      codebase="http://www.appliedsolutions.com/placewiz"
      href="Placewiz.jnlp">
      <information>
        <title>Placement Wizard 4.0</title>
        <vendor>Applied Solutions, Inc.</vendor>
        <homepage href="index.html"/>
        <description>Placement Wizard 4.0</description>
        <description kind="short">Short description goes here.</description>
        <offline-allowed/>
      </information>
      <resources>
        <j2se version="1.4+"/>
        <j2se version="1.3+"/>
         <j2se version="1.5+"/>
        <jar href="Placewiz.jar"/>
      </resources>
      <security>
          <all-permissions/>
      </security>
      <application-desc main-class="com/asisoftware/placewiz/loader/Exec">
    </jnlp>

    This was due to a change in 1.4.2_05
    the main class attribute
    main-class="com/asisoftware/placewiz/loader/Exec">is wrong - it should be:
    main-class="com.asisoftware.placewiz.loader.Exec">this didnt seem to mater before 1.4.2_05, but some change in java since then caused this bad class specification to stop loading.
    /Andy

  • I need help with my text tone and I have ring tone. no text tone for the 4s.

    I need help with my text tone. I have ring tone no text tone. I have a 4s.

        Hi Sarar2333!  Let's get your text tones working again!
    Here's a link with instructions how to enable and change your alert sounds for your text/notification settings on your iPhone 4S: http://vz.to/1stiF8a.  You can ensure text tones are enabled by selecting a tone in the "Text Tone" setting.  Let me know how that works out for you.  Thanks!
    AnthonyTa_VZW
    Follow us on Twitter @VZWSupport

  • Need help with buying graphics card and ram for MSI 865PE NEO 2-V

    Hi,
    I want to buy 1GB of ram for motherboard MSI 865PE NEO 2-V I need help with finding correct parts.
    I also want to buy 512Mb or 1GB graphics card.
    as i said before i need help with finding correct ones so they match motherboard, I would appreciate if any one would post link to cheap and fitting parts.
    I found graphics card allready, i just need to know if it will fit.
    the card is
    NVIDIA GeForce 7600 GS (512 MB) AGP Graphics Card
    Thanks for help.

    here you can see test reports for your mobo:
    http://www.msi.com/product/mb/865PE-Neo2-V.html#?div=TestReport

  • Need help with clickbios ii terminolgy and values. Z77A-GD65 / 3770k

    Hello All 
    I recently purchased a Z77A-GD65 board and after searching I've found the differences in terminology between this and my previous Asus board but still have a couple of settings I cant find any info on.
    System Specs:
    motherboard: msi z77a-gd65
    cpu: intel 3770k
    ram: corsair vengeance 2133mhz 1.5v
    psu: corsair 850w
    First things first is I believe I am running in turbo oc mode. I've selected the oc genie tab on the center right of the bios screen and proceeded to change settings there. With cpu voltage on auto and vdroop set to 50% at 4.6ghz. (I'll try and get screenshots of bios settings soon)
    The following are the terms I need help with:
    In the my oc genie section;
     1. Long duration power limit
     2. Long duration maintained
     3. Short duration power limit
    In the main overclocking section;
     4. Digital Compensation level (not in owners manual, options auto/high)
     5. Cpu core ocp expander (enabled for overclock 4.5ghz+?)
    In the CPU Features section;
     6. long duration power limit w (does "w" stand for watts?)
     7. long duration maintained s   (does "s" stand for seconds?)
     8. short duration power limit
     9. primary plane current limit a  (does "a" stand for amps?)
    10. secondary plane current limit
    11. primary plane turbo power limit
    12. secondary plane turbo power
    I know those are a lot of settings, but would appreciate any simple definitions as to what they do and recommended values for mild overclocking (4.5-4.80)
    Also on my previous board (Asus P8P67 Pro) my 3770k was stable in prime95 for 18 hrs at 4.5ghz fixed 1.155v with only ram timings put in manually and LLC set to extreme.(or whatever max is called in asus bios) Voltage was fixed and everything else was defailts.

    Well I'm back.  Been digging around for a few days and found some answers to my questions.
    First things first s that for some reason I could not adjust voltage values with the + or - symbols. Clearing cmos did not help this. I had to reflash the bios to get this functionality back as well as clearing cmos before and after the flash.
    So I figured out the values in the oc genie section are the same as the normal section but only used when your using the oc genie. (numbers 1-3)
    Digital compensation level and ocp expander should be set to high and enabled respectively when going for higher overclocks. (4 and 5)
    Now for the rest of my questions ( 6 through 12) I have found suggested settings and some info after hours and hours of searching but still have a couple of questions about them.
    Long/short duration power limit, and primary/secondary plane turbo limit. I see suggestion settings of 250 or 255. I take it this is simply max supplied watts to the chip? If so why the 250/255 values? Is that the highest the board will give? Is plane turbo limit related to the enhanced turbo stated and how much wattage can be drawn there while the other limit is for any non turbo frequencies?
    Long duration maintained, I've seen 60 suggested a lot. Why is this?
    There's not an over abundance of info on these boards as compared to asus so it seems info is a little less documented and video tutorials explaining things are next to none.
    Any help would be appreciated. Thanks 

  • HT4528 I need help with my I phone and I can get verizon to let me on there to talk and I will have to have my phone so that I can do what you tell me to do

    I need help with my phone it is not ringing and I cant figure where in here to make it so it will something has been pushed so I cant hear any calls or texts

    Not when you insist on being so impatient.
    These are user to user support forums.  No one here is paid to read or respond to messages.
    Try explaining the issue instead of the jumbled, rambling mess of a title and we will be happy to assist.

  • Need help with batch file for javac.exe and java.exe

    I have this in my batch file:
    c:\jdk1.3.1_05\bin\javac
    What symbol do I need to be able to run this from cprompt with any file following it

    Thanks could remember that for nothing

  • Need help with Java Programming

    Hello All,
    I dont know how to save all the lines separatly and then work with the numbers?
    Example TxtIn:
    2 5
    0 9 2 3 4 // I dont know how many lines will appear, and dont know how many numbers in a line
    1 2 3 9
    1 5 4
    2 0 0 5 6
    2 5 1 9
    4 6 1 5
    4 9 1 8
    9 1 4 8
    9 5 0
    Example TxtOut:
    1 9 4 0
    I would really appreciate your help in this.
    In my code, i only past one time in the text file, and clear the numbers of the list, but i need to make more check =S
    Here is the code:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.StringTokenizer;
    * @author Antonio
    public class web {
        /** Creates a new instance of Main */
         * @param args the command line arguments
        public static void main(String[] args) throws FileNotFoundException {
            int contador;
            ArrayList<Integer> lista = new ArrayList<Integer>();
            Scanner scn = new Scanner(new File("in.txt"));
            try {
            PrintWriter fileOut = new PrintWriter(new FileWriter("out.txt"));
            int ciudades = scn.nextInt();
            int aerolineas = scn.nextInt();
            int ciudadabuscar = scn.nextInt();
            int aerolinea = scn.nextInt();
            int bandera=0;
            while (scn.hasNextLine()){
                    String cad = scn.nextLine();
                    StringTokenizer st = new StringTokenizer(cad," ");
             while (st.hasMoreTokens())
                    String t = st.nextToken();
                    lista.add ( Integer.parseInt(t) );
               int a[]= new int[lista.size()];
               for (int x=0; x<lista.size(); x++)
                            a[x] = lista.get(x);
                          for (int x=0; x<lista.size(); x++)
                   for (x=1;x<lista.size();x++){
                            if (ciudadabuscar == a[0] && aerolinea == a[1])//tenia x=1
                                for (x=2;x<lista.size();x++)
                                { fileOut.printf("%d ",a[x]);
                                  ciudadabuscar= a[2];
                                  bandera = 1;}
                         lista.clear();
            if(bandera==0){
            fileOut.println("No hay destinos posibles por esta línea");
            fileOut.close();
            }catch(FileNotFoundException ex){}catch(IOException ex){}
    }

    #1 Solution is the same as i am working but...if i found AND another pair needs tobe searched...i dont know how to start again with step 1...
    i onli continues reading..that is why i am never show
    2 5//i am reading the file looking for 2 and 5
    0 9 2 3 4
    1 2 3 9
    1 5 4 // I NEVER show the number 4....
    2 0 0 5 6
    2 5 1 9 // here i found them...and now i have to look in the file 1 5 and 9 5 (but 1 5 are before this..so i can never found them)
    4 6 1 5
    4 9 1 8
    9 1 4 8
    9 5 0 // here i found 9 5
    Correct OutTxt: 1 9 4 0
    My OutTxt: 1 9 0...Never show the number 4, because i dont know how to start again...
    thank u
    Edited by: Ing_Balderas on Dec 11, 2009 2:25 PM

  • Need help with simple file sharing application

    I have an assignment to build a Java File Sharing application. Since I'm relatively new to programming, this is not gonna be an easy task for me.
    Therefore I was wondering if there are people willing to help me in the next few days. I will ask questions in this thread, there will be loads of them.
    I already have something done but I'm not nearly halfway finished.
    Is there a code example of a simple file sharing application somewhere? I didn't manage to find it.
    More-less, this is what it needs to contain:
    -client/server communication (almost over)
    -file sending (upload, download)
    -file search function (almost over)
    -GUI of an application.
    GUI is something I will do at the end, hopefully.
    I hope someone will help me. Cheers
    One more thing, I'm not asking for anyone to do my homework. I will only be needing some help in the various steps of building an application.
    As I said code examples are most welcome.
    This is what I have done so far
    Server:
    package ToJeTo;
    import java.io.*;
    import java.net.*;
    public class MultiServer {
        public static ServerSocket serverskiSoket;
        public static int PORT = 1233;
        public static void main(String[] args) throws IOException {
            try {
                serverskiSoket = new ServerSocket(PORT);
            }catch (IOException e) {
                System.out.println("Connection impossible");
                System.exit(1);
            do {
                Socket client = serverskiSoket.accept();
                System.out.println("accepted");
                ClientHandler handler = new ClientHandler(client);
                handler.start();
            } while(true);
    }Client:
    package ToJeTo;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.*;
    import java.util.Scanner;
    public class MultiClient {
        public static InetAddress host;
        public static int PORT = 1233;
        public static void main(String[] args) {
            try {
                host = InetAddress.getLocalHost();
            }catch (UnknownHostException uhe) {
                System.out.println("Error!");
                System.exit(1);
            sendMessages();
        private static void sendMessages() {
            Socket soket = null;
            try {
                soket = new Socket(host, PORT);
                Scanner networkInput = new Scanner(soket.getInputStream());
                PrintWriter networkOutput = new PrintWriter(soket.getOutputStream(), true);
                Scanner unos = new Scanner(System.in);
                String message, response;
                do {
                    System.out.println("Enter message");
                    message = unos.nextLine();
                    networkOutput.println(message);
                    response = networkInput.nextLine();
                    System.out.println("Server: " + response);
                }while (!message.equals("QUIT"));
            } catch (IOException e) {
                e.printStackTrace();
            finally {
                try{
                    System.out.println("Closing..");
                    soket.close();
                } catch (IOException e) {
                    System.out.println("Impossible to disconnect!");
                    System.exit(1);
    }ClientHandler:
    package ToJeTo;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class ClientHandler extends Thread {
        private Socket client;
        private Scanner input;
        private PrintWriter output;
        public ClientHandler(Socket serverskiSoket) {
            client = serverskiSoket;
            try {
            input = new Scanner(client.getInputStream());
            output = new PrintWriter(client.getOutputStream(), true);
            } catch (IOException e) {
                e.printStackTrace();
            public void run() {
                String received;
                do {
                received = input.nextLine();
                output.println("Reply: " + received);
                } while (!received.equals("QUIT"));
                try {
                    if (client != null)
                        System.out.println("Closing the connection...");
                        client.close();
                }catch (IOException e) {
                    System.out.println("Error!");
    }Those three classes are simple client server multi-threaded connection.

    Now the other part that contains the search function looks like this:
    package ToJeTo;
    import java.io.*;
    import java.util.*;
    public class User {
        String nickname;
        String ipAddress;
        static ArrayList<String> listOfFiles = new ArrayList<String>();
        File sharedFolder;
        String fileLocation;
        public User(String nickname, String ipAddress, String fileLocation) {
            this.nickname = nickname.toLowerCase();
            this.ipAddress = ipAddress;
            sharedFolder = new File(fileLocation);
            File[] files = sharedFolder.listFiles();
            for (int i = 0; i < files.length; i++) {
                listOfFiles.add(i, files.toString().substring(fileLocation.length()+1));
    public static void showTheList() {
    for (int i = 0; i < listOfFiles.size(); i++) {
    System.out.println(listOfFiles.get(i).toString());
    @Override
    public String toString() {
    return nickname + " " + ipAddress;
    User Manager:
    package ToJeTo;
    import java.io.*;
    import java.util.*;
    class UserManager {
        static ArrayList<User> allTheUsers = new ArrayList<User>();;
        public static void addUser(User newUser) {
            allTheUsers.add(newUser);
        public static void showAndStoreTheListOfUsers() throws FileNotFoundException, IOException {
            BufferedWriter out = new BufferedWriter(new FileWriter("List Of Users.txt"));
            for (int i = 0; i < allTheUsers.size(); i++) {
                    System.out.println(allTheUsers.get(i));
                    out.write(allTheUsers.get(i).toString());
                    out.newLine();
            out.close();
    }Request For File
    package ToJeTo;
    import java.util.*;
    public class RequestForFile {
        static ArrayList<String> listOfUsersWithFile = new ArrayList<String>();
        Scanner input;
        String fileName;
        public RequestForFile() {
            System.out.println("Type the wanted filename here: ");
            input = new Scanner(System.in);
            fileName = input.nextLine();
            for (User u : UserManager.allTheUsers) {
                for (String str : User.listOfFiles) {
                    if (str.equalsIgnoreCase(fileName))
                        listOfUsersWithFile.add(u.nickname);
        public RequestForFile(String fileName) {
            for (User u : UserManager.allTheUsers) {
                for (String str : User.listOfFiles) {
                    if (str.equalsIgnoreCase(fileName))
                        listOfUsersWithFile.add(u.nickname);
        public static List<String> getAll() {
            for (int i = 0; i < listOfUsersWithFile.size(); i++) {
                //System.out.println("User that has the file: " + listOfUsersWithFile.get(i));
            return listOfUsersWithFile;
    }Now this is the general idea.
    The user logs in with his nickname and ip address. He defines his own shared folder and makes it available for other users that log on to server.
    Now each user has their own list of files from a shared folder. It's an ArrayList.
    User manager class is there to store another list, a list of users that are connected with server.
    When the user is searching for a particular file, he is searching through all the users and their respective files lists. Therefore for each loop inside a for each loop.
    Now the problem is how to connect all that with Client and Server class and put it into one piece.
    GUI should look somewhat like this:

  • Need help with Java applet, might need NetBeans URL

    I posted the below question. It was never answered, only I was told to post to the NetBeans help forum. Yet I don't see any such forum on this site. Can someone tell me where the NetBeans help forum is located (URL).
    Here is my original question:
    I have some Java source code from a book that I want to compile. The name of the file is HashTest.java. In order to compile and run this Java program I created a project in the NetBeans IDE named javaapplication16, and I created a class named HashTest. Once the project was created, I cut and pasted the below source code into my java file that was default created for HashTest.java.
    Now I can compile and build the project with no errors, but when I try and run it, I get a dialog box that says the following below (Ignore the [...])
    [..................Dialog Box......................................]
    Hash Test class wasn't found in JavaApplication16 project
    Select the main class:
    <No main classes found>
    [..................Dialog Box......................................]
    Does anyone know what the problem is here? Why won't the project run?
    // Here is the source code: *****************************************************************************************************
    import java.applet.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    import java.util.*;
    public class HashTest extends Applet implements ItemListener
    // public static void main(String[] args) {
    // Hashtable to add tile images
    private Hashtable imageTable;
    // a Choice of the various tile images
    private Choice selections;
    // assume tiles will have the same width and height; this represents
    // both a tile's width and height
    private int imageSize;
    // filename description of our images
    private final String[] filenames = { "cement.gif", "dirt.gif", "grass.gif",
    "pebbles.gif", "stone.gif", "water.gif" };
    // initializes the Applet
    public void init()
    int n = filenames.length;
    // create a new Hashtable with n members
    imageTable = new Hashtable(n);
    // create the Choice
    selections = new Choice();
    // create a Panel to add our choice at the bottom of the window
    Panel p = new Panel();
    p.add(selections, BorderLayout.SOUTH);
    p.setBackground(Color.RED);
    // add the Choice to the applet and register the ItemListener
    setLayout(new BorderLayout());
    add(p, BorderLayout.SOUTH);
    selections.addItemListener(this);
    // allocate memory for the images and load 'em in
    for(int i = 0; i < n; i++)
    Image img = getImage(getCodeBase(), filenames);
    while(img.getWidth(this) < 0);
    // add the image to the Hashtable and the Choice
    imageTable.put(filenames[i], img);
    selections.add(filenames[i]);
    // set the imageSize field
    if(i == 0)
    imageSize = img.getWidth(this);
    } // init
    // tiles the currently selected tile image within the Applet
    public void paint(Graphics g)
    // cast the sent Graphics context to get a usable Graphics2D object
    Graphics2D g2d = (Graphics2D)g;
    // save the Applet's width and height
    int width = getSize().width;
    int height = getSize().height;
    // create an AffineTransform to place tile images
    AffineTransform at = new AffineTransform();
    // get the currently selected tile image
    Image currImage = (Image)imageTable.get(selections.getSelectedItem());
    // tile the image throughout the Applet
    int y = 0;
    while(y < height)
    int x = 0;
    while(x < width)
    at.setToTranslation(x, y);
    // draw the image
    g2d.drawImage(currImage, at, this);
    x += imageSize;
    y += imageSize;
    } // paint
    // called when the tile image Choice is changed
    public void itemStateChanged(ItemEvent e)
    // our drop box has changed-- redraw the scene
    repaint();
    } // HashTest

    BigDaddyLoveHandles wrote:
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    That wasn't attention-grabbing enough apparantly. Let's try it again.
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}
    h1. {color:red}MULTIPOST: [http://forums.sun.com/thread.jspa?threadID=5358840&messageID=10564025]{color}

  • Need help with gallery showing .jpg AND .swf

    Hi all,
    I have an image gallery that loads images and swf-files from an XML-file. The .jpg's load and display just fine, but the .swf files won't show. The data is loaded though. Any help is greatly appreciated!
    Thanks so much in advance,
    Dirk
    My XML file looks like this:
    <?xml version="1.0" encoding="UTF-8" ?>
    - <slideshow>
    <image src="photo1.jpg" time="1" title="test" desc="test" artist="sabre" link="" target="_self" />
    <image src="photo2.jpg" time="3" title="test2" desc="test2desc" artist="sabre" link="" target="_self" />
    <image src="flash1.swf" time="2" title="test3" desc="test3desc" artist="sabre" link="" target="_self" />
    </slideshow>
    And the AS3:
    // import tweener
    import caurina.transitions.Tweener;
    // delay between slides
    const TIMER_DELAY:int = 5000;
    // fade time between slides
    const FADE_TIME:Number = 1;
    // flag for knowing if slideshow is playing
    var bolPlaying:Boolean = true;
    // reference to the current slider container
    var currentContainer:Sprite;
    // index of the current slide
    var intCurrentSlide:int = -1;
    // total slides
    var intSlideCount:int;
    // timer for switching slides
    var slideTimer:Timer;
    // slides holder
    var sprContainer1:Sprite;
    var sprContainer2:Sprite;
    // slides loader
    var slideLoader:Loader;
    // current slide link
    var strLink:String = "";
    // current slide link target
    var strTarget:String = "";
    // url to slideshow xml
    var strXMLPath:String = "xml.xml";
    // slideshow xml loader
    var xmlLoader:URLLoader;
    // slideshow xml
    var xmlSlideshow:XML;
    function initSlideshow():void {
    // hide buttons, labels and link
    mcInfo.visible = false;
    btnLink.visible = false;
    var request:URLRequest = new URLRequest (strXMLPath);
    request.method = URLRequestMethod.POST;
    var variables:URLVariables = new URLVariables();
    variables.memberID = root.loaderInfo.parameters.memberID;
    request.data = variables;
    var loader:URLLoader = new URLLoader (request);
    loader.addEventListener(Event.COMPLETE, onXMLLoadComplete);
    loader.dataFormat = URLLoaderDataFormat.VARIABLES;
    loader.load(request);
    // create new timer with delay from constant
    slideTimer = new Timer(TIMER_DELAY);
    // add event listener for timer event
    slideTimer.addEventListener(TimerEvent.TIMER, nextSlide);
    // create 2 container sprite which will hold the slides and
    // add them to the masked movieclip
    sprContainer1 = new Sprite();
    sprContainer2 = new Sprite();
    mcSlideHolder.addChild(sprContainer1);
    mcSlideHolder.addChild(sprContainer2);
    // keep a reference of the container which is currently
    // in the front
    currentContainer = sprContainer2;
    // add event listeners for buttons
    btnLink.addEventListener(MouseEvent.CLICK, goToWebsite);
    btnLink.addEventListener(MouseEvent.ROLL_OVER, showDescription);
    btnLink.addEventListener(MouseEvent.ROLL_OUT, hideDescription);
    mcInfo.btnPlay.addEventListener(MouseEvent.CLICK, togglePause);
    mcInfo.btnPause.addEventListener(MouseEvent.CLICK, togglePause);
    mcInfo.btnNext.addEventListener(MouseEvent.CLICK, nextSlide);
    mcInfo.btnPrevious.addEventListener(MouseEvent.CLICK, previousSlide);
    // hide play button
    mcInfo.btnPlay.visible = false;
    function onXMLLoadComplete(e:Event):void {
    // show buttons, labels and link
    mcInfo.visible = true;
    btnLink.visible = true;
    // create new xml with the received data
    xmlSlideshow = new XML(e.target.data);
    var  unesc_xmlSlideshow:XML = new XML(unescape(xmlSlideshow));
    // get total slide count
    intSlideCount = unesc_xmlSlideshow..image.length();
    // switch the first slide without a delay
    switchSlide(0);
    function fadeSlideIn(e:Event):void {
    var  unesc_xmlSlideshow:XML = new XML(unescape(xmlSlideshow));
    // add loaded slide from slide loader to the
    // current container
    addSlideContent();
    // clear preloader text
    mcInfo.lbl_loading.text = "";
    // check if the slideshow is currently playing
    // if so, show time to the next slide. If not, show
    // a status message
    if(bolPlaying) {
      mcInfo.lbl_loading.text = "Next slide in " + unesc_xmlSlideshow..image[intCurrentSlide].@time + " sec.";
    } else {
      mcInfo.lbl_loading.text = "Slideshow paused";
    // fade the current container in and start the slide timer
    // when the tween is finished
    Tweener.addTween(currentContainer, {alpha:1, time:FADE_TIME, onComplete:onSlideFadeIn});
    function onSlideFadeIn():void {
    // check, if the slideshow is currently playing
    // if so, start the timer again
    if(bolPlaying && !slideTimer.running)
      slideTimer.start();
    function togglePause(e:MouseEvent):void {
    var  unesc_xmlSlideshow:XML = new XML(unescape(xmlSlideshow));
    // check if the slideshow is currently playing
    if(bolPlaying) {
      // show play button
      mcInfo.btnPlay.visible = true;
      mcInfo.btnPause.visible = false;
      // set playing flag to false
      bolPlaying = false;
      // set status message
      mcInfo.lbl_loading.text = "Slideshow paused";
      // stop the timer
      slideTimer.stop();
    } else {
      // show pause button
      mcInfo.btnPlay.visible = false;
      mcInfo.btnPause.visible = true;
      // set playing flag to true
      bolPlaying = true;
      // show time to next slide
      mcInfo.lbl_loading.text = "Next slide in " + unesc_xmlSlideshow..image[intCurrentSlide].@time + " sec.";
      // reset and start timer
      slideTimer.reset();
      slideTimer.start();
    function switchSlide(intSlide:int):void {
    // check if the last slide is still fading in
    if(!Tweener.isTweening(currentContainer)) {
      // check, if the timer is running (needed for the
      // very first switch of the slide)
      if(slideTimer.running)
       slideTimer.stop();
      // change slide index
      intCurrentSlide = intSlide;
      // check which container is currently in the front and
      // assign currentContainer to the one that's in the back with
      // the old slide
      if(currentContainer == sprContainer2)
       currentContainer = sprContainer1;
      else
       currentContainer = sprContainer2;
      // hide the old slide
      currentContainer.alpha = 0;
      // bring the old slide to the front
      mcSlideHolder.swapChildren(sprContainer2, sprContainer1);
      // delete loaded content
      clearLoader();
      // create a new loader for the slide
      slideLoader = new Loader();
      // add event listener when slide is loaded
      slideLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, fadeSlideIn);
      // add event listener for the progress
      slideLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, showProgress);
      var  unesc_xmlSlideshow:XML = new XML(unescape(xmlSlideshow));
      // load the next slide, seems to f*ck up here...
      slideLoader.load(new URLRequest(unesc_xmlSlideshow..image[intCurrentSlide].@src));
      // show description of the next slide
      mcInfo.lbl_description.text = unesc_xmlSlideshow..image[intCurrentSlide].@title;
      // show artist's name of the next slide
      mcInfo.lbl_artist.text = unesc_xmlSlideshow..image[intCurrentSlide].@artist;
      // set link and link target variable of the slide
      strLink           = unesc_xmlSlideshow..image[intCurrentSlide].@link;
      strTarget          = unesc_xmlSlideshow..image[intCurrentSlide].@target;
      mcInfo.mcDescription.lbl_description.htmlText = unesc_xmlSlideshow..image[intCurrentSlide].@desc;
      // show current slide and total slides
      //mcInfo.lbl_count.text = (intCurrentSlide + 1) + " / " + intSlideCount + " Slides";
      mcInfo.lbl_count.text = " Slide " + (intCurrentSlide + 1) + " / " + intSlideCount;
    function showProgress(e:ProgressEvent):void {
    // show percentage of the bytes loaded from the current slide
    mcInfo.lbl_loading.text = "Loading..." + Math.ceil(e.bytesLoaded * 100 / e.bytesTotal) + "%";
    function goToWebsite(e:MouseEvent):void {
    // check if the strLink is not empty and open the link in the
    // defined target window
    if(strLink != "" && strLink != null) {
      navigateToURL(new URLRequest(strLink), strTarget);
    function nextSlide(e:Event = null):void {
    // check, if there are any slides left, if so, increment slide
    // index
    if(intCurrentSlide + 1 < intSlideCount)
      switchSlide(intCurrentSlide + 1);
    // if not, start slideshow from beginning
    else
      switchSlide(0);
    function previousSlide(e:Event = null):void {
    // check, if there are any slides left, if so, decrement slide
    // index
    if(intCurrentSlide - 1 >= 0)
      switchSlide(intCurrentSlide - 1);
    // if not, start slideshow from the last slide
    else
      switchSlide(intSlideCount - 1);
    function showDescription(e:MouseEvent):void {
    // remove tweens
    Tweener.removeTweens(mcInfo.mcDescription);
    // fade in the description
    Tweener.addTween(mcInfo.mcDescription, {alpha:1, time:0.5, y: -1});
    function hideDescription(e:MouseEvent):void {
    // remove tweens
    Tweener.removeTweens(mcInfo.mcDescription);
    // fade out the description
    Tweener.addTween(mcInfo.mcDescription, {alpha:0, alpha:1, time:0.5, y: 30});
    function clearLoader():void {
    try {
      // get loader info object
      var li:LoaderInfo = slideLoader.contentLoaderInfo;
      // check if content is bitmap and delete it
      if(li.childAllowsParent && li.content is Bitmap){
       (li.content as Bitmap).bitmapData.dispose();
    } catch(e:*) {}
    function addSlideContent():void {
    // empty current slide and delete previous bitmap
    while(currentContainer.numChildren){Bitmap(currentContainer.getChildAt(0)).bitmapData.disp ose(); currentContainer.removeChildAt(0);}
    // create a new bitmap with the slider content, clone it and add it to the slider container
    var bitMp:Bitmap =  new Bitmap(Bitmap(slideLoader.contentLoaderInfo.content).bitmapData.clone());
    currentContainer.addChild(bitMp);
    // init slideshow
    initSlideshow();

    I'm sorry, you're right! Didn't intend to be lazy...
    This line loads the image in the loader 'slideLoader'. This seems to work fine with image files (.jpg), but .swf files are ignored. Is it possible to load both .jpg AND .swf files in a loader, or do I have to use some other method for this?
    slideLoader.load(new URLRequest(unesc_xmlSlideshow..image[intCurrentSlide].@src));
    Thanks again,
    Dirk

  • Need help with Java app for user input 5 numbers, remove dups, etc.

    I'm new to Java (only a few weeks under my belt) and struggling with an application. The project is to write an app that inputs 5 numbers between 10 and 100, not allowing duplicates, and displaying each correct number entered, using the smallest possible array to solve the problem. Output example:
    Please enter a number: 45
    Number stored.
    45
    Please enter a number: 54
    Number stored.
    45 54
    Please enter a number: 33
    Number stored.
    45 54 33
    etc.
    I've been working on this project for days, re-read the book chapter multiple times (unfortunately, the book doesn't have this type of problem as an example to steer you in the relatively general direction) and am proud that I've gotten this far. My problems are 1) I can only get one item number to input rather than a running list of the 5 values, 2) I can't figure out how to check for duplicate numbers. Any help is appreciated.
    My code is as follows:
    import java.util.Scanner; // program uses class Scanner
    public class Array
         public static void main( String args[] )
          // create Scanner to obtain input from command window
              Scanner input = new Scanner( System.in);
          // declare variables
             int array[] = new int[ 5 ]; // declare array named array
             int inputNumbers = 0; // numbers entered
          while( inputNumbers < array.length )
              // prompt for user to input a number
                System.out.print( "Please enter a number: " );
                      int numberInput = input.nextInt();
              // validate the input
                 if (numberInput >=10 && numberInput <=100)
                       System.out.println("Number stored.");
                     else
                       System.out.println("Invalid number.  Please enter a number within range.");
              // checks to see if this number already exists
                    boolean number = false;
              // display array values
              for ( int counter = 0; counter < array.length; counter++ )
                 array[ counter ] = numberInput;
              // display array values
                 System.out.printf( "%d\n", array[ inputNumbers ] );
                   // increment number of entered numbers
                inputNumbers++;
    } // end close Array

    Yikes, there is a much better way to go about this that is probably within what you have already learned, but since you are a student and this is how you started, let's just concentrate on fixing what you got.
    First, as already noted by another poster, your formatting is really bad. Formatting is really important because it makes the code much more readable for you and anyone who comes along to help you or use your code. And I second that posters comment that brackets should always be used, especially for beginner programmers. Unfortunately beginner programmers often get stuck thinking that less lines of code equals better program, this is not true; even though better programmers often use far less lines of code.
                             // validate the input
       if (numberInput >=10 && numberInput <=100)
              System.out.println("Number stored.");
      else
                   System.out.println("Invalid number.  Please enter a number within range."); Note the above as you have it.
                         // validate the input
                         if (numberInput >=10 && numberInput <=100)
                              System.out.println("Number stored.");
                         else
                              System.out.println("Invalid number.  Please enter a number within range."); Note how much more readable just correct indentation makes.
                         // validate the input
                         if (numberInput >=10 && numberInput <=100) {
                              System.out.println("Number stored.");
                         else {
                              System.out.println("Invalid number.  Please enter a number within range.");
                         } Note how it should be coded for a beginner coder.
    Now that it is readable, exam your code and think about what you are doing here. Do you really want to print "Number Stored" before you checked to ensure it is not a dupe? That could lead to some really confused and frustrated users, and since the main user of your program will be your teacher, that could be unhealthy for your GPA.
    Since I am not here to do your homework for you, I will just give you some advice, you only need one if statement to do this correctly, you must drop the else and fix the if. I tell you this, because as a former educator i know the first thing running through beginners minds in this situation is to just make the if statement empty, but this is a big no no and even if you do trick it into working your teacher will not be fooled nor impressed and again your GPA will suffer.
    As for the rest, you do need a for loop inside your while loop, but not where or how you have it. Inside the while loop the for loop should be used for checking for dupes, not for overwriting every entry in the array as you currently have it set up to do. And certainly not for printing every element of the array each time a new element is added as your comments lead me to suspect you were trying to do, that would get real annoying really fast again resulting in abuse of your GPA. Printing the array should be in its own for loop after the while loop, or even better in its own method.
    As for how to check for dupes, well, you obviously at least somewhat understand loops and if statements, thus you have all the tools needed, so where is the problem?
    JSG

Maybe you are looking for

  • Installation error ABAP + JAVA Stack

    Hi all, I am trying to install ABAP+Java server and i am facing the below issue.Can you please help me in resolving this. Hard Disk:-200 GB RAM:-2GB Log file 1:- ERROR      2010-01-28 17:32:12 CJSlibModule::writeError_impl() CJS-30023  Process call '

  • Set deletion indicator in purchase requisition account assignment

    Hi Guys, Can you please help we with the solution to set deletion indicator in purchase requisition account assignment or close purchase requisition. A purchase requisition of $3.600.000,00 was created through Project system Network-External Processi

  • FTP_COMMAND in order to get files list at FTP address

    Hi all. I want to get a list of files exist at a specific FTP address. For that I'm using FTP_CONNECT (OK) and after I want to execute FTP_COMMAND with parameter command = 'ls' in order to recievce the files list in output table data[]. I keep on get

  • Search does not work in Mail

    After upgrading from Mountain Lion to Mavericks and reindexing my mails, "Mail" does not find anything when using the built-in search feature (neither does Spotlight). I tried removing the envelop files in the Library folder (- reindexing), deleting

  • Installing Updates and Blackout

    I was restarting my laptop and then there was a pop up asking if I wanted to Install and Restart. I clicked install and restart. It was downloading then everything went black and never turned on again. Please, what can I do? I plugged in the charger