Method cannot be applied error

I am having trouble compiling my application because it says a sorting method I want to use cannot be applied to the array I want to sort.
I have a class that was supplied by my instructor that contains a constuctor for an object called "automobile". This constructor has 4 args which are (string, string, double, double). The strings are for make and model of vehicle and the doubles are for gas tank size and range on a full tank. The constructor takes the double values and calculates the miles per gallon. In my application I am making an array of 15 vehicles called "automobile". When I print to an outpuBox the list of vehicles, everthing looks fine. The problem is I need to sort the array by the miles per gallon. Now I have made a seperate class the contains my "cocktail shaker sort", but when it seems that the array of vehicles I created cannot be used in the args of the sort method. Any help would be greatly appeciated. This thing was due a week ago and I've been pulling my hair for 3weeks.
The error message is:
Autos.java:64: cockTailSort(int[]) in CockTail cannot be applied to (Automobile[])
CockTail.cockTailSort(automobile);
1 error
Below is my application and following that will be the cocktailshaker class.
import javabook.*;
import java.text.DecimalFormat;
class Autos
public static void main (String[] args){
MainWindow mainWindow;
InputBox inputBox;
OutputBox outputBox;
MessageBox messageBox;
ResponseBox responseBox;
String modelName, modelType;
double gasTankCapacity, rangeOnFullTank;
int count;
mainWindow = new MainWindow ("Automobile input");
inputBox = new InputBox (mainWindow);
outputBox = new OutputBox (mainWindow);
responseBox = new ResponseBox (mainWindow );
messageBox = new MessageBox (mainWindow);
messageBox.setVisible (false );
mainWindow.setVisible ( true ) ;
outputBox.setVisible ( true ) ;
Automobile[] automobile = new Automobile [3];
int i=0;
count =1;
for (i = 0 ; i < automobile.length ; i ++){
modelName = inputBox.getString ("Enter Model Name for vehicle #" + count);
modelType = inputBox.getString ("Model Type for #" + count);
gasTankCapacity = inputBox.getDouble("Gas capacity for #" + count);
rangeOnFullTank = inputBox.getDouble("Fulltank range for #" + count);
automobile[ i ] = new Automobile ( modelName, modelType,gasTankCapacity,rangeOnFullTank );
count ++;
CockTail.cockTailSort(automobile);
for (i = 0 ; i < automobile.length ; i ++){
automobile.displayAutomobile(outputBox);
Here is the sort:
import javabook.*;
class CockTail
public CockTail()
public static void cockTailSort (int a [] )
boolean sorted = false;
int top = a.length -1, bottom =0;
for (int pass =1; bottom < top && !sorted; pass ++)
sorted = true;
if (pass % 2 != 0) // odd # passes
for (int i = bottom; i < top; i ++)
if (a[i] > a[i + 1])
sorted = false;
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
top --;
else // even-numbered passes
for (int i = top; i > bottom; i--)
if (a[i - 1] > a[i])
sorted =false;
int temp = a[i];
a[i] = a[i - 1];
a[i - 1] = temp;
bottom ++;

Well I changed it to what you said and it didn't work. I really appreciate your though.
Here are the source codes :
import javabook.*;
import java.util.*;
import java.text.DecimalFormat;
class Autos
* Setting data members and constructors
public static void main (String[] args){
MainWindow mainWindow;
InputBox inputBox;
OutputBox outputBox;
MessageBox messageBox;
ResponseBox responseBox;
String modelName, modelType;
double gasTankCapacity, rangeOnFullTank;
int count;
mainWindow = new MainWindow ("Automobile input");
inputBox = new InputBox (mainWindow);
outputBox = new OutputBox (mainWindow);
responseBox = new ResponseBox (mainWindow );
messageBox = new MessageBox (mainWindow);
messageBox.setVisible (false );
mainWindow.setVisible ( true ) ;
outputBox.setVisible ( true ) ;
outputBox.printLine("This program will ask for data for 15 vehicles and ");
outputBox.printLine("calculate the Miles Per Galllon for each vehicle and ");
outputBox.printLine("compare the MPGs to be displayed in a sorted list in an outpuBox.");
outputBox.printLine("you will be asked to enter the vehicles model, model type");
outputBox.printLine("gas tank capacity and total range on a full tank.");
// create an automobile array
Automobile[] automobile = new Automobile [3];
* Loop for data inputs an array creation
int i=0;
count =1;
for (i = 0 ; i < automobile.length ; i ++){
modelName = inputBox.getString ("Enter Model Name for vehicle #" + count);
modelType = inputBox.getString ("Model Type for #" + count);
gasTankCapacity = inputBox.getDouble("Gas capacity for #" + count);
rangeOnFullTank = inputBox.getDouble("Fulltank range for #" + count);
automobile[ i ] = new Automobile ( modelName, modelType,gasTankCapacity,rangeOnFullTank );
count ++;
*Code for cocktail sort method call
CockTail.cockTailSort(automobile); // Error in code
* Display data and MPG's in outputBox
for (i = 0 ; i < automobile.length ; i ++){
automobile.displayAutomobile(outputBox);
Here is the cocktail shaker sort:
import javabook.*;
import java.util.*;
class CockTail
//public CockTail()
public static void cockTailSort (Automobile[] a )
boolean sorted = false;
int top = a.length -1, bottom =0;
for (int pass =1; bottom < top && !sorted; pass ++)
sorted = true;
if (pass % 2 != 0) // odd # passes
for (int i = bottom; i < top; i ++)
if (a[i] .compareto( a[i + 1])==1)
sorted = false;
Automobile temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
top --;
else // even-numbered passes
for (int i = top; i > bottom; i--)
if (a[i] .compareto( a[i - 1])==1)
sorted =false;
Automobile temp = a[i];
a[i] = a[i - 1];
a[i - 1] = temp;
bottom ++;
Here is what I know of the Automobile class:
// JBuilder API Decompiler stub source generated from class file
// Aug 6, 2002
// -- implementation of methods is not available
// Imports
import java.lang.String;
import javabook.OutputBox;
class Automobile {
// Fields
private String modelName;
private String modelType;
private double gasTankCapacity;
private double rangeOnFullTank;
private double milesPerGallon;
// Constructors
public Automobile() { }
public Automobile(String p0, String p1, double p2, double p3) { }
// Methods
public int compareto(Automobile p0) { }
public void displayAutomobile(OutputBox p0) { }

Similar Messages

  • SAP Front-End Patch cannot be applied error

    I have SAP GUI 7.2 patch level 4 installed on my machine and I am  adobe life cycle designer. I got this error when I tried to install
    "This SAP Front-End Patch cannot be applied. Either the installed components are already on the same patch level or the components to be patched are not yet installed at all.
    SAP Interactive Forms - Adobe LifeCycle Designer 8.0 Patch
    Patchlevel 3"
    How do I install the adobe LifeCycle designer?

    hello,
    Please try uninstalling and reinstalling the GUI
    a) Remove all SAP components via "Control panel", this is very
         important
    b) Install SAP GUI
    c) Install latest GUI Patch
    You can download these patches from the following url.
    Apply GUI 7.10 patch  from the following url,
    Goto URL: http://www.service.sap.com/swdc
    SAP Software Distribution Center -> Download -> Support Packages and
    Patches -> Entry by Application Group -> SAP Frontend Components ->
    SAP GUI FOR WINDOWS -> SAP GUI FOR WINDOWS 7.10 CORE -> win32 ->
    regards,
    John Feely

  • After installing Illustrator CC, an update cannot be applied ERROR: U44M1I210

    This error when tryng to apply an update:
    Update failed: Unable to extract the downloaded files. Press retry to download again.
    Thanks,
    Juan Dent

    This does not work. There are no erros in the log file.
    Upon installing Premiere Pro CC, I got the same problem - installed okm but not accepting updates.
    Could this be a security issue?
    Where can we download the patches since the Creative Cloud Desktop is useless?
    Thanks,
    Juan

  • Cannot be applied

    Hello,
    I am trying to call the method print();
    Could someone please tell me what parameters i need to put in to get it to call? Right now its giving me a cannot be applied error.
    The print() method is in the Coin class which is a different class. Thanks
    Coin p = new Coin()//<----pretty sure i need this to call a method in a different class
    Coin.print(not sure what to put here);
    public static void print(int ncount,int dcount,int qcount,LinkedList<String>nickels,LinkedList<String>dimes,
                                 LinkedList<String>quarters,String type)//<---method that needs to be called

    Honestly, because static methods are easier to call.Huh? Apperently you have no idea what static means.
    Sorry Im really new.No need for sorry, just do some research if you don't know what something means/does. You should use the static keyword for methods that "do not directly belong" to a specific instance of a class.
    Example:
    class Coin {
      static Coin createNickle() {
        // return a Coin with a value of a nickle
    }now you can create a Coin object with the static above:Coin nickle = Coin.createNickle();But a print() method suggests that you print the internal state of an instance (nickle is an instance of a Coin)
    class Coin {
      int value;
      static void print() {
        // from here you cannot print 'value', since the print() method is static!
        // In other words: it does not belong to this instance
    }so you should do it like this:class Coin {
      int value;
      void print() {
        // now print the 'value' variable
    }and you can now do:Coin nickle = Coin.createNickle();
    nickle.print();understand?
    Of course, you can create new intance of a Coin by calling it's constructor (if there is one), it was only an example of me to do it with a static (factory) method.

  • Cannot be applied to (java.io.PrintWriter) error

    Hi guys I get the following errors when trying to compile my program and I was wondering how to solve it
    printPay() in PaySlip cannot be applied to (java.io.PrintWriter)
    slip.printPay(slipWrite)
    import java.io.*;
    public class PayApp
      public static void main(String[] args)
        boolean end_of_file = false;
        EmpInFile   f1 =  new EmpInFile(); 
        EmpOutFile  f2 =  new EmpOutFile();
        Employee    emp = null;       
        PaySlip     slip = null;           
        Report   sum = null;     
        PrintWriter slipWrite = null;
        PrintWriter sumWrite  = null;
        if (args.length != 4)    // correct number ?
          errExit("Names of Input employee file , output employee file, payslip file \n, and report file required");
         emp = new Employee();
         sum =   new Report();
         slip  = new PaySlip(emp,sum);
       try
           f1.openFile(args[0]);  
           f2.openFile(args[1]);  
           slipWrite = new PrintWriter(new FileWriter(args[2]));
           sumWrite =  new PrintWriter(new FileWriter(args[3]));
          catch(IOException e)
             System.err.println("error opening files" + e.toString());
             System.exit(1);
         while (!end_of_file )
            end_of_file = f1.readRecord(emp);
            if(!end_of_file)
               slip.printPay(slipWrite); 
               f2.addRecord(emp);  
            }// end if ! end
          }// end while
           System.out.println("All employees processed ");
           sum.printTotals(sumWrite);  
           sumWrite.flush();
           sumWrite.close();        
           slipWrite.flush();
           slipWrite.close();
           f1.closeFile();
           f2.closeFile();
      static void  errExit(String message)
       System.err.println(message);
       System.exit(1);
    public class PaySlip
    // declare variables
         private double gross;
         private double tax;
         private double taxcredits;
         private Employee emp;
         private Report rep;
         public PaySlip (Employee e, Report r)
         emp = e;
         rep = r;
         double gross = 0;
         double tax = 0;
         double taxcredits = 0;
         public void setGross(double gr)
         gross = gr;
         public void setTax(double tx)
         tax = tx;
         public void settaxCreds(double taxcreds)
         taxcredits = taxcreds;
         public void printPay()
         emp.calcPay(this);
         double netpay;
         netpay = gross - tax;
         System.out.println("____________________________________________________");
         System.out.println("               Payslip Information                  ");
         System.out.println("Employee Name: \t\t" +emp.getFirst() +" "+ emp.getLast());
         System.out.println("Employee Id: \t\t" +emp.getId());
         System.out.println("Net Pay: \t" +netpay);
         System.out.println("Year To Date Gross: \t" +emp.getYtdGross());
         System.out.println("Year To Date Tax: \t" +emp.getYtdTax());
         System.out.println("____________________________________________________");
         System.out.println("               Department Totals                    ");
         char dcode = emp.getDeptCode();
         rep.addToTotals(gross,tax,dcode);
    }Any help would be greatly appreciated.

    Post the actual error which would in include a line number when noting errors.
    slip.printPay(slipWrite); The method printPay() does not take parameters. So you can't put 'slipWrite" there.

  • Operator + cannot be applied to operands of type 'method group and 'int'

    Hello I have a problem that I'm trying to fire a bullet everytime I pressed the spacebar key, but I have this problem that is cropping up.
     if ((e.KeyCode == Keys.Space) && (playerOne.Bullet.Alive == false))
                                playerOne.Bullet.Alive = true;
                                playerOne.Bullet.getX = playerOne.getXposition + 15;
                                playerOne.Bullet.getY = playerOne.getYposition + 10;
    It says in the error list: "Opeartor '+' cannot be applied to operands of type 'method group' and 'int'", I have no clue. I'm also new to programming.

    I want to get the bullet to shoot where the player is, here is the code:
    class Player
            // attributes here  -   Int other words data types and variables:
            int health = 3;
            float xPosition;
            float yPosition;
            Bitmap playerGraphics;
            int score = 0;
            bool leftPressed;
            bool rightPressed;
            float Width = 50;
            public Bullet Bullet = new Bullet();
            // functions here:
            public void Init()
                // Get Player_Bat.png from resources, so that we can work with it:
                playerGraphics = new Bitmap(Green_Aliens.Properties.Resources.Player_Bat);
                health = 3;
                score = 0;
                xPosition = 375;
                yPosition = 540;
                leftPressed = false;
                rightPressed = false;
                Bullet Bullet = new Bullet();
            public float getWidth()
                return Width;
            public void toggleLeftPressed()
                if (leftPressed == true)
                    leftPressed = false;
                else
                    leftPressed = true;
            public void toggleRightPressed()
                if (rightPressed == true)
                    rightPressed = false;
                else
                    rightPressed = true;
            public bool getLeftPressed()
                return leftPressed;
            public bool getRightpressed()
                return rightPressed;
            public Bitmap getGraphics()
                return playerGraphics;
            public float getXposition()
                return xPosition;
            public float getYposition()
                return yPosition;
            public int getHealth()
                return health;
            public int getScore()
                return score;
            public void moveLeft()
                xPosition -= 10;
            public void moveRight()
                xPosition += 10;
            public void loseLife()
                health--;
            public void adScore(int valueAdd)
                score += valueAdd;
            //Resets the player to the start position:
            public void resetPosition()
                xPosition = 400;
                yPosition = 550;

  • PSE 9.0.3 update can't install. Error message is "patch cannot be applied."

    PSE 9.0.3 does not install. Error message "patch cannot be applied."

    Manually install the download the update from below given link:-
    For Mac:- http://www.adobe.com/support/downloads/detail.jsp?ftpID=5012
    For Win:- http://www.adobe.com/support/downloads/detail.jsp?ftpID=5000
    Download and install the update.

  • Cannot install update 9.0.3 in my Photoshop Elements 9. Getting error msg "Patch cannot be applied".

    Cannot install update 9.0.3 in my Photoshop Elements 9. Getting error msg "Patch cannot be applied". How can I correct?

    Nobody can know. You are not offering system info or otehr details. Start by uninstalling and reinstalling the base program.
    Mylenium

  • Error messages!  area(double, double) cannot be applied to ( )

    I keep getting these error messages:
    area(double,double) in Rectangle cannot be applied to ()
              return "Area: " + Rectangle.area() + "\tCircumference: " + Rectangle.perimeter(); ^
    perimeter(double,double) in Rectangle cannot be applied to ()
              return "Area: " + Rectangle.area() + "\tCircumference: " + Rectangle.perimeter();
    ^
    setSides(double,double) in Rectangle cannot be applied to (double)
              R.setSides(input.nextDouble());
    ^
    3 errors
    Tool completed with exit code 1
    Can anybody tell me why it is doing this? Thanks in advance!
    import java.util.Scanner;
    public class Rectangle
         public double length;
         public double width;
         public Rectangle()
              length = 0;
              width = 0;
         public double getSides()
              return length;
              return width;
         public void setSides(double length, double width)
              this.length = length;
              this.width = width;
         public double area(double length, double width)
              double area = length * width;
              return area;
         public double perimeter(double length, double width)
              double perimeter = (length * 2) + (width * 2);
              return perimeter;
         public String toString()
              return "Area: " + Rectangle.area() + "\tCircumference: " + Rectangle.perimeter();
         public static void main(String [] args)
              Rectangle R = new Rectangle();
              Scanner input = new Scanner(System.in);
              System.out.println("Enter radius: ");
              R.setSides(input.nextDouble());
              System.out.println(R.toString());
    }

    Looking at your code more, it looks like what you want to do when you call area is get the area of the Rectangle based on the length and width it already has stored, not what you pass it. So if you take out the parameters like this:
    public double area() {
         double area = length * width;
         return area;
    }It will use the member variables length and width to calculate area.

  • Need help with class info and cannot find symbol error.

    I having problems with a cannot find symbol error. I cant seem to figure it out.
    I have about 12 of them in a program I am trying to do. I was wondering if anyone could help me out?
    Here is some code I am working on:
    // This will test the invoice class application.
    // This program involves a hardware store's invoice.
    //import java.util.*;
    public class InvoiceTest
         public static void main( String args[] )
         Invoice invoice1 = new Invoice( "1234", "Hammer", 2, 14.95 );
    // display invoice1
         System.out.println("Original invoice information" );
         System.out.println("Part number: ", invoice1.getPartNumber() );
         System.out.println("Description: ", invoice1.getPartDescription() );
         System.out.println("Quantity: ", invoice1.getQuantity() );
         System.out.println("Price: ", invoice1.getPricePerItem() );
         System.out.println("Invoice amount: ", invoice1.getInvoiceAmount() );
    // change invoice1's data
         invoice1.setPartNumber( "001234" );
         invoice1.setPartDescription( "Yellow Hammer" );
         invoice1.setQuantity( 3 );
         invoice1.setPricePerItem( 19.49 );
    // display invoice1 with new data
         System.out.println("Updated invoice information" );
         System.out.println("Part number: ", invoice1.getPartNumber() );
         System.out.println("Description: ", invoice1.getPartDescription() );
         System.out.println("Quantity: ", invoice1.getQuantity() );
         System.out.println("Price: ", invoice1.getPricePerItem() );
         System.out.println("Invoice amount: ", invoice1.getInvoiceAmount() );
    and that uses this class file:
    public class Invoice
    private String partNumber;
    private String partDescription;
    private int quantityPurchased;
    private double pricePerItem;
         public Invoice( String ID, String desc, int purchased, double price )
              partNumber = ID;
         partDescription = desc;
         if ( purchased >= 0 )
         quantityPurchased = purchased;
         if ( price > 0 )
         pricePerItem = price;
    public double getInvoiceAmount()
         return quantityPurchased * pricePerItem;
    public void setPartNumber( String newNumber )
         partNumber = newNumber;
         System.out.println(partDescription+" has changed to part "+newNumber);
    public String getPartNumber()
         return partNumber;
    public void setDescription( String newDescription )
         System.out.printf("%s now refers to %s, not %s.\n",
    partNumber, newDescription, partDescription);
         partDescription = newDescription;
    public String getDescription()
         return partDescription;
    public void setPricePerItem( double newPrice )
         if ( newPrice > 0 )
    pricePerItem = newPrice;
    public double getPricePerItem()
    return pricePerItem;
    Any tips for helping me out?

    System.out.println("Part number:
    "+invoice1.getPartNumber;
    The + sign will concatenate invoice1.getPartNumber()
    after "Part number: " forming only one String.I added the plus sign and it gives me more errors:
    C:\>javac InvoiceTest.java
    InvoiceTest.java:16: operator + cannot be applied to java.lang.String
            System.out.println("Part number: ",   + invoice1.getPartNumber() );
                                                  ^
    InvoiceTest.java:17: cannot find symbol
    symbol  : method getPartDescription()
    location: class Invoice
            System.out.println("Description: ", + invoice1.getPartDescription() );
                                                          ^
    InvoiceTest.java:17: cannot find symbol
    symbol  : method println(java.lang.String,int)
    location: class java.io.PrintStream
            System.out.println("Description: ", + invoice1.getPartDescription() );
                      ^
    InvoiceTest.java:18: cannot find symbol
    symbol  : method getQuantity()
    location: class Invoice
            System.out.println("Quantity: ", + invoice1.getQuantity() );
                                                       ^
    InvoiceTest.java:18: cannot find symbol
    symbol  : method println(java.lang.String,int)
    location: class java.io.PrintStream
            System.out.println("Quantity: ", + invoice1.getQuantity() );
                      ^
    InvoiceTest.java:19: cannot find symbol
    symbol  : method println(java.lang.String,double)
    location: class java.io.PrintStream
            System.out.println("Price: ", + invoice1.getPricePerItem() );
                      ^
    InvoiceTest.java:20: cannot find symbol
    symbol  : method println(java.lang.String,double)
    location: class java.io.PrintStream
            System.out.println("Invoice amount: ", + invoice1.getInvoiceAmount() );
                      ^
    InvoiceTest.java:24: cannot find symbol
    symbol  : method setPartDescription(java.lang.String)
    location: class Invoice
            invoice1.setPartDescription( "Yellow Hammer" );
                    ^
    InvoiceTest.java:25: cannot find symbol
    symbol  : method setQuantity(int)
    location: class Invoice
            invoice1.setQuantity( 3 );
                    ^
    InvoiceTest.java:30: operator + cannot be applied to java.lang.String
            System.out.println("Part number: ", + invoice1.getPartNumber() );
                                                ^
    InvoiceTest.java:31: cannot find symbol
    symbol  : method getPartDescription()
    location: class Invoice
            System.out.println("Description: ", + invoice1.getPartDescription() );
                                                          ^
    InvoiceTest.java:31: cannot find symbol
    symbol  : method println(java.lang.String,int)
    location: class java.io.PrintStream
            System.out.println("Description: ", + invoice1.getPartDescription() );
                      ^
    InvoiceTest.java:32: cannot find symbol
    symbol  : method getQuantity()
    location: class Invoice
            System.out.println("Quantity: ", + invoice1.getQuantity() );
                                                       ^
    InvoiceTest.java:32: cannot find symbol
    symbol  : method println(java.lang.String,int)
    location: class java.io.PrintStream
            System.out.println("Quantity: ", + invoice1.getQuantity() );
                      ^
    InvoiceTest.java:33: cannot find symbol
    symbol  : method println(java.lang.String,double)
    location: class java.io.PrintStream
            System.out.println("Price: ", + invoice1.getPricePerItem() );
                      ^
    InvoiceTest.java:34: cannot find symbol
    symbol  : method println(java.lang.String,double)
    location: class java.io.PrintStream
            System.out.println("Invoice amount: ", + invoice1.getInvoiceAmount() );
                      ^
    16 errors

  • Create(java.io.InputStream) in Scanner cannot be applied to (java.io.File)

    Ahhh!!!
    Ahem, when I try to compile the file below, "PhoneDirectory.java", I get the following compilation error message:
    PhoneDirectory.java:12: create(java.io.InputStream) in Scanner cannot be applied to (java.io.File)
        Scanner fin = Scanner.create(file);After quite a bit of tweaking... I'm right back where I started. I'm a seasoned programmer, as far as concepts are concerned, but rather new to JAVA.
    The error seems to be occuring where a new instance of "Scanner" is supposed to be created. It uses file I/O, and I had only used the Scanner class for the keyboard input in the past.
    Looking at the Scanner class, everything seems to be right to me. I'm probably missing some simple fundamental concept, and I've been pulling my hair out trying to get it... Please help me shed some light on this situation!
    =========
    PhoneDirectory.java
    =========
    import java.io.*;
    // Read a file of names and phone numbers
    // into an array. Sort them into ascending
    // order using bubble sort.
    // Print names and numbers before and after sort.
    public class PhoneDirectory {
      public static void main (String[] args) {
        PhoneEntry[] directory = new PhoneEntry[200];
        File file = new File("c:\\jessica\\phonenum.txt");
        Scanner fin = Scanner.create(file);
        int numberEntries = 0;
        // read array from file
        while (fin.hasNextInt())
          directory[numberEntries++] = new PhoneEntry(fin);
        // print array as read
        for (int i=0; i<numberEntries; i++)
          System.out.println(directory);
    // sort by ordering defined in PhoneEntry,
    // in this case lastName firstName
    bubbleSort(directory, numberEntries);
    // print sorted array
    System.out.println(
    "============================================");
    for (int i=0; i<numberEntries; i++)
    System.out.println(directory[i]);
    static void bubbleSort(PhoneEntry[] a, int size) {
    // bubbleSortr: simple to write, but very inefficient.
    PhoneEntry x;
    for (int i=1; i<size; i++)
    for (int j=0; j<size-i; j++)
    if (a[j].compareToIgnoreCase(a[j+1]) > 0) {
    // swap
    x = a[j]; a[j] = a[j+1]; a[j+1] = x;
    =========
    PhoneEntry.java
    =========
    class PhoneEntry {
    // number, name entry for a line in a Phone Directory
      protected int area;
      protected int prefix;
      protected int number;
      protected String firstName;
      protected String lastName;
      public String toString() {
      // format name and phone number to printable string
        String x = lastName + ", " + firstName;
        x = x +
        " . . . . . . . . . . . . . . .".substring(x.length())
        + "(" + area + ") " + prefix + "-" + number;
        return x;
      public int compareToIgnoreCase(PhoneEntry v) {
      // alphabetically compare names in this to names in v
      // return negative for this < v, 0 for ==,
      //        positive for this > v
        int m = lastName.compareToIgnoreCase(v.lastName);
        if (m == 0) m = firstName.compareToIgnoreCase(v.firstName);
        return m;
      public PhoneEntry(Scanner fin) {
      // input a PhoneDirectory entry. Must be space delimited
      // area prefix suffix lastname firstname
        // number
        area = fin.nextInt();
        prefix = fin.nextInt();
        number = fin.nextInt();
        // read rest of line
        String name = fin.nextLine();
        // split name into lastName firstName
        int p = name.indexOf(' ');
        if (p > 0) {
            lastName = name.substring(0,p);
            firstName = name.substring(p+1);
        else {
            lastName = name;
            firstName = "";
    }=========
    Scanner.java
    =========
        This class does input from the keyboard.  To use it you
        create a Scanner using
        Scanner stdin = Scanner.create(System.in);
         then you can read doubles, ints, or strings as follows:
        double d; int i; string s;
        d = stdin.nextDouble();
        i = stdin.nextInt();
        s = stdin.nextLine();
        An unexpected input character will cause an exception.
        You cannot type a letter when it's expecting a double,
        nor can you type a decimal point when it's expecting an int.
    import java.io.*;
    public class Scanner {
    // Simplifies input by returning
    // the next value read from the
    // keyboard with each call.
      private String s;
      private int start=0, end = 0, next;
      private BufferedReader stdin;
      Scanner(InputStream stream) {
        start = end = 0;
        // set up for keyboard input
        stdin = new BufferedReader(
        new InputStreamReader(stream));
      public static Scanner create(InputStream stream) {
        return new Scanner(stream);
      double nextDouble() {
         if (start >= end)
           try {
            s = stdin.readLine().trim() + " ";
              start = 0;
             end = s.length();
          catch (IOException e) {System.exit(1);}
         next = s.indexOf(' ',start);
         double d = Double.parseDouble(s.substring(start,next));
         start = next+1;
         return d;
      public int nextInt() {
         if (start >= end)
           try {
            s = stdin.readLine().trim() + " ";
              start = 0;
             end = s.length();
          catch (IOException e) {System.exit(1);}
         next = s.indexOf(' ',start);
         int d = Integer.parseInt(s.substring(start,next));
         start = next+1;
         return d;
      public String nextLine() {
         if (start >= end)
           try {
            s = stdin.readLine().trim() + " ";
              start = 0;
             end = s.length();
          catch (IOException e) {System.exit(1);}
         String t = s.substring(start,s.length()-1);
         start = end = 0;
         return t;
    }=========
    phonenum.txt
    =========
    336 746 6915 Rorie Tim
    336 746 6985 Johnson Gary
    336 781 2668 Hoyt James
    606 393 5355 Krass Mike
    606 393 5525 Rust James
    606 746 3635 Smithson Norman
    606 746 3985 Kennedy Amy
    606 746 4235 Behrends Leonard
    606 746 4395 Rueter Clarence
    606 746 4525 Rorie Lonnie

    I don't see a Scanner.create() method in the Scanner class but I do see a constructor with the signature you want. Change
    Scanner fin = Scanner.create(file);
    to
    Scanner fin = new Scanner(file);

  • CompareTo(Comparable) cannot be applied to...

    When I try to compile my set of files, while trying to create a priority queue, I get the following errors:
    Lijst.java:53: compareTo(Comparable) in Comparable cannot be applied to (java.lang.Object)
        if (lst == null || x.compareTo (lst.wrd) <= 0 ) {
                            ^
    Lijst.java:58: compareTo(Comparable) in Comparable cannot be applied to (java.lang.Object)
        while (h.succ != null && x.compareTo (h.succ.wrd) > 0) {
                                  ^
    Lijst.java:69: compareTo(Comparable) in Comparable cannot be applied to (java.lang.Object)
        if (lst == null || x.compareTo (lst.wrd) < 0 ) {
                            ^
    Lijst.java:74: compareTo(Comparable) in Comparable cannot be applied to (java.lang.Object)
        while (h.succ != null && x.compareTo (h.succ.wrd) > 0) {
                                  ^
    Lijst.java:78: compareTo(Comparable) in Comparable cannot be applied to (java.lang.Object)
        if (h.succ == null || x.compareTo (h.succ.wrd) < 0) {But x was typecasted to a Comparable in Lijst.java:
      void voegIn (Object y) {
        Comparable x = (Comparable) y;
        if (lst == null || x.compareTo (lst.wrd) <= 0 ) {
          zetVoor (x);
          return;
      }Why does Java forget that typecast???

    But that's why I've tried to typecast it to a
    Comparable. Because the argument of the compareTo
    function will be of type Toestand which implements
    Comparable.
    What's the alternative for this, if this is all
    wrong??Looks like you'll need to cast both the reference to
    the object whose method you're invoking and the
    reference to the argument. Comparable foo = (Comparable)bar;
    bar.compareTo((Comparable)lst.wrd); Or something like that.And of course this only works if lst.wrd points to an object that actually does implement Comparable.

  • Cannot find symbol error - Constructor

    Hi Folks,
    i am getting the following errors when the code is compiled. Please help! The code is as below. This code is for the laptop configuration. I have 2 classes, computer.java and Wclass.java with the WIn.java(main class)
    Also, how do i read the input from the radiobutton in the action performed
    WClass.java:13: cannot find symbol
    symbol : constructor Computer()
    location: class Computer
    Computer computer = new Computer();
    ^
    WClass.java:181: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,java.lang.String)
    Out.append("Computer Configuration for %s\n", computer.getName()
    ^
    WClass.java:182: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
    Out.append("Processor:\t\t\t \n", computer.getProcessor());
    ^
    WClass.java:183: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
    Out.append("HardDisk: \t\t\t \n", computer.getHarddisk());
    ^
    WClass.java:184: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
    Out.append("RAM: \t\t\t \n", computer.getRam());
    ^
    WClass.java:185: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
    Out.append("ProcessorSpeed:\t\t \n", computer.getProcessorSpeed(
    ^
    WClass.java:186: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
    Out.append("Printer: \t\t\t \n", computer.getPrinter());
    ^
    WClass.java:187: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
    Out.append("Inbuilt Wireless LAN: \t\t\n", computer.getWireless(
    ^
    WClass.java:188: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
    Out.append("Floppy(External):\t\t \n", computer.getFloppy());
    ^
    WClass.java:189: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
    Out.append("DVD Writer:\t\t\t \n", computer.getDVD());
    ^
    WClass.java:190: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (java.lang.String,float)
    Out.append("CD Writer :\t\t\t \n", computer.getCdw());
    ^
    WClass.java:191: cannot find symbol
    symbol : method getTotal()
    location: class Computer
    Out.append("Total \t\t\t \n", computer.getTotal());
    ^
    12 errors
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class Computer
         private String name;
         private float Processor_cost;
         private float total_cost;
         private float harddrive_cost;
         private float ram_cost;
         private float psspeed_cost;
         private float printer_cost;
         private float wireless_cost;
         private float floppy_cost;
         private float dvd_cost;
         private float cdwriter_cost;
         float pc[] = {1000f, 700f, 650f, 1200f};
         float hd[] = {0, 100f, 150f};
         float ps[] = {0, 100f, 125f};
         float ram[] = {0, 60f};
         float aa[] = {50f, 110f};
         float drive[] = {110f, 220f, 20};
         double T = 0.0;
    public Computer(String Cname, int pcost, float tcost, int hcost, float rcost,
    int pscost, float prcost, float wcost, float fcost, float dvdcost, float cdrwcost)
         name = Cname;
         Processor_cost = pc[pcost];
         total_cost = tcost;
         harddrive_cost = hd[hcost];
         ram_cost = rcost;
         psspeed_cost = ps[pscost];
         printer_cost = prcost;
         wireless_cost = wcost;     
         floppy_cost = fcost;
         dvd_cost = dvdcost;
         cdwriter_cost = cdrwcost;
    public void setName(String Cname)
         name = Cname;
    public String getName()
         return name;
    public void setProcessor(int pcost)
         Processor_cost = pc[pcost];
    public float getProcessor()
         return Processor_cost;
    public void setHarddisk(int hcost)
         harddrive_cost = hd[hcost];
    public float getHarddisk()
         return harddrive_cost;
    public void setRam(int rcost)
         ram_cost = rcost;
    public float getRam()
         return ram_cost;
    public void setProcessorSpeed(int pscost)
         psspeed_cost = ps[pscost];
    public float getProcessorSpeed()
         return psspeed_cost;
    public void setPrinter(float prcost)
         printer_cost = prcost;
    public float getPrinter()
         return printer_cost;
    public void setWireless(float wcost)
         wireless_cost = wcost;
    public float getWireless()
         return wireless_cost;
    public void setFloppy(float fcost)
         floppy_cost = fcost;
    public float getFloppy()
         return floppy_cost;
    public void setDVD(float dvdcost)
         dvd_cost = dvdcost;
    public float getDVD()
         return dvd_cost;
    public void setCdw(float cdrwcost)
         cdwriter_cost = cdrwcost;
    public float getCdw()
         return cdwriter_cost;
    //public String show()
    //     String out;
         //return out.format();
    public double Total()
         T = getProcessor() + getHarddisk() + getRam() + getProcessorSpeed() + getPrinter() + getWireless() + getFloppy() + getDVD() + getCdw();
         return T;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class WClass extends JFrame implements ActionListener
         Computer computer = new Computer();
         private JPanel P1;
         private JPanel P2;
         private JButton submit;
         private JButton clear;
         private JTextArea Out;
         private JLabel name;
         private JTextField Custname;
         private JComboBox processor;
         private JComboBox harddrive;
         private JRadioButton ram1;
         private JRadioButton ram2;
         private JRadioButton ram3;
         private JPanel radiopanel;
         private ButtonGroup radiogroup;
         private JComboBox processorsd;
         private JLabel L1;
         private JCheckBox printer;
         private JCheckBox lan;
         private JLabel L2;
         private JCheckBox fpy;
         private JCheckBox dvd;
         private JCheckBox cdrw;
         private JLabel L3;
         private JLabel L4;
         private JLabel L5;
         private JLabel L6;
         private JLabel L7;
         private JLabel L8;
         private JLabel L9;
         private Container c;
         int row;
         float prncost = 50f;
         float wlan = 110f;
         float fppy = 110f;
         float dvdw = 220f;
         float cdw = 20f;
         public WClass()
              super("Laptop Configuration");
              P1 = new JPanel();
              P1.setLayout(new GridLayout(10,2,5,10));
              P2 = new JPanel(new BorderLayout());
              name = new JLabel("Customer Name");
              P1.add(name);
              Custname = new JTextField(10);
              Custname.addActionListener(this);
              P1.add(Custname);
              L3 = new JLabel("Processor");
              P1.add(L3);
              String p[] = {"Pentium 4", "Celeron", "AMD", "Intel Centrino"};
              processor = new JComboBox(p);
              processor.setMaximumRowCount(3);
              P1.add(processor);
              L4 = new JLabel("Hard Disk");
              P1.add(L4);
              String h[] = {"30 GB", "40 GB", "60 GB"};
              harddrive = new JComboBox(h);
              harddrive.setMaximumRowCount(2);
              P1.add(harddrive);
              L5 = new JLabel("RAM");
              P1.add(L5);
              radiopanel = new JPanel();
              radiopanel.setLayout(new GridLayout(1,2));
              ram1 = new JRadioButton("256 MB", true);
              ram2 = new JRadioButton("512 MB", false);
              radiopanel.add(ram1);
              radiopanel.add(ram2);
              radiogroup = new ButtonGroup();
              radiogroup.add(ram1);
              radiogroup.add(ram2);
              P1.add(radiopanel);
              L6 = new JLabel("Processor Speed");
              P1.add(L6);
              String ps[] = {"1.8 GHz", "2.2 GHz", "2.8 GHz"};
              processorsd = new JComboBox(ps);
              processorsd.setMaximumRowCount(2);
              P1.add(processorsd);
              L1 = new JLabel("Additional Accessories");
              P1.add(L1);
              printer = new JCheckBox("Ink Jet Printer");
              lan = new JCheckBox("Inbuilt Wireless LAN");
              P1.add(printer);
              L7 = new JLabel("");
              P1.add(L7);
              P1.add(lan);
              L2 = new JLabel("Drives");
              P1.add(L2);
              fpy = new JCheckBox("Floppy(External)");
              dvd = new JCheckBox("DVD Writer");
              cdrw = new JCheckBox("CD Writer");
              P1.add(fpy);
              L8 = new JLabel("");
              P1.add(L8);
              P1.add(dvd);
              L9 = new JLabel("");
              P1.add(L9);
              P1.add(cdrw);
              c = getContentPane();
              add(P1, BorderLayout.NORTH);
              submit = new JButton("Submit");
              clear = new JButton("Clear");
              Out = new JTextArea(10,5);
              P2.add(submit, BorderLayout.WEST);
              P2.add(clear, BorderLayout.EAST);
              P2.add(Out,BorderLayout.CENTER);
              add(P2, BorderLayout.SOUTH);
         public void actionPerformed(ActionEvent event)
              if(event.getSource() == submit)
              computer.setName(name.getText());
              computer.setProcessor(processor.getSelectedIndex());
              computer.setHarddisk(harddrive.getSelectedIndex());
              //computer.setRam(radiogroup.getAccessibleContext());
              computer.setProcessorSpeed(processorsd.getSelectedIndex());
              if(printer.isSelected())
                   computer.setPrinter(prncost);
              if(lan.isSelected())
                   computer.setWireless(wlan);
              if(fpy.isSelected())
                   computer.setFloppy(fppy);
              if(dvd.isSelected())
                   computer.setDVD(dvdw);
              if(cdrw.isSelected())
                   computer.setCdw(cdw);
              Out.append("Computer Configuration for %s\n", computer.getName());
              Out.append("Processor:\t\t\t \n", computer.getProcessor());
              Out.append("HardDisk: \t\t\t \n", computer.getHarddisk());
              Out.append("RAM: \t\t\t \n", computer.getRam());
              Out.append("ProcessorSpeed:\t\t \n", computer.getProcessorSpeed());
              Out.append("Printer: \t\t\t \n", computer.getPrinter());
              Out.append("Inbuilt Wireless LAN: \t\t\n", computer.getWireless());
              Out.append("Floppy(External):\t\t \n", computer.getFloppy());
              Out.append("DVD Writer:\t\t\t \n", computer.getDVD());
              Out.append("CD Writer :\t\t\t \n", computer.getCdw());
              Out.append("Total \t\t\t \n", computer.getTotal());
              if(event.getSource() == clear)
                   Custname.setText("");
                   Out.setText("");
                   ram1 = new JRadioButton("256 MB", true);
                   c.setLayout(new GridLayout(10,2,5,10));
    import javax.swing.JFrame;
    public class Win
         public static void main(String args[])
              WClass window = new WClass();
              window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
              window.setSize( 500,550);
              window.setVisible( true);
    }

    When you make a class, the compiler often gives you an empty constructor. The Computer class for example would have the following constructor.
    public Computer(){ }This means you can write code, as you did in the third program like the following.
    Computer c = new Computer();However if you write your own constructor such as:
    public Computer(String Cname, int pcost, float tcost, int hcost, float rcost,
    int pscost, float prcost, float wcost, float fcost, float dvdcost, float cdrwcost)Then an empty constructor is not supplied. So you must write your own if you want one or you must use the one that you created.
    You can create as many constructors as you like, so long as they all take different arguments

  • 'operator + cannot be applied to double'

    public double getTotalPrice() {
            if (orderItems.size() == 0) {
                return 0.0;
            double total = 0.0;
            for (Iterator it = orderItems.iterator(); it.hasNext();) {
                OrderItem oi = (OrderItem) it.next();
                 total += (oi.getCost()).multiply(BigDecimal.valueOf(oi.getPurchaseQty()));
            return total;
    }ive got this method here and this part's got an error:
    total += (oi.getCost()).multiply(BigDecimal.valueOf(oi.getPurchaseQty()));Error: operator + cannot be applied to double, <any>
    any help is appreciated. thx

    What type does this return?
    (oi.getCost()).multiply(BigDecimal.valueOf(oi.getPurchaseQty()))At a glance, I'd guess BigDecimal. You can't use arithmetic operations like + on BigDecimal. You'd have to call its doubleValue method, or whatever there is that returns a double. Of course, since BigDecimal can hold numbers that double can't, that could give you bogus values, so you really need to make total a BigD as well, and call BigD's methods in place of +=, or else stick to numbers that fit in a double and don't use BigD at all.

  • Please help with cannot find symbol error. Been struggling all day :(

    Hi all. :)
    Writing a game for my phone with KToolbar and have been getting a cannot find symbol error for every variable and method I try to use across Classes. I've looked all over and though it seems a common problem I always either don't understand or can't get working the various solutions. Example of my errors:
    C:\...\BTK800i.java:197: cannot find symbol
    symbol : variable youSayWhat
    location: class HelloCanvas
              youSayWhat=key;
              ^
    If I try BTK800i.variable or BTK800i.message I get a new error.
    C:\...\src\BTK800i.java:184: non-static method newOrdersSarge() cannot be referenced from a static context
              BTK800i.newOrdersSarge();
              ^
    Both these errors apply to both variables and methods. It only happens when I'm using methods/variables of one class in another, am I using public and private incorrectly? It doesn't seem to make a difference if I make variables public or leave them private, I'm trying to get to them with a public method within a private class. Is it something else? I really have no idea. :(
    Here's my code, it's long enough to be a tiresome read so I've tried to skip what I know isn't relevant.
    public class BTK800i extends MIDlet {
         private Display myDisplay;
         private HelloCanvas myCanvas;
         public int youSayWhat;
            //a whole bunch more skipped here, but I'm fairly certain it's not anything that'll help find a solution
         public BTK800i() {
              paused=false;
    public void startApp() throws MIDletStateChangeException {
              if( paused ) {
                   myCanvas.repaint();
              else {
                   myDisplay=Display.getDisplay(this);
                   myCanvas=new HelloCanvas();
                   myDisplay.setCurrent(myCanvas);
                   myCanvas.setFullScreenMode(true);
                   youSayWhat=0;
                           //again with the skipping, more code not related
    public void newOrdersSarge() {
    //whole bunch of code
    //other methods skipped
    class HelloCanvas extends Canvas {
         public void keyPressed (int key) {
              youSayWhat=key;
              repaint ();
    //skippage
    }The stuff I skipped is mainly either more of the same sorta thing or maths/writing to screen stuff.
    Thanks alot to anyone who helps. I'm really struggling with this. :(
    Dan.

    But I have been reading them :(
    My next-door neighbour unfortunately is an 80-something married man, but I will go have a looksie about static and instances.
    I thought the point of public variables was that other classes could use them, is this wrong?
    Also does this mean that to use the variables from my BTK class in the HelloCanvas class I need to first instantiate BTK? I don't understand how that works as the code starts running from the BTK class in the first place :S I guess more reading will help with this.
    Thanks very much for replying. :)
    Edit:
    OK I have read up on it but I don't think I found anything I hadn't read before. I tried to make a new class which I could instantiate to hold all the variables and methods I wanted everything to be able to access, but that went disastrously. Am I right in understanding that there are no global variables in Java? :s
    Edited by: Dan69 on Apr 17, 2010 1:15 PM

Maybe you are looking for

  • How to avoid the long time consuming process of settlement on periodic basi

    For investment Project(purpose of capitalisation) related expenses We would like to show it  Directly in Balance Sheet rather than P/L  A/C.Whether it is feasible or not?as per one of consultant it will be first hit the p/L and after settlement it wi

  • HTC Touch 2 Alarm

    Hi All, new to this forum but seen some really neat ideas I can go play with. My question is the alarm on my phone. When I set it the alarm and switch the phone off it doesn't switch or wake up the phone and hence me!!  I have to leave the it on all

  • Completely appalled by Adobe

    I have worked for a year to develop an app and published it to the Apple Store using InDesign and DPS.  This week I created alternate layouts for Android.  I have everything set up to publish to Google Play.  When I went to publish it using DPS I fou

  • Importing lookup values for Z tables thru FTP connections running MDMGX

    When executing MDMGX and importing into lookup tables of MDM thru FTP connection on MDM Server it is working fine with defined tables, But when we want to get the data into Z tables thru FTP connection on MDMserver executing MDMGX,how is it possible

  • Problems saving survey values

    Hello, I have problems with surveys. I want modify the values of a survey from a customer program. If the survey has been saved on-line before from the corresponding transaction, I have no problem. But If it hasn't been saved, I can't do the changes.