Index 0 out of bounds for length 0 zona ошибка

Here i am getting this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 public static void main(String[] args) { Scanner

Here i am getting this error:
Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

public static void main(String[] args) {
    Scanner keyboard  = new Scanner(System.in);
    String input = keyboard.nextLine();
    System.out.println(input);
    while(true){
        if(args[0].equals("k")){
            System.out.println("k");
        }
    }
}

asked Jun 28, 2020 at 5:30

Karthik Putchala's user avatar

4

You need run the code on cmd as java MyProgram abc xyz then args will contain [«abc», «xyz»].Maybe you are not doing that right now and therefore getting the error.

answered Jun 28, 2020 at 5:51

Sanjanah's user avatar

You need to provide Command Line Arguments like so:

java MyClass k foo bar

These arguments are passed to the array args[] which will then contain {"k", "foo", "bar"}

Therefore args.length will be 3 and args[0] will be k

answered Jun 28, 2020 at 5:51

Ishan Goel's user avatar

Ishan GoelIshan Goel

781 silver badge7 bronze badges

If you are executing through IDE and not setting arguments OR not passing command line arguments while running through cmd, you’ll get this error.

But for this program, even if you pass arguments, it will run in infinite loop probably as while condition is always true.

answered Jun 28, 2020 at 6:05

Aniruddha Sardar's user avatar

You are executing this java class without arguments. In that case, args[0] does now exist, and thus the Exception with Error message.

You can modify the if in this form:

if(args[0].equals("k") && args.length > 0 )

so you do not get exception with message

Index 0 out of bounds for length 0

Your program is producing output without error, when Running the program with argument «k» produces the infinite look of printing k. For this you need to run command the java printKjavaFile k , or start it from IDE with this argument.

answered Nov 19, 2020 at 20:01

zhrist's user avatar

zhristzhrist

8977 silver badges24 bronze badges

You are doing 2 things at the same time:

  • ask for user input via stdin, when the program is running already
  • parsing the args[], which should be given when the program starts to run

and expect they work together. But they are different.

I suppose you run the app like: java MyClass without adding extra args after this. You can:

  • provide arg k after java MyClass, so args[] becomes a non-empty array
  • stop trying to use args, but just focus on input, which is the line you read from user input.

answered Oct 13, 2021 at 9:09

WesternGun's user avatar

WesternGunWesternGun

10.4k3 gold badges83 silver badges139 bronze badges

Не часто, но иногда все же случается неприятная ситуация, когда Zona не может подключиться к серверу с каталогом и вместо списка фильмов показывает ошибку доступа. Ниже собраны 5 рекомендаций, которые помогут вам исправить ошибку самостоятельно.

Совет 1

Возможно, на сервере разработчика в данный момент проводятся технические работы. В Zona не выводятся оповещения о запланированных отключениях каталога от сети, поэтому рекомендуем при возникновении проблемы отписаться в комментариях внизу этой страницы. Если и другие пользователи сообщат о неработающем подключении к серверу — значит разработчики точно что-то намудрили и нужно просто подождать, когда ошибка исчезнет сама собой.

Совет 2

Если ждать нет сил и желания, проверьте, не начал ли антивирус блокировать Зоне доступ в сеть. Временно приостановите работу антивируса (в Avast, например, для этого достаточно кликнуть по иконке в системном лотке Windows и выбрать команду «приостановить все экраны на 1 час»), и заодно отключите брандмауэр Windows.

Инструкция как отключить брандмауэр в Windows 10

Откройте Пуск и наберите на клавиатуре слово «бранд». Кликните по иконке в виде кирпичной стены из списка лучшего соответствия в результатах поиска (см. скриншот ниже).

Запуск брандмауэра

В окне управления на левой панели кликните на ссылку «Включение и отключение брандмауэра     Windows». 

Включение и отключение брандмауэра

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

отключите брандмауэра

Следующее окно не закрывайте, оно еще пригодится.

Теперь перезапустите Zona и проверьте, исчезла ли ошибка доступа к серверу.

Если исчезла, включите брандмауэр в том же окне, которые я просил не закрывать и проверьте снова. Если после этого Zona перестанет подключаться к серверу, значит это брандмауэр ее блокирует.

Кликните на кнопку «Разрешение взаимодействия с приложением или компонентом…», затем найдите Zona в списке программ и проставьте галочки в столбцах частной и публичной сети.

Добавляем Zona в исключения брандмауэра

Добавляем Zona в исключения брандмауэра

Если оказалось, что брандмауэр не причем, и программа работает, после его включения, значит виноват антивирус.

Внесите Zona в исключения вашего антивируса. Если на компьютере установлен Avast, Касперский, Nod32 или Dr.Web, посмотрите их справку — там есть инструкция, как это сделать.

Совет 3

Если после отключения брандмауэра и антивируса Zona все равно выдает ошибку доступа к серверу, возможно некоторые файлы программы в папке «Program Files» или в реестре Windows были повреждены.

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

Можете проверить инсталлятор перед установкой на сервисе virustotal.com, к примеру, чтобы убедиться в его безопасности.

После переустановки, проверьте, исчезла ли ошибка доступа к серверу. Если исчезла, добавьте папку с установленными файлами Zona и саму программу в исключения брандмауэра и антивируса, и только после этого запускайте их.

Совет 4

На компьютерных форумах некоторым пользователям решить проблему помогла смена способа подключения к интернету с беспроводного на проводной. Если ваш компьютер подключен к роутеру через wi-fi, подключитесь к нему через провод, хотя бы для проверки.

Совет 5

Запустите диагностику сетевого подключения — кликните на значок сети в системном лотке Windows правой кнопкой мыши и в открывшемся меню нажмите ссылку «Диагностика неполадок».

диагностика сетевого подключения

В открывшемся окне выберите тип проблем с сетью. Кликните на надпись «У меня другая проблема», и затем на «Использование конкретного сетевого адаптера…».

У меня другая проблема

Использование конкретного сетевого адаптера

Следуйте подсказкам мастера устранения неисправностей. Если будет предложено выполнить сброс адаптера — выполните его.

Запустите Zona и проверьте, исчезла ли ошибка доступа к серверу.

Знаете еще один способ решения проблемы? Опишите его в форме комментариев ниже, помогите другим пользователям.

Quote:

Thanks, now I don’t have that problem anymore.
But instead of printing the array it prints gibberish : [I@2f92e0f4.
now I need to solve this problem, if you could help me with that I will appreciate it a lot :).

Compiling successfully does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language — English, rather than German for example — not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it’s the fourth or fifth, but you’ll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it’s doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:

Input   Expected output    Actual output
  1            2                 1
  2            4                 4
  3            6                 9
  4            8                16

Then it’s fairly obvious that the problem is with the bit which doubles it — it’s not adding itself to itself, or multiplying it by 2, it’s multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it’s obvious that it’s somewhere here:

int Double(int value)
   {
   return value * value;
   }

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called «single stepping») and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the «Step over» button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it’s one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Https dbo centrinvest ru sbns web ru html login html error timeout
  • Http error code 407
  • Http error code 405
  • Inbound authentication failed with error logondenied for receive connector default
  • Http error code 400

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии