Array out of bounds java - java

I am trying to write a code in which I construct a 52 card pile, then deal the cards out to n number of players (it is possible for some players to have an extra card). The winner is the one with the Ace of Spades card.
Here is my program:
public class CardGame {
public static void main(String[] args) {
System.out.println("Enter the number of players");
int numofPlayers = Integer.parseInt(args[0]);
CardPile gameDeck = CardPile.makeFullDeck();
CardPile [] players = new CardPile[numofPlayers];
for (int i=0;i<numofPlayers;i++) {
int numofnum = i%numofPlayers;
players[i] = new CardPile();
}
for (int i=0;i<52;i++) {
int numofnum =i%numofPlayers;
CardPile curPlayer = players[i%numofPlayers];
Card nextCard = gameDeck.get(i);
players[numofnum].addToBottom(nextCard);
}
for (int i=1;i<numofPlayers;i++) {
if (players[i].find(Suit.SPADES, Value.ACE) != -1) {
System.out.println("Player" + i + "has won!");
}
}
}
}
I keep getting an out of bounds error. The methods that I am calling in this program are well written so the problem should come from this code. Can anyone help ?
Edit : Here is the error that I get
java.lang.ArrayIndexOutOfBoundsException: 0
at CardGame.main(CardGame.java:5)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
>
Thanks !

You're asking for the number of players, but not reading input; instead you're reading the args to the program to figure out the number of players.
Likely you're not passing any arguments on the command line, so it's throwing an exception when you ask for args[0].
You'll want to look into getting input from console within the program, or pass the number of players when you run the program (in which case the println can be removed).

As Alex explained in his answer, the reason is because you are not passing arguments when running your code. If you wish for the code to work then you have to run your code as follow:
java CardGame 5
The above executes your CardGame class and pass 5 as argument to the main method in args[0]. If you are executing the code via some IDE let's assume Eclipse then please see the answer in this question to figure out how to pass argument.
If you wish to replace your code above (to accept input from user) then please replace the following line
int numofPlayers = Integer.parseInt(args[0]);
With the following line
Scanner input= new Scanner(System.in);
int numofPlayers = input.nextInt();
After executing the code will ask you to input the number of players and input a +ve integer value.
If you use the Scanner option then make sure you validate your input against values that are not integer (as well as negative integer). For example, if the input is provided as anything but, integer then you will get InputMismatchException hence, surrounding your input with try{} and catch(){} to catch above exception would be the right way to go about it.

Related

Calculating factorial for 0 leading to NoSuchElementException

I got to calculate the factorial of a number. As a fact factorial of 0 is 1. So I included that case in the function as well.
here's the code:
import java.util.*;
public class Factorial {
static int fact(int n) {
int result;
if (n == 0 || n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
public static void main(String args[]) {
int i, fact = 1;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
fact = fact(n);
System.out.println(fact);
}
}
but if I'm giving input as 0, some exception was raised
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Factorial.main(Factorial.java:14)
How to resolve this situation?
Edits:
I have changed the exception.All apologies for the thing that yes the code wasn't even 26 lines. I had put some code above as comments before posting just the code here.
This ain't a duplicate. As of the fact I want to know why it doesn't accept 0 as an input. It works perfect for all other inputs.
I use an online Compiler https://www.tutorialspoint.com/compile_java_online.php
Works fine with Java Compiler of the PC JDK 1.7 ,but raises exception on online IDE.
NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. To prevent it from happening, you may consider using hasNextInt() to check if any more tokens are available. Link.
Modified your code and added hasNextInt so that NoSuchElementException is not thrown and sc.close() to close the resource at the end of main method
public static void main(String args[]) {
int fact = 1;
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
int n = sc.nextInt();
fact = fact(n);
System.out.println(fact);
}
sc.close();
}
The online IDE is probably doing some kind of pre-processing of the data that
don't plays very nice with zeros.
TutorialPoint has online compilers for multiple languages and is very likely
that these all share some common backend that does the magic of passing text
from your browser to their servers. I'm not sure what kind of processing is
happening behind but I can imagine that is something like trimming the
unnecessary zeros from the left of the numbers or something like that.
I have encountered the opposite problem in standard C with the function sscanf,
which expected to fail (return 0) when the input string is empty just like its
sister function scanf but it still returns sucess and stores zero in the integer
variables.
By the way, if you just add a leading space or \n to the zero, everything works
just fine.

Half String every second char

I an coding beginner.I have started practicing SPOJ basic problems.This was the one I was trying to solve , But the code is incorrect.
Please help me where I have coded this question wrong as I am unable to figure out:
public class Print2ndChar {
public static void main(String[] args) throws java.lang.Exception {
Print2ndChar mainObj = new Print2ndChar();
java.io.BufferedReader inputReader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
String noOfTestCase;
if(((noOfTestCase = inputReader.readLine()) == null))
System.exit(0);
int noOfLines = 0;
try{
noOfLines = Integer.parseInt(noOfTestCase);
}catch(Exception e){
System.exit(0);
}
if(noOfLines<0 || noOfLines>100)
System.exit(0);
String [] randomWords = new String[noOfLines];
for(int i=0;i<noOfLines;i++){
randomWords[i] = inputReader.readLine();
if(randomWords[i] == null || randomWords[i].length()<2 || randomWords[i].length()%2!=0 || (randomWords[i].length()/2)>100)
System.exit(0);
}
for (String word : randomWords){
mainObj.letsBegin(word.substring(0, word.length() / 2));
System.out.println();
}
}
private void letsBegin(String data) {
if (data.length() <= 0) {
return;
} else {
System.out.print(data.charAt(0));
if (data.length() >= 3)
letsBegin(data.substring(2, data.length()));
}
}
}
EDIT :
I/P : 4
your
progress
is
noticeable
O/P
y
po
i
ntc
OK! So after a lot of hit and trials, I know what is wrong with your code. The code that you have written fails because of the condition randomWords[i].length()%2!=0 inside your if. There is nothing wrong with you putting this condition to check the input, but if you will select sample test case, inside the highlighted blue area you will notice an extra space after every string. Like this :
You can see that other than the last input all other input strings have a space character at the end. So, when you read the string from stdin the length of the string is 2*k + 1 (because of the space), and your program will exit without any output. Hence you get a wrong answer.
This problem exists with other test cases as well probably. And how do I know this? After spoj shows you wrong answer, if you click on the wrong answer, it will show you 2 failed test cases, something like this:
It shows your program's output is empty because your code exited because of the extra space at the end of strings.
So, I believe the person who wrote the test cases should be given a WT Error (Wrong Test Cases) :P :D
So, the possible correction is you remove the mentioned condition from the if and you will get AC. Because now you will be dividing 2*k + 1 by 2, which will not be an integer and which will get rounded to the nearest smallest integer, which will be same as dividing 2*k by 2 and the program will give the correct result.
A few things that you should take care while solving questions on spoj, you do not have to verify that every input lies within the range specified in the question, or if it is a valid data type. The range is given to tell you that Spoj will only test your program with cases which lie between those ranges and will not exceed them. So, even if you remove all the code where you check for exceptions and ranges of input data, you will get an AC. Moreover, writing such code only adds to the burden.
Hope this helps. :)

Java: Saving User Input to be Calculated in a Loop

Unfortunately, I can't attach my overall program (as it is not finished yet and still remains to be edited), so I will try my best to articulate my question.
Basically, I'm trying to take an integer inputted by the user to be saved and then added to the next integer inputted by the user (in a loop).
So far, I've tried just writing formulas to see how that would work, but that was a dead end. I need something that can "save" the integer entered by the user when it loops around again and that can be used in calculations.
Here is a breakdown of what I'm trying to make happen:
User inputs an integer (e.g. 3)
The integer is saved (I don't know how to do so and with what) (e.g. 3 is saved)
Loop (probably while) loops around again
User inputs an integer (e.g. 5)
The previously saved integer (3) is added to this newly inputted integer (5), giving a total of (3 + 5 =) 8.
And more inputting, saving, and adding...
As you can probably tell, I'm a beginner at Java. However, I do understand how to use scanner well enough and create various types of loops (such as while). I've heard that I can try using "var" to solve my problem, but I'm not sure how to apply "var". I know about numVar, but I think that's another thing entirely. Not to mention, I'd also like to see if there are any simpler solutions to my problem?
Okay So what you want is to store a number.
So consider storing it in a variable, say loopFor.
loopFor = 3
Now we again ask the user for the input.
and we add it to the loopFor variable.
So, we take the input using a scanner maybe, Anything can be used, Scanner is a better option for reading numbers.
Scanner scanner = new Scanner(System.in);//we create a Scanner object
int numToAdd = scanner.nextInt();//We use it's method to read the number.
So Wrapping it up.
int loopFor = 0;
Scanner scanner = new Scanner(System.in);//we create a Scanner object
do {
System.out.println("Enter a Number:");
int numToAdd = scanner.nextInt();//We use it's method to read the number.
loopFor += numToAdd;
} while (loopFor != 0);
You can just have a sum variable and add to it on each iteration:
public static void main(String[] args) {
// Create scanner for input
Scanner userInput = new Scanner(System.in);
int sum = 0;
System.out.println("Please enter a number (< 0 to quit): ");
int curInput = userInput.nextInt();
while (curInput >= 0) {
sum += curInput;
System.out.println("Your total so far is " + sum);
System.out.println("Please enter a number (< 0 to quit): ");
}
}
You will want to implement a model-view-controller (mvc) pattern to handle this. Assuming that you are doing a pure Java application and not a web based application look at the Oracle Java Swing Tutorial to learn how to build your view and controller.
Your model class is very simple. I would suggest just making a property on your controller that is a Java ArrayList of integers eg at the top of your controller
private Array<Integer> numbers = new ArrayList<Integer>();
Then your controller could have a public method to add a number and calculate the total
public void addInteger(Integer i) {
numbers.addObject(i);
}
public Integer computeTotal() {
Integer total = 0;
for (Integer x : numbers) {
total += x;
}
return total;
}
// This will keep track of the sum
int sum = 0;
// This will keep track of when the loop will exit
boolean errorHappened = false;
do
{
try
{
// Created to be able to readLine() from the console.
// import java.io.* required.
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
// The new value is read. If it reads an invalid input
// it will throw an Exception
int value = Integer.parseInt(bufferReader.readLine());
// This is equivalent to sum = sum + value
sum += value;
}
// I highly discourage the use Exception but, for this case should suffice.
// As far as I can tell, only IOE and NFE should be caught here.
catch (Exception e)
{
errorHappened = true;
}
} while(!errorHappened);

Java Method Call Array

How do I pass an array from my main method to another method? I'm having an error with the parameters. Do I use the return value from main? And since the return value from main is an array, should the parameters for the call of main have brackets? Should there be a value between those brackets?
public class arraysAndMethods {
public void printArray(double[] arr) {
int x = arraysAndMethods.main(double[i] arr);//error with paremeters
for (int i = 0; i < studGrades.lenght; i++)
System.out.print(studGrades[i] + " ");
}// end of printArray method
public static double[] main(String args[]){// double array
java.util.Scanner input = new java.util.Scanner(System.in); // input scanner
System.out.println("What is the size of the class?");
int n = input.nextInt();
double[] arr = new double[n];// declare and initialize array to have n many elements
for (int i = 0; i < arr.length;i++) {// input grades for each students
System.out.println("What is the grade of student #" + (i+1));
arr[i] = input.nextDouble();
} // end of for loop
return arr;
}// end of main method
}// end of class
Just pass the name, not the type.
int x = arraysAndMethods.main(arr);
EDIT:
Besides that, your code shows a few other problems.
main(...) is the entry point to your application. It doesn't make sense to call main(...) from the other method. It should be the other way around.
main(...) HAS TO have the following signature: public static void main(String[] args). You cannot declare it to return an array of double.
This whole thing doesn't make much sense. If you're hoping to have this as the main method of a Java program, this won't work because the main method must have a void return type. Regardless, you have a syntax error here:
int x = arraysAndMethods.main(double[i] arr);//error with paremeters
Instead it should be
int x = arraysAndMethods.main(arr);//error with paremeters
as the variable has already been declared. I'm not sure what you were trying to do with double[i], but that syntax is more like a declaration, i.e.
double[] someArrayName = new double[5];
Your main method is where the program begins execution. In other words you should be calling printArray() from within main, not the other way around
I think I see where the confusion is. Perhaps this will help.
First I think you should understand something very important about Java.
Your main method is the FIRST method that is run.
So let's give a short walk through of how a Java program is created without an IDE.
First, you write your code in a text file and rename it to arraysAndMethods.java when you're done. Next we need to take your code and put it into a form that is usable by the computer it is first compiled down to bytecode with the following from the command line:javac arraysAndMethods.java
After it is compiled you can run the program with this command: java arraysAndMethods
Your program will run if there are no problems.
You say that you want to pass variables things into the main method? Here is how you do that from the command line: java arraysAndMethods 45.6 38.2 5.5 105.3
Looking at your main method, it takes the following arguments: (String args[])
So in your case, the 45.6 38.2 5.5 105.3 would be passed into your main method as an array of strings. With the first entry being 45.6, followed by 38.2, then 5.5 and finally 105.3.
It would look like this in the array: ["45.6"],["38.2"],["5.5"],["105.3"] but they are all Strings and not doubles.
All of this is to say that if you want to pass something in to your main method, you'll either need to do it through the command line, or look up how your individual IDE (i.e. Eclipse, Netbeans, etc.) handles that.
So to recap: The parameters in the main method are coming in from the console unless other specifications are made, and in your case it is returning an array of type double.
I know this is quite verbose, but bear with me, I'm almost done.
When a Java program is run(I'm simplifying a bit here), it comes into the main method and executes the first line it sees. When it's done with that one, it goes onto the next line, and so forth until it gets to the end of the main method. Then the program is done.
So everything MUST be done in the main method. Although you can call other Classes and methods from the main method.
Now that you have the explanation, here is what I would do to fix your code:
public class arraysAndMethods {//Changed from arraysAndMethods to ArraysAndMethods because classes are always capitalized
public static void printArray(double[] arr) {//Added static so this could be used within the same class as the main method.
//int x = arraysAndMethods.main(double[i] arr); No need for this line
for (int i = 0; i < arr.length; i++)// Changed "studGrades.lenght" to arr.length
System.out.print(arr[i] + " ");//Changed "studGrades" to arr
}// end of printArray method
public static void main(String args[]){// Changed the return type to "void". No need to return the double array.
java.util.Scanner input = new java.util.Scanner(System.in); // input scanner
System.out.println("What is the size of the class?");
int n = input.nextInt();
double[] arr = new double[n];// declare and initialize array to have n many elements
for (int i = 0; i < arr.length;i++) {// input grades for each students
System.out.println("What is the grade of student #" + (i+1));
arr[i] = input.nextDouble();
} // end of for loop
printArray(arr);
//return arr; No need for this line
}// end of main method
}// end of class
Please be sure to mark the best answer when you're ready and up-vote any answers or comments you feel helped. Not just for this question, where you are the original poster, but for other question threads as well.

How do I fix my scanner input that is null?

Hi I am new at java programming and ran into a problem on my latest project. I am making a score generator for bowling and finished the code, except when I went to test it, it said
"Exception in thread "main" java.lang.NullPointerException
at Bowling_Score.main(Bowling_Score.java:34)"
I tried everything to fix it, and looked through tons of websites, but no solutions solved my problem. It's probably something really easy to fix, but I can't seem to find the answer. The line that has the problem is the second line here.
System.out.println("Frame 1, Throw 1");
Frame1Throw1 = sc.nextInt();
This is the only way I know how to use a scanner with variables, so if there is a better way please tell me. It also may be a problem because the variable Frame1Throw1 is the first variable on the list.
The variable is correct, and my scanner's name is sc
Please be specific with your answer, because as I said, I am new at java, and am just learning the basics now. This is my first big project.
Thank You!
P.S. I use eclipse to code I don't know if that matters or not
* I got one answer, and it was helpful, but It didn't work. Here is some more of the beginning of the code which may be helpful in answering.
import java.util.Scanner;
public class Bowling_Score {
private static Scanner sc;
public static void main(String[] args) {
//All Variables
int Frame1Throw1 = 0;
int Frame1Throw2 = 0;
int Frame2Throw1 = 0;
int Frame2Throw2 = 0;
int Frame3Throw1 = 0;
int Frame3Throw2 = 0;
int Frame4Throw1 = 0;
//Then I have one variable for each throw of the game, and one for the final total score.
//Directions
System.out.println("To put in your score, put the number of pins you knocked down in the throw specified. If you get a strike, enter a 10 in the first throw of the frame and a 0 in the second throw of the frame. If you get a spare, Ener a 0 in the first throw of the frame and 10 in the second throw of the frame.");
//Frame 1
System.out.println("Frame 1, Throw 1");
Frame1Throw1 = sc.nextInt();
if (Frame1Throw1 == 10){
Frame1Throw1 = Frame1Throw1 + Frame2Throw1 + Frame2Throw2;
Frame1Throw2 = 0; }
A NullPointerException means that the object you are referencing hasn't been initialised. So in this case I imagine that your sc hasn't been created previously in your code.
Look for something like
Scanner sc;
and change it to
Scanner sc = new Scanner(System.in);
Otherwise it could be a scope problem (you created the object somewhere that can't be seen by that method) you'll need to provide more code if the first solution doesn't work.

Categories

Resources