Manisha Singh Sanoo
Manisha Singh Sanoo

Reputation: 929

Why am i getting error for .format? JAVA FILES

I am reading text from a file then creating another file containing those texts but when i'm calling the function .format no matter what i do it keeps being underlined. Here's my codes:

package number3;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;

public class ReadFileCarData {

private static Scanner Infile;
private static Formatter OutFile;

public static void main(String[] args) throws FileNotFoundException{

    try
    {
        Infile = new Scanner(new File("cardata.txt"));
        OutFile = new Formatter("cardatasold.txt");
    }

    catch(FileNotFoundException fnfe)
    {
        System.out.println("File not found");
        System.exit(0);
    }

    System.out.println("Plate Brand Model Price Power Status");

    while(Infile.hasNext())
    {
        String plate,brand,model,status;
        int price,power;

        plate = Infile.next();
        brand = Infile.next();
        model = Infile.next();
        price = Infile.nextInt();
        power = Infile.nextInt();
        status = Infile.next();

        while(status.equals("Sold"))
        {
            try
            {
                OutFile.format("%s %s %s %d %d \r\n",plate,brand,model,price,power);
            }
            catch(Exception e)
            {
                System.out.print("Error");
            }

        }
    }

    Infile.close();
    OutFile.close();
}

}

The error message says:

The method format(Locale, String, Object[]) in the type Formatter is not applicable for the arguments (String, String, String, String, int, int)

I can't understand why because according to me I've written the correct format. Any idea what i'm doing wrong? Thanks.

Upvotes: 0

Views: 956

Answers (2)

CMPS
CMPS

Reputation: 7769

It works fine for me. That's the output:

Plate Brand Model Price Power Status

The problem you're having is that your compiler does not recognize the var-args on the method (and thinks it's just a Object[]) and probably doesn't even autobox the integers. Both of these are features of Java 1.5.

This probably means that your IDE/compiler is set up wrong. Open your project's settings and look for target compatibility, generated .class compatibility, or something similar, and switch it from 1.4 to 1.7/1.8.

Upvotes: 3

kucing_terbang
kucing_terbang

Reputation: 5131

You might want to check your Java version.
meanwhile, you could try to use this function.

OutFile.format(Locale.getDefault(),"%s %s %s %d %d \r\n", new Object[]{plate,brand,model,price,power});

hope it helps ;)

Upvotes: 1

Related Questions