Error parsing file arguments

Почему- то не работает вот эта команда $ jar cf ./target/{project-name}.jar -C ./target/classes . Вылетала с ошибкой "Error parsing file arguments" Однако уб... [20181]

Артем Соломатин

Почему- то не работает вот эта команда $ jar cf ./target/{project-name}.jar -C ./target/classes .
Вылетала с ошибкой «Error parsing file arguments»
Однако убрав ключ -С, jar файл без каких либо проблем создался


5


0

Артем Соломатин

Однако столкнулся с другой проблемой…
enter image description here

Если это нужно, то сам jar выглядит так
enter image description here

А Makefile вот так:
enter image description here


0

Vyacheslav Lapin

Так… На всякий случай, документация на утилиту jar: https://docs.oracle.com/javase/8/docs/technotes/tools/unix/jar.html

Ключ «-C dir» указывает команде, откуда брать файлы для того, что бы положить их в «Casino.jar», т.е. следующий аргумент за ключём «-С» — это параметр для ключа -С, а тем, что Вы убрали этот ключ, вы превратили следующее значение (./target/classes) в нечто иное, что явно будет интерпретировано неадекватно.

Кроме того, после ключа «-C ./target/classes», который, напомню, указывает папку, в которой нужно искать файлы для упаковки, в команде должен быть перечислен список файлов, которые нужно будет добавить из этой папки в результирующий jar. А т.к. нам нужны из этой папки все файлы, нужно просто указать символ «.»

В общем, в Вашем случае, правильная команда должна выглядеть вот так:

jar cf ./target/Casino.jar -C ./target/classes .

P.S. Вы не могли случайно написать «-С» в русской раскладке? С этим символом вечно проблемы у русскоязычной аудитории, поскольку он мало того, что выглядит одинаково, так ещё и располагается на одной и той же клавише, так что очень легко не заметить, что напечатал не тот символ, а кодируется он совершенно по-разному…


0

Vyacheslav Lapin

Пакет (в Вашем случае «games») должен соответствовать папкам, ведущим к файлу от корня. По прикреплённой картинке я вижу, что в корне получившегося у Вас jar’ника лежит не папка пакета («games»), а папка «target», что естественно приводит к тому, что класс games.Slot он обнаружить не может. Это результат того, что Вы убрали ключ «-С».


0

Артем Соломатин

Разобрался… Проблемы были из-за того, что я точку в конце не ставил… Спасибо большое за развернутый ответ!


0

Vyacheslav Lapin

На здоровье! :))


0

Testing the same command on OctoPi:

(oprint)pi@octopi:~/OctoPrint $ octoprint --help
Usage: octoprint [OPTIONS] COMMAND [ARGS]...

Options:
  -b, --basedir PATH  Specify the basedir to use for uploads, timelapses etc.
  -c, --config PATH   Specify the config file to use.
  -v, --verbose       Increase logging verbosity
  --safe              Enable safe mode; disables all third party plugins
  --version           Show the version and exit.
  --help              Show this message and exit.

Commands:
  client   Basic API client.
  config   Basic config manipulation.
  daemon   Starts, stops or restarts in daemon mode.
  dev      Additional commands for development tasks.
  plugins  Additional commands provided by plugins.
  serve    Starts the OctoPrint server.

Same behaviour on any other checkout, regardless of OS.

Also tried a replication of your exact checkout & install steps. Differences being: no docker, virtual environment:

$ git clone -b 1.3.0 https://github.com/foosel/OctoPrint.git OctoPrint-1.3.0-Test && cd OctoPrint-1.3.0-Test && virtualenv venv && source ./venv/bin/activate && python setup.py install
[...]
$ octoprint --help
Usage: octoprint [OPTIONS] COMMAND [ARGS]...

Options:
  -b, --basedir PATH  Specify the basedir to use for uploads, timelapses etc.
  -c, --config PATH   Specify the config file to use.
  -v, --verbose       Increase logging verbosity
  --safe              Enable safe mode; disables all third party plugins
  --version           Show the version and exit.
  --help              Show this message and exit.

Commands:
  client   Basic API client.
  config   Basic config manipulation.
  daemon   Starts, stops or restarts in daemon mode.
  dev      Additional commands for development tasks.
  plugins  Additional commands provided by plugins.
  serve    Starts the OctoPrint server.

The error sounds like something seriously messed up the command line arguments here.

Now, I have to admit that I’m completely unfamiliar with Docker, and especially how it works internally, but could it be that it’s doing something in its environmental setup or they way the actual executable gets called that’s messing with things here?

I played around a bit with things and finally could reproduce the exact error message:

$ OCTOPRINT_VERSION=1.3.0 octoprint --help
Usage: octoprint [OPTIONS] COMMAND [ARGS]...

Error: Invalid value for "--version": 1.3.0 is not a valid boolean

Could it be that such an environment variable is set by Docker, causing the issues here? Should be easy enough to check with CMD ["env"] if I understand things right. If so, that would be the reason. Click (which is what I use for argument parsing) here is set up to also take arguments from the environment, prefixed with OCTOPRINT_. Apparently it also does that for the flag-parameter version (which I’ll have to see if I can prevent that from happening), causing this issue. The question though would be via such an environment variable would even be set in the container in the first place.

  1. July 20th, 2011, 03:45 PM


    #1

    gerry123 is offline


    Junior Member


    Default HELP Error Parsing File

    Hi there I have a few error messages coming up with my code, if someone could point me in the right direction

    regards

    gerry

    package supermarketproject;
     
    public class LinkedQueue<T> implements QueueADT<T>
    {
       private int count;
       private LinearNode<T> front, rear;
     
       /**
        * Creates an empty queue.
        */
       public LinkedQueue()
       {
          count = 0;
          front = rear = null;
       }
     
        public boolean isEmpty( ) {
            return front == null;
        }
     /**
        * Adds the specified element to the rear of this queue.
        *
        * @param element  the element to be added to the rear of this queue
        */
       public void enqueue (T element)
       {
          LinearNode<T> node = new LinearNode<T>(element);
     
          if (isEmpty())
             front = node;
          else
             rear.setNext (node);
     
          rear = node;
          count++;
       }
     
       public T dequeue() throws EmptyCollectionException
       {
          if (isEmpty())
             throw new EmptyCollectionException ("queue");
     
          T result = front.getElement();
          front = front.getNext();
          count--;
     
          if (isEmpty())
             rear = null;
     
          return result;
       }
     
       /**
        * Sets up this exception with an appropriate message.
        */
     public ElementNotFoundException (String collection)
       {
          super ("The target element is not in this " + collection);
       }
    }
    /**
     * EmptyCollectionException represents the situation in which a collection
     * is empty.
     */
     
    public class EmptyCollectionException extends RuntimeException
    {
       /**
        * Sets up this exception with an appropriate message.
        */
       public EmptyCollectionException (String collection)
       {
          super ("The " + collection + " is empty.");
       }
    }
    }

    Last edited by gerry123; July 20th, 2011 at 04:14 PM.


  2. Default Related threads:


  3. July 20th, 2011, 04:07 PM


    #2

    Default Re: HELP Error Parsing File

    I have a few error messages

    Sorry, I don’t see your error messages???

    Please edit your code and wrap it in code tags. See:BB Code List — Java Programming Forums


  4. July 20th, 2011, 04:15 PM


    #3

    gerry123 is offline


    Junior Member


    Default Re: HELP Error Parsing File

    Quote Originally Posted by Norm
    View Post

    As you can see i have put the code in question in bold

    regards

    gerry


  5. July 20th, 2011, 04:28 PM


    #4

    Default Re: HELP Error Parsing File

    Can you explain what the problem is with that code?

    You said:

    I have a few error messages coming up with my code

    Please copy and paste the full text of those error messages here.


  6. July 20th, 2011, 05:04 PM


    #5

    gerry123 is offline


    Junior Member


    Default Re: HELP Error Parsing File

    i have underlined the error messages in question

    regards

    gerry

    public ElementNotFoundException (String collection)

    invalid method declaration; return type required{
    super («The target element is not in this » + collection); constructor Object in java.lang.Object cannot be applied to given types; required: no arguments, found: java.lang.String, reason: actual and formal argument lists different in length. call to super must be first statement in constructor}
    }
    /**
    * EmptyCollectionException represents the situation in which a collection
    * is empty.
    */

    public class EmptyCollectionException extends RuntimeException

    classEmptyCollectionException is public, should be declared in a file named EmptyCollectionException.java
    {
    /**
    * Sets up this exception with an appropriate message.
    */
    public EmptyCollectionException (String collection)
    {
    super («The » + collection + » is empty.»);
    }
    }
    } class, interface, or enum expected


  7. July 20th, 2011, 05:13 PM


    #6

    Default Re: HELP Error Parsing File

    That is a very confusing post. Why are the error messages mixed in with the source code?

    public ElementNotFoundException (String collection) invalid method declaration; return type required

    The code looks like a constructor (no return type) but the compiler thinks it is a method definition.
    Check the placement of the code.
    Which is it? A method or a constructor? Where is the class statement for it?

    public class EmptyCollectionException extends RuntimeException classEmptyCollectionException is public, should be declared in a file named EmptyCollectionException.java

    That message is self explanatory. Move the class to its own named file.


  8. July 20th, 2011, 05:24 PM


    #7

    gerry123 is offline


    Junior Member


    Default Re: HELP Error Parsing File

    the error messages are not mixed in with the source code, i typed the underlined text out manually to show u what the errors were

    regards


  9. July 20th, 2011, 05:28 PM


    #8

    Default Re: HELP Error Parsing File

    It be better to just post the error messages without any editing.

    Or to leave a blank line between the source and the error message.


  10. July 21st, 2011, 03:30 AM


    #9

    Default Re: HELP Error Parsing File

    I must say this thread is rather confusing.

    gerry123, the code or highlight tags are used to keep the code neat and add syntax highlighting which both make it easier to read.

    You also need to post all your code and give us something we can attempt to compile.

    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.


  11. July 21st, 2011, 11:57 AM


    #10

    gerry123 is offline


    Junior Member


    Default Re: HELP Error Parsing File

    package supermarketproject;
     
    public class LinkedQueue<T> implements QueueADT<T>
    {
       private int count;
       private LinearNode<T> front, rear;
     
       /**
        * Creates an empty queue.
        */
       public LinkedQueue()
       {
          count = 0;
          front = rear = null;
       }
     
        public boolean isEmpty( ) {
            return front == null;
        }
     /**
        * Adds the specified element to the rear of this queue.
        *
        * @param element  the element to be added to the rear of this queue
        */
       public void enqueue (T element)
       {
          LinearNode<T> node = new LinearNode<T>(element);
     
          if (isEmpty())
             front = node;
          else
             rear.setNext (node);
     
          rear = node;
          count++;
       }
     
       public T dequeue() throws EmptyCollectionException
       {
          if (isEmpty())
             throw new EmptyCollectionException ("queue");
     
          T result = front.getElement();
          front = front.getNext();
          count--;
     
          if (isEmpty())
             rear = null;
     
          return result;
       }
     
       /**
        * Sets up this exception with an appropriate message.
        */
     
    public ElementNotFoundException (String collection)
       {
          super ("The target element is not in this " + collection);
       }
    }

    below is where the errors are within the code, what exactly am i missing in this code?

    /**
     * EmptyCollectionException represents the situation in which a collection
     * is empty.
     */
     
    public class EmptyCollectionException extends RuntimeException
    {
       /**
        * Sets up this exception with an appropriate message.
        */
       public EmptyCollectionException (String collection)
       {
          super ("The " + collection + " is empty.");
       }
    }
    }

    Last edited by JavaPF; July 21st, 2011 at 01:53 PM.

    Reason: added highlight tags.


  12. July 21st, 2011, 12:33 PM


    #11

    Default Re: HELP Error Parsing File

    Please copy and paste here the full text of the error messages.
    Not too many of us are compilers. We need the errors from the compiler to be able to tell you what the compiler sees is wrong with your code.

    Did you read post#6?

    Please edit your code and wrap it in code tags. Use Go Advanced, select your code and press the # icon above the input box.


  13. July 21st, 2011, 01:20 PM


    #12

    gerry123 is offline


    Junior Member


    Default Re: HELP Error Parsing File

    Quote Originally Posted by Norm
    View Post

    Please copy and paste here the full text of the error messages.
    Not too many of us are compilers. We need the errors from the compiler to be able to tell you what the compiler sees is wrong with your code.

    Did you read post#6?

    Please edit your code and wrap it in code tags. Use Go Advanced, select your code and press the # icon above the input box.

    All it says is as follows «error parsing file»


  14. July 21st, 2011, 01:36 PM


    #13

    Default Re: HELP Error Parsing File

    What is the «it»?
    Can you get to a javac compiler?
    Use that to get error messages with some meaning.


  15. July 21st, 2011, 01:54 PM


    #14

    gerry123 is offline


    Junior Member


    Default Re: HELP Error Parsing File

    im using netbeans they dont clearly define error messages, what is a javac compliler?


  16. July 21st, 2011, 02:01 PM


    #15

    Default Re: HELP Error Parsing File

    The javac compiler is the one installed with the JDK from Oracle.


  17. July 21st, 2011, 02:18 PM


    #16


  18. July 21st, 2011, 02:22 PM


    #17

    Default Re: HELP Error Parsing File

    I don’t use a proper IDE. I have an enhanced editor — syntax hilighting and multiple projects each with commandlines


  19. July 21st, 2011, 02:23 PM


    #18

    gerry123 is offline


    Junior Member


    Default Re: HELP Error Parsing File

    Quote Originally Posted by Norm
    View Post

    The javac compiler is the one installed with the JDK from Oracle.

    after running the file i got the following message;

    run:
    Exception in thread «main» java.lang.ExceptionInInitializerError
    at supermarketproject.SuperMarketSimulator.main(Super MarketSimulator.java:23)
    Caused by: java.lang.RuntimeException: Uncompilable source code — cannot find symbol
    symbol: class QueueADT
    at supermarketproject.LinkedQueue.<clinit>(LinkedQueu e.java:7)
    … 1 more
    Java Result: 1
    BUILD SUCCESSFUL (total time: 2 seconds)


  20. July 21st, 2011, 02:26 PM


    #19

    Default Re: HELP Error Parsing File

    Where is QueueADT defined?

    after running the file i got the following message;

    IDEs are magic. This source won’t compile. There is no way to execute it.
    How can you «run» it?


  21. July 23rd, 2011, 04:18 PM


    #20

    dlorde is offline


    Forum old-timer


    Default Re: HELP Error Parsing File

    I can see where one error comes from — at the bottom of your LinkedQueue class, there is a method defined that doesn’t have a return value specified, so it looks like a constructor, but it isn’t a constructor. See under ‘Sets up this exception with an appropriate message.’

    ETA — I notice Norm pointed this out very early on in the thread…

    Last edited by dlorde; July 24th, 2011 at 07:01 PM.


Время прочтения
6 мин

Просмотры 87K

Если вы занимаетесь обработкой и анализом данных с использованием Python, то вам, рано или поздно, придётся выйти за пределы Jupyter Notebook, преобразовав свой код в скрипты, которые можно запускать средствами командной строки. Здесь вам и пригодится модуль argparse. Для новичков, привыкших к Jupyter Notebook, такой шаг означает необходимость покинуть зону комфорта и перейти в новую среду. Материал, перевод которого мы публикуем сегодня, написан для того, чтобы облегчить подобный переход.

Модуль argparse

Модуль argparse

Модуль argparse можно сравнить с силами природы, которые воздвигли горные пики, возвышающиеся над облаками. Благодаря этому модулю в скриптах становится возможным работа с тем, что, без его использования, было бы скрыто от кода этих скриптов.

Надо отметить, что argparse является рекомендуемым к использованию модулем стандартной библиотеки Python, предназначенным для работы с аргументами командной строки. Мне не удалось найти хорошее руководство по argparse для начинающих, поэтому я и решил написать такое руководство сам.

Жизнь за пределами Jupyter Notebook

Когда я впервые столкнулся с argparse в Python-скрипте, который нужен был мне для проекта, которым я занимался в свободное время, я подумал: «А это что ещё за таинственная конструкция?». После этого я быстро перенёс код в Jupyter Notebook, но такой ход оказался нерациональным.

Мне нужно было, чтобы у меня была возможность просто запустить скрипт, а не работать с ним средствами Jupyter Notebook. Автономным скриптом, в котором использовался модуль argparse, было бы гораздо легче пользоваться, работать над ним было бы проще, чем полагаясь на возможности Jupyter Notebook. Однако тогда я спешил, и, когда взглянул на документацию по argparse, не смог сходу ухватить её суть, поэтому и не стал пользоваться исходной версией скрипта.

С тех пор я разобрался с argparse и этот модуль мне очень понравился. Теперь я считаю его прямо-таки жизненно необходимым. При этом освоить его не так уж и сложно.

Зачем нужен модуль argparse?

Модуль argparse позволяет разбирать аргументы, передаваемые скрипту при его запуске из командной строки, и даёт возможность пользоваться этими аргументами в скрипте. То есть речь идёт о том, что этот модуль позволяет предоставлять скрипту некие данные в момент его запуска, а этими данными скрипт сможет воспользоваться во время выполнения его кода. Модуль argparse — это средство, с помощью которого можно наладить общение между автором программы и тем, кто ей пользуется, например — между вами, когда вы сегодня пишете скрипт, и вами же, когда вы завтра его запускаете, что-то ему передавая.

Использование argparse означает, что, при необходимости изменить поведение скрипта или при необходимости передачи ему неких данных, если это предусмотрено автором скрипта, пользователю не нужно редактировать программный код. В результате скрипты обретают определённый уровень гибкости.

Пример

Предположим, вы хотите написать скрипт для преобразования видеофайлов в обычные изображения с использованием библиотеки OpenCV. Для того чтобы скрипт мог бы решить эту задачу, ему нужно знать место, где хранятся видеофайлы, и место, в которое нужно поместить готовые изображения. То есть, ему требуются сведения о двух папках, пути к которым, что не очень удобно, можно жёстко задать в коде скрипта, или, что уже куда лучше, можно позволить задавать пользователю скрипта, вводя их в качестве аргументов командной строки при запуске скрипта. Для того чтобы оснастить скрипт такой возможностью, нам и пригодится модуль argparse. Вот как может выглядеть раздел скрипта (назовём этот скрипт videos.py), в котором осуществляется разбор аргументов командной строки:

# videos.py
import argparse
parser = argparse.ArgumentParser(description='Videos to images')
parser.add_argument('indir', type=str, help='Input dir for videos')
parser.add_argument('outdir', type=str, help='Output dir for image')
args = parser.parse_args()
print(args.indir)

Здесь, в начале файла, импортируется модуль argparse. Затем, с использованием конструкции argparse.ArgumentParser(), создаётся объект parser с указанием его описания. Далее, с помощью метода parser.add_argument(), описывается переменная indir, в которую планируется записать путь к папке с видеофайлами. При этом указывается то, что она имеет строковой тип, а также задаётся справочная информация о ней. После этого, точно так же, создаётся переменная outdir, в которую попадёт путь к папке, в которую скрипт должен будет поместить изображения, созданные на основе видеофайлов. На следующем шаге работы в переменную args попадает результат разбора аргументов командной строки. То, что передано скрипту при запуске, теперь будет доступно в виде свойств indir и outdir объекта args. Теперь с этими значениями можно работать. В данном случае мы просто выводим в консоль то, что передано скрипту в аргументе indir.

Вот как запустить этот скрипт из командной строки:

python videos.py /videos /images

Обратите внимание на то, что строки /videos и /images не нужно заключать в кавычки. Скрипт, запущенный таким образом, выведет в терминал строку /videos, чем подтвердит возможность использования переданных ему аргументов в своём коде. Это — магия argparse в действии.

Магия разбора аргументов командной строки

Подробности об argparse

Только что мы рассмотрели простой пример работы с argparse. Теперь давайте обсудим некоторые подробности, касающиеся argparse.

▍Позиционные аргументы

Конструкция вида parser.add_argument('indir', type=str, help='Input dir for videos') из скрипта videos.py предназначена для создания позиционного аргумента (positional argument). При вызове скрипта важен порядок указания таких аргументов. Так, первый аргумент, переданный скрипту, становится первым позиционным аргументом, второй аргумент — вторым позиционным аргументом.

Что произойдёт в том случае, если скрипт запустить вообще без аргументов, выполнив в терминале команду python videos.py?

В таком случае будет выведено сообщение об ошибке следующего вида:

videos.py: error: the following arguments are required: indir, outdir

В результате оказывается, что для того, чтобы запустить скрипт, в котором предусмотрено использование позиционных аргументов, такие аргументы всегда нужно указывать при его запуске.

▍Необязательные аргументы

Что произойдёт при запуске нашего скрипта командой python videos.py --help?

В ответ будет выведена справочная информация о нём. Это — именно те сведения о позиционных аргументах, которые мы указывали при описании соответствующих переменных:

usage: videos.py [-h] indir outdir

Videos to images

positional arguments:
  indir       Input dir for videos
  outdir      Output dir for image

optional arguments:
  -h, --help  show this help message and exit

Скрипт сообщил нам много интересного о том, чего он ждёт от пользователя, а help — это пример необязательного аргумента (optional argument). Обратите внимание на то, что --help (или -h) — это единственный стандартный необязательный аргумент, которым мы можем пользоваться при работе с argparse, но, если вам нужны и другие необязательные аргументы, их можно создавать и самостоятельно.

Необязательные аргументы создают так же, как и позиционные. Основная разница между командами их создания заключается в том, что при указании имён таких аргументов эти имена начинаются с последовательности символов --, или, для кратких форм аргументов, с символа -. Например, необязательный аргумент можно создать так:

parser.add_argument('-m', '--my_optional')

Вот пример того, как создавать и использовать необязательные аргументы. Обратите внимание на то, что мы, описывая здесь необязательный аргумент, указали его тип как int. То есть он представляет собой целое число. В подобной ситуации можно использовать и другие типы Python.

# my_example.py
import argparse
parser = argparse.ArgumentParser(description='My example explanation')
parser.add_argument(
    '--my_optional',
    type=int,
    default=2,
    help='provide an integer (default: 2)'
)
my_namespace = parser.parse_args()
print(my_namespace.my_optional)

Аргумент, описанный как --my_optional, доступен в программе в виде свойства объекта my_namespace с именем my_optional.

Необязательным аргументам можно назначать значения, которые они будут иметь по умолчанию. В нашем случае, если при вызове скрипта аргументу my_example не будет задано никакого значения, в него будет записано число 2, которое и будет выведено в консоль. Для того чтобы задать значение этого аргумента во время запуска скрипта можно воспользоваться такой конструкцией:

python my_example.py  --my_optional=3

Для чего ещё можно использовать argparse?

Модуль argparse можно использовать при разработке Python-приложений, которые планируется упаковывать в контейнеры Docker. Так, например, если при запуске приложения, упакованного в контейнер, ему нужно передать аргументы командной строки, то описать это, на этапе сборки контейнера, можно в Dockerfile с помощью инструкции RUN. Для запуска скриптов во время выполнения контейнера можно пользоваться инструкциями CMD или ENTRYPOINT. Подробности о файлах Dockerfile вы можете найти здесь.

Итоги

Мы рассмотрели базовые способы работы с модулем argparse, используя которые, вы можете оснастить свои скрипты возможностью принимать и обрабатывать аргументы командной строки. При этом надо отметить, что возможности argparse на этом не заканчиваются. Например, использование при описании аргументов параметра nargs позволяет работать со списками аргументов, а параметр choices позволяет задавать наборы значений, которые могут принимать аргументы. На самом деле, теперь, освоив основные возможности argparse, вы, без особых сложностей, сможете изучить этот модуль более глубоко, используя документацию к нему.

Если вы привыкли работать с Jupyter Notebook и хотите отойти от этой практики, то вот и вот — материалы по работе с переменными окружениями. Вот материал, посвящённый средству, repo2docker, позволяющему преобразовывать репозитории Jupyter Notebook в образы Docker.

Уважаемые читатели! Как вы работаете с аргументами командной строки в Python-скриптах?

Avatar of pbenito

pbenito

 asked on 1/26/2009

Hi,
  I have a NetBeans 6.5 Java project and one of my .java files always has a red exclamation point next to it and shows the error: «Error Parsing File».

   The problem is the project builds and runs successfully, and when you open up the .java file that is showing the error, the IDE does not highlight any errors.

   Does anyone know how to fix this?

Thanks

Editors IDEsJava

Avatar of undefined

check your file for special/control characters

What type of characters are in that category?

anything thats not ascii

I just checked — everything is ascii.  Any other suggestions?

try creating a new file, and copy/paste file into new one.

Tried that — still doesn’t work.

Let me add more — the new file with a name, doesn’t have the error.  When I rename that to the file with the original name, the error comes back.

whats the file name, and class name (they need to be the same)

Sure — I’ve made sure that the filename and class name are always the same.

> When I rename that to the file with the original name, the error comes back.

What was the name before?

So say the problem file was originally called Salesrecord.java, I created a new file called Sales.java and copied and pasted the contents of Salesrecord.java into Sales.java.  I then deleted Salesrecord.java and renamed Sales.java to Salesrecord.java.

Hope this clarifies a bit better.

If thats the case then I don’t see how it compiled when it was Sales.java as the name was wrong

It didn’t — i deleted Salesrecord.java immediatley and renamed Sales.java to Salesrecord.java and then recompiled.

After I did that, I still get the error «Error Parsing File» next to the file in the Project explorer, but when I open the file there are no errors and the program compiles and runs normally.

weird. sorry can’t think what the cause is.
I don’t use Netbeans, don’t really like it.

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.

View this solution by signing up for a free trial.

Members can start a

7-Day free trial

and enjoy unlimited access to the platform.

Понравилась статья? Поделить с друзьями:
  • Error parsing error unexpected token vue
  • Error parsing error missing semicolon
  • Error parsing error cannot find module babel eslint
  • Error parsing condition with key 0 modx
  • Error parsing attribute name 1c розница