Okay, I need help with the snake tail, following it with arrays.

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class snake1
     public static void main(String args[])
          String name1= JOptionPane.showInputDialog("Enter Player one's name");
          Windows myW=new Windows(name1);
          myW.setSize(800,600);
          myW.addWindowListener(new WindowAdapter()
               public void windowClosing(WindowEvent event)
                    System.exit(0);
          myW.show();
          while(true)
               myW.repaint();
               try{Thread.sleep(60/myW.getLevel());}catch(Exception e){}
class Windows extends Frame implements KeyListener
     int appleSize = 10;
     int snakeSize = 10;
     private int x,y,xold,yold;
     private boolean go,move,firsttime,win,tie,goTitle,play,selectLevel;
     private int size,growth;
     private int level = 0;
     private int AppleX, AppleY, SnakeX, SnakeY;
     private boolean left,right,up,down;
     private boolean hitWall,start;
     private String nam1;
     private int snakeBody[][];
     private int currentLength,snakeLength;
     public Windows(String n1)
          nam1=n1;
          play=false;
          win = false;
          x=265;
          y=265;
          AppleX=x;
          AppleY=y;
          xold=x;
          yold=y;
          firsttime =true;
          go =false;
          move =false;
          goTitle=true;
          go=false;
          addKeyListener(this);
          selectLevel=false;
          level=0;
          SnakeX=265;
          SnakeY=265;
          left=false;
          right=true;
          up=false;
          down=false;
          size=5;
          hitWall=false;
          start=false;
          growth = 1;
          snakeLength = 999;
          currentLength = 1;
          snakeBody = new int[snakeLength][2];
          snakeBody[0][0] = SnakeX;
          snakeBody[0][1] = SnakeY;
     public int getLevel()
          return level;
     public void update(Graphics g)
          paint(g);
     public void paint(Graphics g)
          if(goTitle)
               title(g);
          if(firsttime){
               selectLevel=true;
               startgame(g);
               movebox(g);
               firsttime=false;
          if(go){
               selectLevel=true;
               snakeGame(g);
          if(play)
               snakeGame(g);
               selectLevel=false;
          g.setFont(new Font("Courier",Font.BOLD,30));
          g.setColor(Color.yellow);
          g.drawString("X = ",490,100); // display x,y on screen
          String xnum=Integer.toString(x);
          g.drawString(xnum,550,100);
          g.drawString("Y = ",640,100);
          String ynum=Integer.toString(y);
          g.drawString(ynum,700,100);
          if(move)
               movebox(g);
          //repaint();
public void title(Graphics g)
          g.setColor(Color.red);
          g.fillOval(100,100,600,450);
          g.fillRect(390,30,20,80);
          //g.setColor(Color.black);
          //g.drawRoundRect(100,150,20,10,20,20);
          g.setColor(Color.black);
          g.fillRect(0,0,800,600);
          //g.setColor(Color.black);
          //g.fillRect(100,100,600,400);
          g.setColor(Color.red);
          g.setFont(new Font("Courier",Font.ITALIC,36));
          g.drawString("Snake Game", 300,200);
          g.setColor(Color.white);
          try{Thread.sleep(75);}catch(Exception e){}
          g.drawOval(410,250,6,6);
          try{Thread.sleep(75);}catch(Exception e){}
          g.drawOval(404,250,6,6);
          try{Thread.sleep(75);}catch(Exception e){}
          try{Thread.sleep(75);}catch(Exception e){}
          g.drawOval(400,240,20,20);
          try{Thread.sleep(75);}catch(Exception e){}
          g.drawOval(400,220,20,20);
          try{Thread.sleep(75);}catch(Exception e){}
          g.drawOval(320,200,20,20);
          try{Thread.sleep(75);}catch(Exception e){}
          g.drawOval(340,200,20,20);
          try{Thread.sleep(75);}catch(Exception e){}
          g.drawOval(360,200,20,20);
          try{Thread.sleep(75);}catch(Exception e){}
          g.drawOval(380,200,20,20);
          try{Thread.sleep(75);}catch(Exception e){}
          g.drawOval(400,200,20,20);
          try{Thread.sleep(400);}catch(Exception e){}
          for(int k=0; k<4; k++)
          g.setColor(Color.green);
          g.setFont(new Font("Courier",Font.ITALIC,36));
          g.drawString("How you like them APPLES!", 140,400);
          try{Thread.sleep(400);}catch(Exception e){}
          g.setColor(Color.red);
          g.setFont(new Font("Courier",Font.ITALIC,36));
          g.drawString("How you like them APPLES!", 140,400);
          try{Thread.sleep(400);}catch(Exception e){}
          goTitle=false;
          firsttime=true;
     public void startgame(Graphics g)
          g.setColor(Color.black);
          g.fillRect(0,0,800,600);
          g.setColor(Color.white);
          g.setFont(new Font("Courier",Font.ITALIC,30));
          g.drawString("Snake Game", 300,75);
          firsttime=false;
          g.setColor(Color.yellow);
          g.drawString("Easy",250,265);
          g.setColor(Color.yellow);
          g.drawString("Normal",250,365);
          g.setColor(Color.yellow);
          g.drawString("Hard",250,465);
     public void keyPressed(KeyEvent event)
          if(selectLevel)
               xold=x;
               yold=y;
               switch (event.getKeyCode())
                    case KeyEvent.VK_UP:
                         if(y<=265)
                              y=265;
                         else
                              y-=100;
                         move=true;
                    break;
                    case KeyEvent.VK_DOWN:
                         if(y>=465)
                              y=465;
                         else
                              y+=100;
                         move=true;
                    break;
                    case KeyEvent.VK_ENTER:
                         if(y==465) //HARD
                              level=3;
                         else if (y == 365) //MEDIUM
                              level=2;
                         else // EASY
                              level=1;
                         if(x==xold && y==yold)
                              play=true;
                         break;
          else
               if (event.getKeyCode() == KeyEvent.VK_UP)
                         if(!down)
                         down=false;
                         up=true;
               left=false;
               right=false;
               move=false;
               selectLevel=false;
               if (event.getKeyCode() == KeyEvent.VK_DOWN)
                    if(!up)
                         up=false;
                         down=true;
                    left=false;
                    right=false;
                    move=false;
                    selectLevel=false;
               if (event.getKeyCode() == KeyEvent.VK_LEFT)
                    if(!right)
                         right=false;
                         left=true;
               up=false;
               down=false;
               move=false;
               selectLevel=false;
               if (event.getKeyCode() == KeyEvent.VK_RIGHT)
                         if(!left)
                         left=false;
                         right=true;
                    up=false;
                    down=false;
                    move=false;
                    selectLevel=false;
               if (event.getKeyCode() == KeyEvent.VK_ENTER)
                    play=true;
     public void keyReleased(KeyEvent event)
     public void keyTyped(KeyEvent event)
     public void movebox(Graphics screen)
          screen.setColor(Color.black); //blue rectangle to clear
          screen.fillRect(490,80,260,30);
          screen.setFont(new Font("Courier",Font.BOLD,30));
          screen.setColor(Color.yellow);
          screen.drawString("X = ",490,100); // display x,y on screen
          String xnum=Integer.toString(x);
          screen.drawString(xnum,550,100);
          screen.drawString("Y = ",640,100);
          String ynum=Integer.toString(y);
          screen.drawString(ynum,700,100);
               if(x!=xold || y!=yold)
               screen.setColor(Color.black);
               screen.fillRect(xold-10,yold,xold+110,yold);
          screen.setFont(new Font("Courier",Font.ITALIC,30));     
          screen.setColor(Color.yellow);
          screen.drawString("Easy",250,265);
          screen.setColor(Color.yellow);
          screen.drawString("Normal",250,365);
          screen.setColor(Color.yellow);
          screen.drawString("Hard",250,465);
          screen.setColor(Color.red);
          screen.drawLine(x-10,y,x+110,y);
          xold=x;
          yold=y;
          move=false;
          selectLevel=true;
     public void snakeGame(Graphics g)
          Random rnum=new Random();     
          g.setColor(Color.gray);
          g.fillRect(0,0,800,600);
          DrawApple(g, AppleX, AppleY);
          g.setColor(Color.white);
          g.setFont(new Font("Courier",Font.ITALIC,30));     
          if(left)
               SnakeX-=size;
          if(right)
               SnakeX+=size;
          if (up)
               SnakeY-=size;
          if(down)
               SnakeY+=size;
          drawSnake(g);
          if (SnakeX<5)
               hitWall=true;
               SnakeX=785;
          if(SnakeX>785)
               hitWall=true;
               SnakeX=5;
          if(SnakeY<30)
               hitWall=true;
               SnakeY=585;
          if(SnakeY>585)
               hitWall=true;
               SnakeY=30;
          selectLevel=false;
          boolean touchSnakeX = (AppleX >= SnakeX) && (AppleX <= SnakeX + snakeSize);
          boolean touchSnakeY = (AppleY >= SnakeY) && (AppleY <= SnakeY + snakeSize);
          boolean touchAppleX = (AppleX <= SnakeX) && (AppleX + appleSize >= SnakeX);
          boolean touchAppleY = (AppleY <= SnakeY) && (AppleY + appleSize >= SnakeY);
          //if(SnakeX==AppleX && SnakeY==AppleY)
          if((touchSnakeX && touchSnakeY) || (touchAppleX && touchAppleY))
               AppleX = rnum.nextInt(785/size)*size+size;
               AppleY = rnum.nextInt(585/size)*size+size;
               if(AppleX<30)
                    AppleX=30;
               if(AppleX>785)
                    AppleX=785;
               if(AppleY<5)
                    AppleY=5;
               if(AppleY>785)
                    AppleY=785;
     public void DrawApple(Graphics g, int x, int y)     
          g.setColor(Color.green);
          g.fillRect(x,y,appleSize,appleSize);          
     public void drawSnake(Graphics g)
          g.fillRect(SnakeX,SnakeY, snakeSize, snakeSize);
}Okay I know you need arrays, that following it, and i set it up with the names that we should use.
int snakeBody[][];
nt currentLength,snakeLength;
Thank you, for your help, and if you got it you can explain lil thanks!

hiwa wrote:
What on earth is your problem?What, you're not doing the assignment? Dude! Think of the marks you'll miss!

Similar Messages

  • Need Help with Array.sort and compare

    Hi
    I have a big problem, i try to make a java class, where i can open a file and add new words, and to sort them in a right order
    Ok everthing works fine, but i get a problem with lower and upper cases.
    So i need a comparator, i tried everything but i just dont understand it.
    How do i use this with Array.sort??
    I hope someone can help me

    Okay, you want to ignore case when sorting.
    There are two possibilities: Truly ignore case, so that any of the following are possible, and which one you'll actually get is undefined, and may vary depending on, say, which order the words are entered in the first place:
    English english German german
    english English german German
    English english german German
    english English German german
    The second possibility is that you do consider case, but it's of lower priority--it's only considered if the letters are the same. This allows only the first two orderings above.
    Either way, you need to write a comparator, and call an Arrays.sort method that takes both array and Comparator.
    The first situation is simpler. Just get an all upper or lower case copy of the strings, and then compare thosepublic int compare(Object o1, Object o2) {
        String s1 = ((String)o1).toUpper();
        String s2 = ((String)o1).toUpper();
        return s1.compareTo(s2);
    } You'll need to add your own null check if you need one.
    For the second way, your comparator will need to iterate over each pair of characters. If the characters are equal, ignoring case, then you compare them based on case. You pick whether upper is greater or less than lower.
    Of course, the need to do this assumes that such a method doesn't alrady exist. I don't know of one, but I haven't looked.

  • Exchange was deployed without a CASArray, need help with array settings and PRF to fix.

    I'm standing up a new Exchange 2010 server to replace old hardware (not going 2013 at this time) and found out the hard way that the person who built the old 2010 box never created a CASArray.  I've created one and applied it to the mailbox DB on the
    new server with set-rpcclientaccess and it works fine - I move my own mailbox to the new DB and do a "Repair" to the Outlook profile and then it shows the address for the CAS Arrary within Outlook.
    I set up a hardware load balancer for the CAS Array IP address and it shows good connection from both CAS servers, Outlook is connecting through that just fine.
    Users are on Outlook 2007 and 2010, almost all 64-bit versions.
    Reconfiguring everybody's outlook isn't going to be a practical solution for me - I support a couple hundred geographically-dispersed users most of whom aren't keen to muck about in their Outlook settings.  So here are my questions:
    Should I add the mailbox DB on the old CAS server to the array using set-rpcclientaccess or will this disrupt connectivity for all users?
    Assuming I need to use a PRF to update client computers, have read several pages on how to create the PRF, but even launching outlook.exe /importprf doesn't fix the value - and /promptimportprf doesn't prompt (I see a brief flash of what is probably the
    prompt window but it disappears immediately).  I'm going to paste in the PRF in use exempting sections 5, 6 and 7 which are unchanged.  Where do I correctly need to enter the CAS array value?
    [General]
    Custom=1
    DefaultProfile=Yes
    OverwriteProfile=Append
    ModifyDefaultProfileIfPresent=true
    ; Section 2 - Services in Profile
    [Service List]
    ;ServiceX=Microsoft Outlook Client
    ; Section 3 - List of internet accounts
    [Internet Account List]
    ; Section 4 - Default values for each service.
    ;[ServiceX]
    ;FormDirectoryPage=
    ;-- The URL of Exchange Web Services Form Directory page used to create Web forms.
    ;WebServicesLocation=
    ;-- The URL of Exchange Web Services page used to display unknown forms.
    ;ComposeWithWebServices=
    ;-- Set to true to use Exchange Web Services to compose forms.
    ;PromptWhenUsingWebServices=
    ;-- Set to true to use Exchange Web Services to display unknown forms.
    ;OpenWithWebServices=
    ;-- Set to true to prompt user before opening unknown forms when using Exchange Web Services.
    [Service1]
    HomeServer=cas.corp.mydomain
    DefaultProfile=Yes
    OverwriteProfile=Append
    ModifyDefaultProfileIfPresent=true

    If you move a mailbox from one server to another, Outlook will automatically repair the Outlook profile.  Have you tried this, instead of trying to force a profile update using a PRF?

  • Need help with Arrays

    Hey guys, I'm a beginner programmer and I'm having a bit of a tough time with arrays. I could really use some help!
    What I'm trying to do is roll one die and then record the rolls.
    Here is my sample I/O:
    How many times should I roll a die?
    -> 8
    rolling 8 times
    2, 1, 5, 6, 2, 3, 6, 5
    number of 1's: 1
    number of 2's: 2
    and so on....
    Here is my incomplete code at this moment:
    //CountDieFaces.java
    import java.util.Scanner;
    import java.io.*;
    import library.Gamble;
    public class CountDieFaces
        //prompt for and read in: number of times user wants to roll one die
        //simulate rolling a die that many times, counting how many times each face 1 thru 6 comes up
        //print out: each roll
        //AND the total number of times each face occured and the percentage of the time each face occured.
        Scanner scan = new Scanner(System.in);
        int[] faceCount= {0,0,0,0,0,0,0};
        int dice;
        System.out.println("How many times would you like to roll the die?");
        int dieCount = scan.nextInt();
        int dieRoll = Gamble.rollDie(); // Main calling class method
        int count = 1;
        while(count < dieCount)
            System.out.println(faceCount[count]);
            count++;
    }Here is the gamble library:
    //Gamble.java
    package library;
    public class Gamble
         // returns 1, 2, 3, 4, 5, or 6
         public static int rollDie()
              int dieRoll = (int)(Math.random()*6)+1;
              return dieRoll;
    }and here are the errors I have so far:
    ----jGRASP exec: javac -g CountDieFaces.java
    CountDieFaces.java:19: <identifier> expected
         System.out.println("How many times would you like to roll the die?");
         ^
    CountDieFaces.java:19: illegal start of type
         System.out.println("How many times would you like to roll the die?");
         ^
    CountDieFaces.java:25: illegal start of type
         while(count < dieCount)
         ^
    CountDieFaces.java:25: > expected
         while(count < dieCount)
         ^
    CountDieFaces.java:25: ')' expected
         while(count < dieCount)
         ^
    CountDieFaces.java:26: ';' expected
         ^
    CountDieFaces.java:27: illegal start of type
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ';' expected
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: invalid method declaration; return type required
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ']' expected
              System.out.println(faceCount[count]);
              ^
    CountDieFaces.java:27: ')' expected
              System.out.println(faceCount[count]);
    I'm really confused with how a the gamble library gets put into the array, so any help is appreciated! Also if anyone could explain the errors to me, I would really appreciate it.
    thanks in advance,
    wootens
    Edited by: Wootens on Oct 18, 2010 8:55 PM

    D'oh!
    Thanks you guys, fixed that. Although I'm having trouble with storing the die roll in the array. Any suggestions?
    java.io.*;
    public class CountDieFaces
        //prompt for and read in: number of times user wants to roll one die
        //simulate rolling a die that many times, counting how many times each face 1 thru 6 comes up
        //print out: each roll
        //AND the total number of times each face occured and the percentage of the time each face occured.
        public static void main(String[] args)
            Scanner scan = new Scanner(System.in);
            int[] faceCount= {0,0,0,0,0,0};
            int dice;
            System.out.println("How many times would you like to roll the die?");
            int dieCount = scan.nextInt();
            int dieRoll = rollDie(); // Main calling class method
            int count = 0;
            while(count < dieCount)
                System.out.println(faceCount[dieRoll]);
                count++;
        public static int rollDie()
            int dieRoll = (int)(Math.random()*6)+1;
            return dieRoll;
    }Wootens

  • Need Help with Arrays/Text

    I'm trying to create a flash program that uses it's own code to send and create images. Each square has a colour and that colour gets added into the array. A black, then grey, then white is:
    filecode = ["Bl", "Gr", "Wh"];
    That works fine, but when I try to paste it into an Input text box it will only fill in the first part of the array.
    filecode = ["Bl,Gr,Wh"];
    So the program has NO idea what I want.
    The only ways I can think of fixing this is by putting in 402 text boxes to suit every box...But every one of them needs a Variable Name.
    Or by sending the information straight into the array. But this way you are just looking at what you just drew, and that is not at ALL practical.
    Helping me with this headache will be greatly apprectiated.
    FlashDrive100.

    If you can explain the first part of your posting it might become a little clearer what you are trying to do and what isn't working... particularly this...
    " when I try to paste it into an Input text box it will only fill in the first part of the array."
    I can't speak for anyone else, but at this point, I share your file's problem... not knowing what you want.

  • Noob needs help with array manipulation

    First off, I'd like to say hello to eveybody!
    I'm trying to figure out how to search for a value in an array, delete the first occurence of it, and shift the rest of the array down one. Can anyone point me in the right direction of an algorithm, mabey?
    Any help is most appreciated!

    first of all, let me comment that for this purpouse, you're better using the ArrayList class.
    anyway, you would need to make a temporary array inside a method, and traverse the array in question using a loop. most people use a for loop.
    Then, put all the values of the old array into the temporary one, except for the one you dont want.
    after the loop, set the old array to equal the temporary array.

  • Need help optimizing the writing of a very large array and streaming it a file

    Hi,
    I have a very large array that I need to create and later write to a TDMS file. The array has 45 million entries, or 4.5x10^7 data points. These data points are of double format. The array is created by using a square pulse waveform generator and user-defined specifications of the delay, wait time, voltages, etc. 
    I'm not sure how to optimize the code so it doesn't take forever. It currently takes at least 40 minutes, and I'm still running it, to create and write this array. I know there needs to be a better way, as the array is large and consumes a lot of memory but it's not absurdly large. The computer I'm running this on is running Windows Vista 32-bit, and has 4GB RAM and an Intel Core 2 CPU @ 1.8Mhz. 
    I've read the "Managing Large Data Sets in LabVIEW" article (http://zone.ni.com/devzone/cda/tut/p/id/3625), but I'm unsure how to apply the principles here.  I believe the problem lies in making too many copies of the array, as creating and writing 1x10^6 values takes < 10 seconds, but writing 4x10^6 values, which should theoretically take < 40 seconds, takes minutes. 
    Is there a way to work with a reference of an array instead of a copy of an array?
    Attached is my current VI, Generate_Square_Pulse_With_TDMS_Stream.VI and it's two dependencies, although I doubt they are bottlenecking the program. 
    Any advice will be very much appreciated. 
    Thanks
    Attachments:
    Generate_Square_Pulse_With_TDMS_Stream.vi ‏13 KB
    Square_Pulse.vi ‏13 KB
    Write_TDMS_File.vi ‏27 KB

    Thanks Ravens Fan, using replace array subset and initializing the array beforehand sped up the process immensely. I can now generate an array of 45,000,000 doubles in about one second.
    However, when I try to write all of that out to TDMS at the end LV runs out of memory and crashes. Is it possible to write out the data in blocks and make sure memory is freed up before writing out the next block? I can use a simple loop to write out the blocks, but I'm unsure how to verify that memory has been cleared before proceeding.  Furthermore, is there a way to ensure that memory and all resources are freed up at the end of the waveform generation VI? 
    Attached is my new VI, and a refined TDMS write VI (I just disabled the file viewer at the end). Sorry that it's a tad bit messy at the moment, but most of that mess comes from doing some arithmetic to determine which indices to replace array subsets with. I currently have the TDMS write disabled.
    Just to clarify the above, I understand how to write out the data in blocks; my question is: how do I ensure that memory is freed up between subsequent writes, and how do I ensure that memory is freed up after execution of the VI?
    @Jeff: I'm generating the waveform here, not reading it. I guess I'm not generating a "waveform" but rather a set of doubles. However, converting that into an actual waveform can come later. 
    Thanks for the replies!
    Attachments:
    Generate_Square_Pulse_With_TDMS_Stream.vi ‏14 KB
    Write_TDMS_File.vi ‏27 KB

  • I am desperate (I need help with Arrays of parameters)

    Anyone please available to help

    I have tried it but it is still displaying.
    Here is the actual parameters sent from my form (copied from the location bar)
    organise_info.jsp?skills_sets44=skills_ptp&description44=+&description45=+&skills_sets46=skills_ptp&description46=+&description47=+&description48=+&description49=+&description50=+&description51=+&description52=+&description53=+&description54=+&description55=+&description56=+&description43=+&fname=Jonathan--24&lname=Wheelwright
    the description-nos is the one that I am having problems with because it is from a text input field.

  • Need help with Arrays please

    I keep getting nullPointerException in both the driver and the class for this program and I can't figure out what is causing it and the program won't run with it. We have not covered handling exceptions in class and are not to use anything that we haven't covered in class. Can someone look over this and tell me what is wrong? There are 3 sections of code - the Installations Class, the Mufflers Class and the InstallationsTest Class (driver). Thanks in advance for any help
    public class InstallationsTest
    public static void main (String [] args)
    Installations install=new Installations(5723, "Boswell's Muffler Shop");
    install.addMuffler("Jones", "A3");
    install.addMuffler("Carr", "A");
    install.addMuffler("Smith", "B3");
    install.updateMuffler("Smith", "BL");
    install.updateMuffler("Mason", "A3");
    System.out.println(install.getMuffler("Carr" + "\n"));
    System.out.println(install.getMuffler("Mason" + "\n"));
    System.out.println("The total sales are $" +install.getTotalSales());
    System.out.println(install.toString());
    ===================================================================================
    This class calculates the cost of a muffler
    based on model chosen and appropriate warranty.
    It then prints customer name, price code and
    cost of muffler.
    import java.text.NumberFormat;
    public class Muffler
    Constructs the elements of the muffler class
    @param custName - the customer's name
    @param pCode - comprises the 2 char code for the price
         public Muffler(String custName,String pCode)
                   customer = custName;
                   priceCode = pCode;
                   computeCost();
         Returns the name of the customer
         @return customer - the customers name     
         public String getCustomer()
                   return customer;
         Returns the price code
         @return priceCode - the price code     
         public String getPriceCode()
                   return priceCode;
         Returns the cost
         @return cost - the cost     
         public double getCost()
                   return cost;
              Computes cost of muffler
         private void computeCost()
                   double w=0;
                   double factor;
                   int num;
                   char msize=' ';
                   char war=' ';
                   if (priceCode.length()==1)
                   msize = Character.toUpperCase(priceCode.charAt(0));
                   w=0;
                   if (priceCode.length()==2)
                   war = priceCode.charAt(1);
                   msize = Character.toUpperCase(priceCode.charAt(0));
                   switch(msize)
                             case 'A' : factor = 1; num=1; break;
                             case 'B' : factor = 1.07; num=2; break;
                             case 'C' : factor = 1.15; num=3; break;
                             case 'D' : factor = 1.22; num=4; break;
                             case 'E' : factor = 1.38; num=5; break;
                             case 'F' : factor = 1.50; num=6;break;
                             default : factor = 0; num=7;
                   if (num<=6 && war=='3')
                        w=2;
                             cost = (39.95 + w) * factor;
                   if (num>1 && num<=6 && war=='L' || num>1 && num<=6 && war=='l' )
                             w=5;
                             cost = (39.95 + w) * factor;
                   if (num==1 && war=='L' || num==1 && war=='l')
                        cost=9999.99;
                   if (num==6 && war==' ')
                             cost=9999.99;
                   if (num<6 && war==' ')
                        w=0;
                        cost = (39.95 + w) * factor;
                   if (num<1 || num>6 )
                             cost=9999.99;
         Updates the price code
         @param updatePC - the new price code     
         public void updatePriceCode(String updatePC)
                   priceCode = updatePC;
                   computeCost();
         Returns the formatted muffler information
         @return toString information     
         public String toString()
              NumberFormat currencyFormater = NumberFormat.getCurrencyInstance();
                   if(cost==9999.99)
                        return(priceCode + " is an invalid price code\t" + cost);
                        else return(customer + "\t" + priceCode + "\t" + currencyFormater.format(cost));
              private String customer;
              private String priceCode;
              private double cost;
    ===================================================================================
    *Stores information about the mufflers sold by a specific franchise location
    public class Installations
    /** Creates a new instance of Installations */
    public Installations(int franchID, String franchName)
    franchiseID = franchID;
    franchiseName = franchName;
    *Adds a new muffler installation for the franchise
    *@param name the customer name
    *@param code the service code
    public void addMuffler(String name, String code)
    mufflers[count]=new Muffler(name, code);
    count++;
    *updates a muffler installation for the franchise
    *@param name the customer name
    *@param code the service code
    public void updateMuffler(String name, String code)
    for(int i=0; i<=count; i++)
    if (mufflers.getCustomer().equalsIgnoreCase(name))
    mufflers[i].updatePriceCode(code);
    private double calculateTotalSales()
    double sales=0;
    for(int i=0; i<=count; i++)
    double price=mufflers[count].getCost();
    if (price!=9999.99)
    sales+=mufflers[count].getCost();
    return sales;
    *Returns total sales for the franchise
    *@return sales the total sales
    public double getTotalSales()
    double sales;
    return sales=calculateTotalSales();
    *Returns a particular installation for the franchise
    *@param name the customer name
    *@return statement the installations details
    public String getMuffler(String name)
    String statement= name + "not found";
    for (int i=0; i<=count; i++)
    if (mufflers[i].getCustomer().equalsIgnoreCase(name))
    statement=mufflers[i].toString();
    return statement;
    *Returns all installations, franchise name, id and total sales
    *@return info the sales history for the franchise
    public String toString()
    String info="Franchise ID: " + franchiseID + "\nFranchise Name: " + franchiseName + "\nTotal Sales: " + getTotalSales() + "\n";
    for (int i=0; i<=count; i++)
    info+=mufflers[i].toString();
    return info;
    private int franchiseID;
    private int count=0;
    private String franchiseName;
    private Muffler[] mufflers = new Muffler[10];

    Thank you. That did fix those problems, but now I am getting the same error for this in Installations Class:
    private double calculateTotalSales()
             double sales=0;
             for(int i=0; i<count; i++)
                 double price=mufflers[count].getCost(); //This line is causing the problem
                 if (price!=9999.99)
                     sales+=mufflers[count].getCost();            
             return sales;     
         }    and this block in Installations Class:
         public double getTotalSales()
           double sales;
           return sales=calculateTotalSales(); // This line is getting the error
         }and this in the driver program (InstallationsTest)
          System.out.println("The total sales are $" +install.getTotalSales());You will notice that I do not have the i<=count in the for loop here. I get the error both ways, though. What am I doing wrong?

  • Need help with arrays in a survey

    I am making a survey using arrays to store the answers to 2 questions and output the frequencies of each answer, as well as the average rating for each question. When I do it in a structured manner, it works properly:
    import java.text.DecimalFormat;  //in order to format numbers
    import javax.swing.*;
    public class Music1
      public static void main (String[] args)
        int iCount = 0, iResponsesSum1 = 0, iResponsesSum2 = 0, iParticipants;
        double dResponsesAve1 = 0, dResponsesAve2 = 0;
        String sInput = "", sOutput = "", sOutput1 = "";
        int frequency1[] = new int[6];
        int frequency2[] = new int[6];
        iParticipants = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of participants\nin music taste survey:"));
        int responses1[] = new int[iParticipants];
        int responses2[] = new int[iParticipants];
        for (iCount = 0; iCount < responses1.length; iCount++)//for loop
          responses1[iCount] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please rate Rave music (1: awful - 5: great):", "Participant #" + (iCount + 1) + ":", JOptionPane.QUESTION_MESSAGE));//display first input box
          responses2[iCount] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please rate Rock & Roll music (1: awful - 5 great):", "Participant #" + (iCount + 1) + ":", JOptionPane.QUESTION_MESSAGE));//display second input box
          ++frequency1[responses1[iCount]];
          ++frequency2[responses2[iCount]];
          iResponsesSum1+= responses1[iCount];//sum answers for first question
          iResponsesSum2+= responses2[iCount];//sum answers for second question
        }//end for loop
        for (int rating = 1; rating < frequency1.length; rating++)
          sOutput1+=  " Participants who left rating " + rating + " \t" + frequency1[rating] + "\t" + frequency2[rating] + "\n";
        }//end for loop
        dResponsesAve1 = iResponsesSum1/(double)(responses1.length);
        dResponsesAve2 = iResponsesSum2/(double)(responses2.length);
        DecimalFormat myFormat = new DecimalFormat("0.00");
        sOutput = "\tMusic Survey Results\n\n\n\n" +
           " Number of participants: " + iParticipants + "\n\n" +
           " Rave average rating:  " + myFormat.format(dResponsesAve1) + "\n" +             " Rock average rating:  " + myFormat.format(dResponsesAve2) + "\n\n\n" +
           "\tRatings by music:\n\n" +
           "\t\t" +
           "Rave\tRock" + "\n" +
           sOutput1 + "\n";
        JTextArea outputArea = new JTextArea(20, 15);
        outputArea.setText(sOutput);
        JOptionPane.showMessageDialog(null, outputArea, "Music Survey", JOptionPane.PLAIN_MESSAGE);//output the message
      System.exit(0);//exit the program
      }//end main
    }//end classNow, the problems start when I try to transform that into classess that create survey object and methods to be performed on that object.
    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;
    public class Music
         public int iCount;
         public int iRating;
         private int iResponsesSum1;
         private int iResponsesSum2;
         private int iParticipants;
         private double dResponsesAve1;
         private double dResponsesAve2;
         private String sInput;
         private String sOutput1;
         private String sOutput;
         private int responses1[];
         private int responses2[];
         private int frequency1[];
         private int frequency2[];
         public Music()
              setParticipants();
              iCount = 0;
              iRating = 0;
              iResponsesSum1 = 0;
              iResponsesSum2 = 0;
              iParticipants = 0;;
              dResponsesAve1 = 0;
              dResponsesAve1 = 0;
              iParticipants = 0;
              sInput = "";
              sOutput = "";
              sOutput1 = "";
              responses1 = new int[iParticipants];
              responses2 = new int[iParticipants];
              frequency1 = new int[6];
              frequency2 = new int[6];
         public void setParticipants()
              iParticipants = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of participants\nin music taste survey:"));
         public int getParticipants()
              return iParticipants;
         public void setResponses1()
              for (iCount = 0; iCount < responses1.length; iCount++)//for loop
                   responses1[iCount] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please rate Rave music (1: awful - 5: great):", "Participant #" + (iCount + 1) + ":", JOptionPane.QUESTION_MESSAGE));//display first input box
         public void setResponses2()
              for (iCount = 0; iCount < responses1.length; iCount++)//for loop
                   responses2[iCount] = Integer.parseInt(JOptionPane.showInputDialog(null, "Please rate Rock & Roll(1: awful - 5: great):", "Participant #" + (iCount + 1) + ":", JOptionPane.QUESTION_MESSAGE));//display second input box
         public void setFrequency1()
              ++frequency1[responses1[iCount]];     
         public void  setFrequency2()
              ++frequency1[responses1[iCount]];     
         public void  setSum1()
              iResponsesSum1+= responses1[iCount];//sum answers for first question
         public int getSum1()
              return iResponsesSum1;
         public void  setSum2()
              iResponsesSum2+= responses2[iCount];//sum answers for first question     
         public int getSum2()
              return iResponsesSum2;
         public void setFrequenciesByRating()
              sOutput1+=  "Participants who left rating " + iRating + "               " + frequency1[iRating] + "                        " + frequency2[iRating] + "\n";
         public String getFrequenciesByRating()
              return sOutput1;
         public double getAverage1()
              dResponsesAve1 = getSum1()/(double)(responses1.length);
              return dResponsesAve1;
         public double getAverage2()
              dResponsesAve2 = getSum2()/(double)(responses2.length);
              return dResponsesAve2;
         public String toString()
              DecimalFormat myFormat = new DecimalFormat("0.00");
              sOutput = "                        Music Survey Results\n\n\n\n" +
                   "Number of participants: " + getParticipants() + "\n\n" +
                   "Rave average rating:  " + myFormat.format(getAverage1()) + "\n" +
                   "Rock average rating:  " + myFormat.format(getAverage2()) + "\n\n\n" +
                   "                        Ratings by music:\n\n" +
                   "                                                          " +
                   "Rave       Rock" + "\n" +
                   getFrequenciesByRating() + "\n";
              return sOutput;
    }Here is what I have for the main program:
    mport java.text.DecimalFormat;  //in order to format numbers
    import javax.swing.JOptionPane;
    public class MusicApp
         public static void main (String[] args)
              int iCount = 0, iRating = 0;
              int responses1[] = new int[6];
              Music survey = new Music();
              for (int iCount1 = 0; iCount1 < responses1.length; iCount1++)
                   survey.setResponses1();
              for (int iCount2 = 0; iCount2 < responses1.length; iCount2++)
                   survey.setResponses2();
              for (int iCount3 = 0; iCount3 < responses1.length; iCount3++)
                   survey.setFrequency1();
              for (int iCount4 = 0; iCount4 < responses1.length; iCount4++)
                   survey.setFrequency2();
              for (iRating = 1; iRating < responses1.length; iRating++)
                   survey.setFrequenciesByRating();
              JOptionPane.showMessageDialog(null,survey.toString(), "Music Survey", JOptionPane.PLAIN_MESSAGE);//output the message
              System.exit(0);//exit the program
    }This obviously doesn't work, it gives me an ArrayIndexOutOfBoundsException.
    I tried to twist it in every way I could think of, but I still couldn't get it to work. I would like the program to run as it does in the structured form.
    I think I have a problem with the scope of the variables, but I am really not sure, that's why I hope that someone can give me some insight into what I am doing wrong.
    So, please, any constructive comment or advice is greatly appreciated.

    By the way, have a good look at your Music constructor:
    setParticipants(); //this will only be called once!
    iCount = 0;
    iRating = 0;
    iResponsesSum1 = 0;
    iResponsesSum2 = 0;
    iParticipants = 0;; //double semicolon :)
    dResponsesAve1 = 0;
    dResponsesAve1 = 0;
    iParticipants = 0; //!!
    sInput = "";
    sOutput = "";
    sOutput1 = "";
    responses1 = new int[iParticipants]; //this creates an array of int with size 0 (see iParticipants)
    responses2 = new int[iParticipants]; //idem
    frequency1 = new int[6]; //this creates an array of size 6 [0,0,0,0,0,0]
    frequency2 = new int[6]; //idem

  • I need help with color pallette in iPhoto 11. I have created a book and would like to use a different color background than those given in "background." I have found the color palettes but can't seem to incorporate them into my backgrounds palette.

    I need help with color pallette in iPhoto 11. I have created a book and would like to use a different color background than those given in "background." I have found the color palettes but can't seem to incorporate them into my backgrounds palette.

    That is not a feature of iPhoto - suggest to Apple - iPhoto Menu ==> provide iPhoto feedback.
    Additionally I have no idea what you are saying here
    I have found the color palettes but can't seem to incorporate them into my backgrounds palette.
    And it always helps for you to dientify the version of iPhoto that you are using
    LN

  • I just created an iCloud email and I want to use that email for my iTunes account as well. I need help suiting the old apple I'd because I do not remember anything associated with that email and I don't know the security questions

    I just created an iCloud email and I want to use that email for my iTunes account as well. I need help switching the old apple ID because I do not remember anything associated with that email and I don't know the security questions or the login for that old email.

    You cannot do that.  The AppleID you used to create the iCloud account is an active primary email address.  The email address you created with the iCloud account is also an active primary email address (all Apple domain email address automatically become AppleIDs as well).  You cannot replace the primary email address on one active AppleID with the primary email address on another, active AppleID.
    You can use your iCloud email/AppleID with iTunes, but it will be a separate account, so all your previous purchases remain tied to the other AppleID you have.
    I don't understand your statement that you could not remeber your old AppleID password, as you would have had to use it to create the iCloud account in the first place (the first step of creating the iCloud account required you to login with your existing AppleID and password)?

  • Hello, I need help with my macbook pro. It looks like I cannot install anything anymore. Everytime I try to install a new software, use the migration assistant or click the lock to make changes, it simply does not react.

    Hello, I need help with my macbook pro.
    It looks like I cannot install anything anymore. Everytime I try to install a new software, I simply get stuck during the installation type process. I put in my password, it does accept it, but it does not go any further.
    I tried to reset the password, put no password, repair the permissions, the disk but nothing will do. I nearly got stuck with the log in screen but finally succeeded in disabling it.
    So I thought I might try to create a new account but I cannot click the lock to make changes. It simply refuses to react.
    I am now thinking about using the migration assistant to save all my settings, data and so fourth, but again I get stuck when I have to type in my password. It accepts it but nothing happens...
    I guess it has something to do with the authorization process, but can't find anything on the internet about it... Can you help me out?
    I am running Lion 10.7.3.
    Regards,
    Nicolas.
    (I apologize if any grammatical/structural mistakes were to be found, english is not my mother-tongue. )

    You probably won't like this suggestion, but I suggest you reinstall Lion.
    First, backup your system. Next, reboot your system, press/hold the COMMAND-R keys to boot into the Recovery HD. Select 'Reinstall Mac OS X'. If you purchased Lion as an upgrade to Snow Leopard, the reinstall process will install Lion 10.7.3. If your system came preinstalled with Lion, you might still get Lion 10.7.2. Both installs are a total install of the OS. None of your apps or data will be impacted. Just the OS.

  • I need help with event structure. I am trying to feed the index of the array, the index can vary from 0 to 7. Based on the logic ouput of a comparison, the index buffer should increment ?

    I need help with event structure.
    I am trying to feed the index of the array, the index number can vary from 0 to 7.
    Based on the logic ouput of a comparison, the index buffer should increment
    or decrement every time the output of comparsion changes(event change). I guess I need to use event structure?
    (My event code doesn't execute when there is an  event at its input /comparator changes its boolean state.
    Anyone coded on similar lines? Any ideas appreciated.
    Thanks in advance!

    You don't need an Event Structure, a simple State Machine would be more appropriate.
    There are many examples of State Machines within this forum.
    RayR

  • Need help with the Vibrance adjustment in Photoshop CC 2014.

    Need help with the Vibrance adjustment in Photoshop CC 2014.
    Anytime I select Vibrance to adjust the color of an image. The whole image turns Pink in the highlights when the slider is moved from "0" to - or + in value.  Can the Vibrance tool be reset to prevent this from happening? When this happens I cn not make adjustments...just turns Pink.
    Thanks,
    GD

    Thank you for your reply. 
    Yes, that does reset to “0” and the Pink does disappear.
    But as soon as I move the slider +1 or -1 or higher the image turns Pink in all of the highlights again, rather than adjusting the overall color.
    GD
    Guy Diehl  web: www.guydiehl.com | email: [email protected]

Maybe you are looking for