Java lang illegalargumentexception bound must be positive

IllegalArgumentException: Bound must be positive

The issue is that you are calling Random.nextInt() with a zero and it doesn’t like that. That is happening because the List from getAllItems() is empty. I would prevent this situation by checking that the list has items before performing your logic:

List items = getAllItems(level); if(!items.isEmpty())

Solution 2

As far as your stacktrace says,

java.lang.IllegalArgumentException: bound must be positive at java.util.Random.nextInt(Unknown Source) ~[?:1.8.0_51]

The argument to nextInt needs to be a positive integer. You will need to find out where you’re passing a non-positive input to that method.

Guus Huizen

Updated on August 21, 2020

Comments

inv.setItem(i, items.get(r.nextInt(items.size()))); 

As far as I know, it comes from the part where I request a random integer from the list of items. This is how I defined the list:

List items = getAllItems(level); 
public List getAllItems(int level) < Listitems = new ArrayList(); for (String item : settings.getChests().getStringList("chestitems." + level)) < ItemStack toAdd = parseItem(item); items.add(toAdd); >return items; > 
[19:03:53 ERROR]: Error occurred while enabling KitPvP v0.5 (Is it up to date?) java.lang.IllegalArgumentException: bound must be positive at java.util.Random.nextInt(Unknown Source) ~[?:1.8.0_51] at me.iamguus.gamegetsiepunt.kitpvp.chests.ChestsUtil.randomlyFillInv(ChestsUtil.java:101) ~[. ] at me.iamguus.gamegetsiepunt.kitpvp.Main.onEnable(Main.java:40) ~[. ] at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) ~[spigot.jar:git-Spigot-5818108-a486600] at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:335) [spigot.jar:git-Spigot-5818108-a486600] at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) [spigot.jar:git-Spigot-5818108-a486600] at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugin(CraftServer.java:356) [spigot.jar:git-Spigot-5818108-a486600] at org.bukkit.craftbukkit.v1_8_R3.CraftServer.enablePlugins(CraftServer.java:316) [spigot.jar:git-Spigot-5818108-a486600] at org.bukkit.craftbukkit.v1_8_R3.CraftServer.reload(CraftServer.java:746) [spigot.jar:git-Spigot-5818108-a486600] at org.bukkit.Bukkit.reload(Bukkit.java:534) [spigot.jar:git-Spigot-5818108-a486600] at org.bukkit.command.defaults.ReloadCommand.execute(ReloadCommand.java:25) [spigot.jar:git-Spigot-5818108-a486600] at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) [spigot.jar:git-Spigot-5818108-a486600] at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchCommand(CraftServer.java:646) [spigot.jar:git-Spigot-5818108-a486600] at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchServerCommand(CraftServer.java:632) [spigot.jar:git-Spigot-5818108-a486600] at net.minecraft.server.v1_8_R3.DedicatedServer.aO(DedicatedServer.java:405) [spigot.jar:git-Spigot-5818108-a486600] at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:369) [spigot.jar:git-Spigot-5818108-a486600] at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:657) [spigot.jar:git-Spigot-5818108-a486600] at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:560) [spigot.jar:git-Spigot-5818108-a486600] at java.lang.Thread.run(Unknown Source) [?:1.8.0_51] 

Источник

Как исправить java.lang.IllegalArgumentException: граница должна быть положительной

Хорошо, я нашел проблему. Проблема была в основном классе с тестом. Он не работал без dependOnMethod, но это нормально или у меня есть ошибка?

'@Test public void addToCompare() < hp.compareItems(); >@Test public void goToComparePage() < hp.goToComparePage(); >@Test public void usun() < hp.findAvailability(); >@Test(dependsOnMethods = < "goToComparePage" >) public void chooseRandomItemToCart()< hp.chooseRandomItem(); >' 

Это именно то, что говорит ошибка: IllegalArgumentException: bound must be positive .

Ваш gen.nextInt() требует, чтобы вы gen.nextInt() положительное числовое значение (я принимаю целое число), а links.size() возвращает неположительное значение. Это может links.size() что links.size() равен 0 или null, что означает, что он не смог найти ни одного из элементов из строки 1 вашего кода. В этом случае проблема заключается в следующей строке:

List links = driver.findElements(By.xpath("//input[@value = \"Add to Cart\"]")); 

Пара вариантов на данный момент:

Сначала попробуйте распечатать links.size() чтобы узнать, что вы получаете. Это будет первый шаг.

Во-вторых, если оно равно 0 или null, попробуйте отладить первую строку кода.

Я не могу сказать, что это нормально или нет, потому что я не знаю, что содержит ваш hp.goToComparePage() . Однако, если этот метод должен взять вас на страницу сравнения, где находится кнопка, которую вы пытаетесь реализовать, тогда имеет смысл фактически перейти на страницу сравнения.

Я предполагаю, что пример был бы, если бы вы хотели войти в Stack Overflow. Вы, очевидно, хотите нажать кнопку “Войти”, но то, что должно произойти заранее, – это сначала перейти на веб-сайт “Переполнение стека”, а затем нажать кнопку “Вход”.

Из полученного вами IllegalArgumentException , похоже, что links.size() равно 0. Я бы гарантировал, что ваша первая строка действительно вернет хотя бы 1 ссылку.

Источник

[Fixed] IllegalArgumentException: Bound must be positive

In this post, we will see how to fix IllegalArgumentException: Bound must be positive in java.

You will generally get this exception while generating random numbers using Random.nextInt() method. If you pass bound as 0 or less than 0 , then you will get the exception.

Let’s understand with the help of example:

When you run the code, you will get following exception.

at org . arpit . java2blog . GenerateRandomNumberMain . main ( GenerateRandomNumberMain . java : 12 )

As we have passed bound as 0 to nextInt() , we got above exception.

Here is source code Random’s nextInt() method.

As you can see, if bound is less than or equals to 0, we will get this exception.

To resolve the issue, pass positive number to nextInt() method.

Here is code to generate random number between 1 to 5.

When you run the code, you will get following exception.

As you can see, we have passed bound as 5 to nextInt() method and it worked fine now.

Further reading:

Generate Random Number Between 1 and 100 in Java
Get random number between 0 and 1 in java

That’s all about how to fix IllegalArgumentException: Bound must be positive .

Was this post helpful?

Share this

Author

[Solved] Exception in thread “main” java.lang.NullPointerException

Table of ContentsReasons for NullPointerException1. Invoking the instance method of a null object2. Accessing or modifying the field of a null object.3. Taking the length of null as if it were an array.4. Accessing or modifying the slots of null as if it were an array.5. Throwing null as if it were a Throwable value.6. When you add null to Collections which do not allow […]

java.util.NoSuchElementException

Table of ContentsScenario 1: In case of EnumerationSolutionScenario 2: In case of IteratorSolutionScenario 3: In case of StringTokenizerSolution java.util.NoSuchElementException is a RuntimeException or say an UncheckedException and therefore it does not need to be declared in a constructor’s or a method’s throw block. java.util.NoSuchElementException is usually thrown when we try to access some element which […]

java.lang.StackOverflowError

Table of ContentsHow JVM invokes a methodReasons for java.lang.StackOverflowErrorPoor or No Termination ConditionSolutionDue to the Cyclic Relationships Between ClassesSolution In this article, we will discuss about the java.lang.StackOverflowError by looking different code examples and also how can we avoid them. More precisely, StackOverflowError is an error which Java doesn’t allow to catch, for instance ,stack […]

java.lang.NumberFormatException

Table of ContentsIteration 1: Put correct Integer valueIteration 2: Put NA as user inputIteration 3: Put “” as user inputIteration 4: Put “1.0” as user inputHow to resolve java.lang.NumberFormatException In this post, we will see about Java.lang.NumberFormatException. java.lang.NumberFormatException occurs where you try to convert any non-numeric String to Number such as Integer, Double, Float or […]

FileNotFoundException in Java

In this post, we will see about FileNotFoundException in java. FileNotFoundException is thrown by constructors of FileInputStream, FileOutputStream, RandomAccessFile when file is not found on specified path. Exception can also be raised when file is inaccessible for some reason.For example: When you do not have proper permissions to read the files. FileNotFoundException is checked exception […]

Источник

java.lang.IllegalArgumentException: bound must be positive

HazardousToast

HI there! I know this is a dead thread, but I wanted to throw in my 2 cents since this is the thread which popped up when i searched for the issue. I was having this exact issue- unable to download a file via the launcher, cant ping libraries.minecraft.net, but could ping minecraft.net. Turns out the DNS server my computer was automagically getting assigned was borked. What fixed it was: going to my ‘network connections’ in control panel right clicking the adapter I’m using (wifi, in my case), and selecting properties click the IPV4 property, then select the properties button In this screen, select the ‘use the following DNS server addresses’ radio button, then enter the following 2 DNS server IDs without the quotes «1.1.1.1» — thats the BetterDNS IP «8.8.8.8» — thats Google’s DNS address after applying these settings, i was immediately able to ping libraries.minecraft.net, and the launcher could download all necessary files to launch mincraft, and the forge version i wanted

The version you are using is no longer supported on this forum. Please update to a modern version of Minecraft to receive support.

LexManos

The concept is a known exploit that has been around for several years. It is not something that is caused by anything in ours, or Minecraft’s end. It is unfortunately a risk when using mods in Minecraft. They are arbitrary jars which can have any code in them. This is one of the reasons we push people to use the latest versions. This particular case was fixed in BdLib for 1.16+ and the author has no intention of back porting.

ReinierTheGhost

Hallo I am working on a fantasy rpg mod for 1.20.1. In this mod I want to create my own dimension which will generate a continent that we have already decided on how it should look, so the biomes should generate on the places we want them to generate instead of random like it does in vanilla minecraft. I know it should be posible since the LOTR mod has this done as well.

Источник

Читайте также:  Constructors in javascript objects
Оцените статью