This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am trying to write a guessing game where we are not allowed to use the same card twice and we need to use an array of 15 card (objects) I have created everything (probably not in an ideal fashion) but I keep getting the error java.land.ArrayIndexOutOfBoundException: Index 15 is out of bounds for length 15 when I try to answer all questions correctly it won't complete the deck of cards. I don't understand why. Here is the relevant code:
while (CountryCard.instances < 30) {
System.out.println("Would you like to guess the capital of a country?"
+ " Hit 1 for yes, or 2 for no (Case sensitive)");
yesNo = input.nextInt();
if (yesNo == 2) {
return;
}
int randomNumber = 0 + (int) (Math.random() * ((game.length)+1 ));
while(game[randomNumber].used==true){
randomNumber = 0 + (int) (Math.random() * ((game.length)+1 ));
}
System.out.println("What is the Capital of "
+ game[randomNumber].getName() + "?");
game[randomNumber].usedCard(1);
guess = input.next();
if (guess.equals(game[randomNumber].getCapital())) {
System.out.println("Correct! :)");
} else {
System.out.println("Incorrect! :(");
}
}//end of while
System.out.println("Thanks for playing :)");
Array indices are 0 based that means the 15th element has an index of 14
The index for any Array/List starts with 0, so a object with length of 9, will have the max object index of 8
char[] a = "Apple".toCharArray();
so the length of a is 5, but a[4] = 'e'
Related
This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed last month.
Whats the difference between these two operations?
I imagined:
length - 1
to be the same as
length-1
but I am getting an error with length when using the latter
using operation here: for (int i = length - 1; i >= 0; i--)
int length = Integer.parseInt(scan.nextLine());
Edit: ENTIRE CODE:
import java.util.Scanner;
import java.util.Arrays;
public class continuousmedian
{
public static void main(String args[])
{
Scanner scan = new Scanner (System.in);
int cases = Integer.parseInt(scan.nextLine());
for (int set = 0; set < cases; set++)
{
int length = Integer.parseInt(scan.nextLine()), med = 0;
String[] copy = (scan.nextLine()).split(" ");
int[] test = new int[length];
for (int i = length-1; i >= 0; i--)
{
test [i] = Integer.parseInt(copy[i]);
//System.out.println("4 is " + test[4]);
Arrays.sort(test);
//*
System.out.print(">>");
for (int a = 0; a < length; a++)
System.out.print(test [a]);
System.out.println();
//*/
//System.out.println(i);
int mid = length - 1 - i;
if (i%2 == 0)
med += test[mid];
else
med += Math.floor((test[mid] + test[mid+1])/2);
//System.out.println("TEST AT " + mid + " is " + test[mid]);
}
System.out.println(med);
}
}
}
input case:
2
6
1 3 6 2 7 8
7
1 3 6 2 7 8 5
and finally, the error message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1 3 6 2 7 8"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:784)
at continuousmedian.main(continuousmedian.java:13)
For those of you saying that it is trying to parse a line of input:
The ONLY thing I changed is length-1 -> length - 1
"They are the same. Coding conventions say to use spaces, but the semantics are the same." - Ole
This was correct. Turns out, it didn't matter which of the formats I chose. In the end, it was completely 50/50 when running the program whether it worked or not. I ran the program a few times, copy pasting the same input into the same program. Sometimes it worked, sometimes it didn't. Maybe something with my computer clock or something, Idk but thanks for the help anyways.
This line is your problem:
int length = Integer.parseInt(scan.nextLine()), med = 0;
If the input line is "1 3 6 2 7 8", then you attempt to parse that line as an integer, which it manifestly is not. An exception is thrown indicating you're applying parseInt to invalid data.
We can tell this with absolute certainty - the exception message says so. You were trying to apply parseInt to the string "1 3 6 2 7 8". This is not in doubt.
It looks like that particular line of input was intended for the next line of code, which will split it on spaces, but in fact you never get there because of the previous error.
Given your statement that the input was supposed to be
2
6
1 3 6 2 7 8
7
1 3 6 2 7 8 5
then it looks like you didn't actually type one of the "2" or the "6".
This question already has an answer here:
Determine if a number contains a digit for class assignment
(1 answer)
Closed 2 years ago.
My idea is to create a loop and not print numbers that contain a 3 in them like 13, 23, 43,etc. between 2 numbers given by a user.
My problem is on the loop. How do I check that the numbers contain a 3 on them?
For example if it prints from 2 to 24. It should not print 3,13 and 23.
for(int i = x; i <= y; i++){
if(i%3 == 0){
System.out.print("");
else{
System.out.println(i);
}
}
for(int i = x; i <= y; i++){
if(i%10 == 3){
System.out.print("");
}
else{
System.out.println(i);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
Example 2:
Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.
Example 3:
Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.
Traverse from left to right and change the first occurrence of 6 to 9. If there is not any 6 while traversal then does not change any digit.
Following code may help:-
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class testing {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number : ");
int a=sc.nextInt();
String numberString = Integer.toString(a);
for (int i = 0; i < numberString.length(); i++){
char c = numberString.charAt(i);
if(c=='6') { // check if the digit is 6 or not, if 6 is present then change it to 9
numberString = numberString.substring(0, i) + '9' + numberString.substring(i + 1);
break; // break the loop if 6 is changed to 9
}
}
System.out.println("Largest Number is : "+numberString);
}
}
public class Maximum69 {
public static void main(String[] args) {
int num=6669;
int added = 0;
int cur = 1;
int curNum = num;
while(curNum > 0) {
if(curNum % 10 == 6)
added = cur;
cur *= 10;
curNum = curNum / 10;
}
System.out.println(num + added * 3);
}
}
I found out how to slove, This takes less time to run:
I have found a formule, it could have been a single line solution but for clarity I have divided in two lines
First , get the highest number based on input number of digits , for example if input is 6, topNumber will be 9, for 69 top will be 99 , for 696 top is 999, so topNumber can be 9 or 99 or 999 or 9999 or 99999,etc up to java limit, the formula to get number of digits in an integer is :
floor(log10(input)) + 1
Then you can notice that the top number minus the input, it gives you a number that starts with 3, for example 9-6 = 3 , 99 - 69 = 30 , 999 - 696 = 303, except when the input is equal to the top number, in that case the result is 0,
knowing that fact, we can conclude that for switching the first 6 in the number can be achieved by summing up 3 * (((the position of the 6) -1) * 10) , eg. 3 or 30 or 300 or 3000 or 30000, etc.
resulting in the last part of the function : input + (10^(NumberOfDigits(top - input)) -1) * 3
private static int largest69(int number) {
int topNumber = (int) (Math.pow(10,(int)(Math.log10(number)) + 1) -1);
return number + (int) Math.pow(10,(( (int)(Math.log10(topNumber - number)) + 1 ) -1) ) * 3;
}
If you're not as good as nitinsridar at intuitively implementing math into your algorithm, and if you don't want to mess around with strings like backdoor did, then you can utilize data structures to help you come to a solution without much thought
public static void main(String[] args) {
System.out.println(maxNumber(9669));
}
public static int maxNumber(int number) {
Stack<Integer> numbers = new Stack<Integer>();
int numberLength = 0;
while(number > 0) {
numbers.push(number % 10);
number /= 10;
numberLength++;
}
boolean changedFirstOccurrence = false;
int maxNumber = 0;
for(int i = numberLength; i > 0; i--) {
int numberToAdd = numbers.pop();
if (numberToAdd == 6 && !changedFirstOccurrence) {
numberToAdd = 9;
changedFirstOccurrence = true;
}
maxNumber += numberToAdd * (int) Math.pow(10, i);
}
return maxNumber / 10;
}
Is this the best solution? Nope, I would go with nitinsridar's answer (I also believe that his/her answer should get the green checkmark).
Backdoor's answer is definitely how I would've solved this problem before I took my data structures and algorithms class. I'm not saying it's a bad answer. In fact, his algorithm is more concise than mine. It's just my opinion that you don't want to get in the habit of relying on string manipulation to solve these sort of "numerical" problems, because one day it's not going to work; in this case, it did. I'm just providing another way of doing it
This question already has answers here:
Java Increment / Decrement Operators - How they behave, what's the functionality?
(2 answers)
Closed 7 years ago.
I've seen this question (from a multiple choice) "what is the output of the following program" :
class array_output {
public static void main(String args[])
{
int array_variable [] = new int[10];
for (int i = 0; i < 10; ++i) {
array_variable[i] = i/2;
array_variable[i]++;
System.out.print(array_variable[i] + " ");
i++;
}
}
}
The expected output is:
1 2 3 4 5
It is clear to me that the value i is incremented twice, first in the body of the loop and at the last line.
But I don't really get what the line array_variable[i]++; is doing.
Any suggestions?
Thanks in advance to answer to this newbie question!
The post-fix increment and decrement operators return the value of a variable before altering its value. Consider the following:
int anInt = 0;
System.out.println("anInt: " + anInt);
// anInt: 0
System.out.println("anInt: " + anInt++);
// anInt: 0
System.out.println("anInt: " + anInt);
// anInt: 1
System.out.println("anInt: " + ++anInt);
// anInt: 2
System.out.println("anInt: " + anInt);
// anInt: 2
So basically, anInt++ returns the value of anInt before incrementing it. ++anInt increments the value of anInt before returning the (freshly-incremented) value.
array_variable[i]++; increments the value that is stored in array_variable[i] by one.
Hello i am having a tough time trying to write a function that can create an array that holds integers, that equal my simple math problem.
my problem is not adding integers into the array but finding the correct integers that could add up to a math problem.
for example i have a simple math problem like: 10 + 10 = ? we know it equals 20
so i want my array to hold up to ten integers, that when added all together equal 20.
this is what i have been trying in code but not getting the results i want.
while (totalCount != answer
&& count < setCount) {
randomNumber = rand.nextInt((int) answer / 2) + 1;
if(count < setCount) {
sumOfBalloons.add(randomNumber);
totalCount += randomNumber;
count++;
}
if(totalCount > answer) {
count = 0;
totalCount = 0;
sumOfBalloons.clear();
}
}
i am trying to find random numbers that add up to the math problems answer so i can draw them on balloons. problem is i can never get ten numbers to equal the answer in my while loop.
does anyone know some way of doing something like this?
need array to hold 3 - 10 integers that equals my math problems answer.
** update on code thanks to the advice i received i managed to fix my while loop now it looks like this
had to post like this cause my rep is very low. sorry.
while (totalCount != answer) {
randomNumber = rand.nextInt((int) answer / 2) + 1;
if(totalCount + randomNumber > answer) {
randomNumber = rand.nextInt((int) answer - totalCount) + 1;
}
if(count + 1 == setCount) {
randomNumber = answer - totalCount;
}
if(count < setCount) {
sumOfBalloons.add(randomNumber);
totalCount += randomNumber;
count++;
}
if(totalCount > answer
|| totalCount == answer
&& count < setCount
|| totalCount != answer
&& count == setCount) {
count = 0;
totalCount = 0;
sumOfBalloons.clear();
}
}
this is what i got in my console from this code
Total count = 10
Total totalCount = 20
sumOfBalloons 0 = 2
sumOfBalloons 1 = 3
sumOfBalloons 2 = 3
sumOfBalloons 3 = 2
sumOfBalloons 4 = 1
sumOfBalloons 5 = 4
sumOfBalloons 6 = 2
sumOfBalloons 7 = 1
sumOfBalloons 8 = 1
sumOfBalloons 9 = 1
I think there are a few options here re: generating random numbers that sum to 20.
Here's one possible solution:
Create an array of length 4, for example.
Generate random number between 1 and 6 for each of the first 3 indices of your array.
At this point you'll have an array of the form: { 4, 5, 2, _ } (where our 4th element hasn't been chosen yet).
Sum our first 3 elements: 4 + 5 + 2 = 11. Determine 4th element by calculating 20 - current_total (11) = 9.
Set myArray[3] = 9;
A few things to note:
You may need to modify the range of possible random numbers ( 1-6 ) I've given. Consider what happens if the array we generate turns out to be { 2, 1, 2, _ }...then there's no digit that will ensure the elements sum to 20.
Another option is to use an arrayList instead of an array. The benefit to this is that you can keep adding elements to your arrayList until you either hit 20 (then you're done) or go over (in which case you delete the most recent element and begin adding again). You also won't need (or be able) to know the length of your arrayList in advance.