I am trying to make a program wherein a user will be prompt on how many inputs to input. I have 3 user inputs in my multi array, if the user will input 1 then only one user input will appear. Otherwise, if the user inputs 2 or 3, then 2 or 3 user inputs will appear. Upon testing my program, it ran, but the java.lang.ArrayIndexOutOfBoundsException error appeared. I can't seem to find the error in here, I've tried adding extra index on my multi array but I still get the same error.
import java.io.*;
public class student {
private int stud_id;
private String stud_prog;
Object ctr1;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Object stud [][] = {{1,2,3},{"enter name:","enter age:","enter gender:"}};
public void stud() throws NumberFormatException,IOException{
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
for (int x = 1; x<=num1;x++){
for (int i = 0 ; i<num1;){
System.out.println(stud[x][i]);
ctr1 =in.readLine();
i++;
}
}
}
}
///////////////////////////////////////////////////////////////////main/////////////////////////////////////////////////////////////////////////////////
import java.io.IOException;
public class persontest {
public static void main(String[]args) throws NumberFormatException,IOException{
student s = new student();
s.stud();
}
}
Array index starts from 0 and end to length-1
Change:
for (int x = 1; x<=num1;x++){
To:
for (int x = 0; x<num1;x++){
First check for length of array before iterating
if(num1<=stud.length){
for (int x = 0; x<num1;x++){
....
}
}
Note: Multidimensional array can contains variable no of columns. You should use stud[row].length to get the no of columns of any row.
stud.length gives no of rows
stud[i].length gives no of columns of ith row
As per comment
what I mean is that if the user inputs 1 then 1 user attribute will appear, if 2 then 2 and so on...
Is this what are you looking for?
String stud[] = { "enter name:", "enter age:", "enter gender:" };
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
if (num1 <= stud.length) {
for (int x = 0; x < num1; x++) {
System.out.println(stud[x]);
//read input from user
}
}
Java uses zero-indexed arrays, meaning that counting starts at 0 (not 1!), 1, 2, 3, 4...
This means that when you attempt to reference array[4], it's actually getting the fifth element in the array (and if it doesn't exist? ArrayIndexOutOfBoundsException!)
You can fix your for-loops by changing it to look like this; it starts with zero, and goes up to (but not equaling) num1.
for(int x = 0; x < num1; x++) {
for (int x = 1; x<=num1;x++){
for (int i = 0 ; i<num1;){
System.out.println(stud[x][i]);
ctr1 =in.readLine();
i++;
}
}
Here it will run in two for loop. first one start from 1 to num1. but in next iteration invoking stud[x][i] x will be 2 . but stud has index 0,1 only. Please check your logic
Related
I have to write a battleships program, where the user inputs the size of the board, which is always square, and the number of ships that there will be. They then input their board, using 0 to represent water and 1 to represent a boat, and the program has to return whether the board they have entered is correct - i.e. there are the correct number of boats, and none of the boats are touching diagonally.
I have written code which aims to let the user input each line one by one (so for example, if it is a 5x5 grid, the user will have to put in 5 different numbers of 5 digits each) and each line will be put into my bidimensional array board[][]. I will then use this to check if the board is correct.
However I keep getting a string index out of range error. I know this error occurs when the code tries to access something at an index larger than the string, but I can't work out why this is happening as I have used the 'size' variable, in which the size of the grid is stored.
Here is my code:
public static void main(String[] args) {
int ships_num;
Scanner sc;
int size;
int[][] board;
sc = new Scanner(System.in);
do {
System.out.println("Please enter the number of boats. The maximum number is 10: ");
ships_num = sc.nextInt();
} while (ships_num > 10);
System.out.println("Number of boats: " + ships_num);
do {
System.out.println("Please enter the size of the board. This value is for both the length and width: ");
size = sc.nextInt();
} while (size > 20);
System.out.println("Size of board: " + size);
board = new int[size][size];
for (int y = 0; y < size; ) {
for (int x = 0; x < size; x++) {
System.out.println("Please enter the values for the first line. Values must either be 1, to represent a boat, or 0, to represent water");
String temp = Integer.toString(sc.nextInt());
for (int i = 0; i < size;i++) {
board[y][x]=temp.charAt(i);
}
if (x == (size-1)) {
x = 0;
y++;
}
}
}
}
The specific error I keep getting is: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4. This occurs when I enter size as 5, and then put in the number 01110 for the first line.
Thank you in advance :)
I'm working on a two part task, where the first part is to create an array of 3 rows and 4 columns and then have the user input 4 numbers to make up the first column of the first row. so if the user inputs 1,2,3,4 then the array should print out: (0 just blank for the second part of the task.
1 2 3 4
0 0 0 0
0 0 0 0
So far this is what I have, but I've only been working with Java for a few days and i'm sure i'm not seeing my error clearly. I would really appreciate any help in what i am doing wrong.
Here is my code:
import java.util.Scanner;
public class multipleElements {
public static void main(String[] args) {
//set up the array and assign variable name and table size
int[][] startNum = new int[3][4];
//set user input variable for the array
Scanner userInput = new Scanner(System.in);
for (int i = 0; i < startNum.length; i++) {
//get user input
System.out.print("please enter your value: ");
//push into the array
String inputValue = userInput.nextInt();
startNum[i][0] = inputValue;
startNum[i][0] = userInput
}
}
}
as for the second part of the task, the second and third row need to be multiples of whatever number is entered into the first row of that column. So it would look like this:
1 2 3 4
2 4 6 8
3 6 9 12
I'm not yet sure how i'm going to do that so any advice on where i could start researching or what i should look into would also be appreciated.
Please try this code:
public static void main(String[] args) {
//set up the array and assign variable name and table size
int[][] startNum = new int[3][4];
//set user input variable for the array
Scanner userInput = new Scanner(System.in);
for (int i = 0; i < startNum[0].length; i++) {
System.out.print("please enter your value: ");
int inputValue = userInput.nextInt();
startNum[0][i] = inputValue;
}
for (int i = 1; i < startNum.length; i++) {
for (int j = 0; j < startNum[0].length; j++) {
startNum[i][j] = (i + 1) * startNum[0][j];
}
}
}
In the first loop you are getting the values from user and setting first row of 2d array.
In the second for loops(2 fors) you are setting the values for 2nd and 3rd loop for each column from first row. That's why first for loop is starting from i=1 and second for loop is starting from j=1.
for (int i = 0; i < startNum[0].length; i++) {
// get user input
System.out.print("please enter your value: ");
// push into the array
int inputValue = userInput.nextInt(); // <-- assign to an int value
// assigns the user input to the columns of 0th row
startNum[0][i] = inputValue;
//startNum[i][0] = userInput // <-- not required
}
for (int i = 1; i < startNum.length; i++) {
for (int j = 0; j < startNum[0].length; j++) {
// starting from 1st row calculate the values for all the rows
// for a column and then move on to next column once finished
startNum[i][j] = startNum[0][j] * (i + 1);
}
}
I'm quite new to java.
I'm trying out some things for a project but I don't get why this does not work.
The goal here is to let the user input numbers separated by spaces and end with a letter. The program then needs to count the even and odd indexed numbers and output which sum is larger.
I already made this successfully when the amount of numbers given was a constant, but now I want to make it adapt to the user input.
Because I want to put the numbers in an array I need to know the length of this array. To get this I want to count the amount of numbers the user puts in so I can create the appropriate length array.
For some reason the while loop does not end and keeps running. How do I count the amount of numbers put in?
EDIT
I've added in.next(); in the first while loop so it is not stuck at the first input element. This brings me to a further problem however of having two while loops trying to loop through the same input. I have tried to create a second scanner and resetting the first one, but it does not get the second loop to start at the first element. Previous answers show that this is not possible, is there a way to put this in one while loop while still using arrays to store the values?
P.S. The input values should be able to be any positive or negative integer.
Here is my complete code:
import java.util.Scanner;
public class LargerArraySum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int length = 0;
System.out.println("Enter your numbers seperated by spaces, end with a letter");
while(in.hasNextInt()) {
length++;
in.next();
}
System.out.println(length);
int arra[] = new int[length];
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
int evenSum = EvenArraySum(arra);
int oddSum = OddArraySum(arra);
if(evenSum<oddSum) {
System.out.println("The sum of the odd indexed elements is bigger");
} else if(oddSum<evenSum) {
System.out.println("The sum of the even indexed elements is bigger");
} else {
System.out.println("The sum of the odd and even indexed elements is equal");
}
}
public static int EvenArraySum(int[] a) {
int sum = 0;
for(int i=1;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the even indexed elements is: " + sum);
return sum;
}
public static int OddArraySum(int[] a) {
int sum = 0;
for(int i=0;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the odd indexed elements is: " + sum);
return sum;
}
}
add in.next(); in the loop. Actually you don't need array. You can sum even and odd indexed numbers while reading without saving them.
1) Your first while-loop does not work because the iterator is always checking for further numbers in from the same position.
Example:
Position 0 1 2 3 4 5
Value 1 3 5 7 9 0
At start the iterator points to position 0. If you call hasNextInt() it will check if position 1 is available, in this case it will be true. At this moment the interator still points to position 0. So you increase your length and do the same thing again, so you have an infinite loop.
To move the iterator to the next position you need to call nextInt().
2) You can't iterate over the same Scanner with a second while-loop in that way. If you would correct you first while-loop the iterator would point to position 5 (it reached the end of the scanner). So the check for hasNextInt() will be false and the second while-loop will not be entered.
3) The comments already mentioned it, you could use an ArrayList for this use case like so:
final ArrayList<Integer> input = new ArrayList<>();
while ( in.hasNextInt() ) {
input.add( in.nextInt() );
}
System.out.println( input.size() );
( or like kitxuli mentioned in his answer, dont even store the values, just count them in the first while-loop)
Your code has 2 major problems . The first and the second while loops lets take a look at your first loop .
while(in.hasNextInt()) {
length++;
}
your condition in.hasNextInt() made you insert input because no variable was initialized with in.nextInt but also returns either [true] or [false] so as long as its true it will add to the length variable without prompting you to insert a [new input] .so the code should look like.
Int length = 0;
int k ;
while(in.hasNextInt()) {
length++ ;
k = in.nextInt();
}
you insert the input into an initialized variable k for ex then prompt the user to further input into k after adding to [length] then the loop will check your condition without prompting user for input.
Lets look at your second while loop.
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
In in.NextInt() you are prompting the user to enter new input once again so you don't need int x.Not even the while loop .However you MUST declare a new scanner in this ex: I call it c .The code should look like this.
int [] a = new int [length];
Scanner c = new Scanner (System.in);
for(int i=0;i<length;i++) {
if (c.hasNextInt()){
a[i] = c.nextInt();
} else
break;
}
You must add the if statement because if you get an alphabet in the int array you will get an exception error .The array a[i] will not prompt the user.
Of course it isn't practical to make the user enter the values twice so a better code to implement without using ArrayList class which I think you may not know very well is by using an empty String .
NEW CODE :-
String g = "";
String j ="";
int y ;
int q=0;
int w = 0;
while (in.hasNextInt())
{
y = in.nextInt();
g =g+y+",";
q++;
}
int arra [] = new int [q];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(',')){
arra[w]=Integer.parseInt(j);
System.out.println(arra[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
Another even better code :-You just insert your numbers separated by spaces without a letter ,hit enter and the array is filled.
Scanner in = new Scanner (System.in);
String g = "";
String j ="";
int y ;
int q=0;
int i=0;
int w = 0;
System.out.println("inset your input separated by spaces");
g = in.nextLine();
while(i<g.length()){
if((g.charAt(i))==(' ')){
q++;
}
i++;
}
int a [] = new int [q+1];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(' ')){
a[w]=Integer.parseInt(j);
System.out.println(a[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
a[w]=Integer.parseInt(j);
System.out.println(a[w]);
I am trying to generate a program that ask the user a number "n" and displays a 2 x n array. E.g:
1 2 3 4 5 (User input)
5 8 2 1 5 (Random numbers)
I can't see to make my code to work. Here is my code:
import java.util.Scanner;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of exits: ");
int n = input.nextInt();
int [][] A = new int[2][n];
for (int i =0; i <= A[n].length; i++){
A[i][n]= (int)(Math.random()*10);
}
System.out.println(A[2][n]);
System.out.print("Distance between exit i and exit j is: " + distance());
}
public static int distance(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter exit i: ");
int i = input.nextInt();
System.out.print("Please enter exit j: ");
int j = input.nextInt();
return i + j;
}
}
I am getting this error
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
5"
How can I fix it?
And I think my Math.random is wrong. Can you guys help me with some advises or where am I doing things wrong?
Thanks.
All your errors lie within and after your for-loop:
for (int i =0; i <= A[n].length; i++){
A[i][n]= (int)(Math.random()*10);
}
If n = 5, A[5].length does not exist, because the first dimensions of your array only exist between 0 and 1. A[2] reserves space for 2 int primitives, the first is at index 0 and the last is at index 1. Even if that is changed, the i variable your for loop declares is incremented beyond 1 and so the JVM will throw a ArrayIndexOutOfBoundsException.
When declaring an array with the dimensions [2][n], (given n is an Integer, which will be provided by the user via the scanner) you cannot access arrayReference[2][x]
Arrays are based on a 0 index structure...
Consider the following:
int [][] A = new int[2][2];
You can only access A[0][0], A[0][1], A[1][0] & A[1][1].
you CANNOT access A[2][0], A[2][1] or A[2][2].
Here's what you need to do:
//A.length will give you the length of the first dimension (2)
for(int i=0; i<A.length; i++){
for(int j=0; j<n; j++){
A[i][j] = (int) (Math.random()*10);
}
}
}
System.out.println(A[1][n-1]);
System.out.print("Distance between exit i and exit j is: " + distance());
I am attempting to create a small java program where the user will enter a string of numbers such as 2 4 6 7 8 9 0 3 4 5. These numbers will be saved to an array of int[] type. I then need the program to calculate how many of each number has been entered and output 2 columns, one containing the number entered and the other containing the amount of times the individual number was entered. Using the above numbers, I need the output to be as below:
Number Times Entered
2 1
4 2
6 1
7 1
8 1
9 1
0 1
3 1
5 1
So far I am using 3 classes. An application class that contains the main method, a driver class and the class containing the logic and objects. At this stage I have only started work on the class containing the logic. The code I have so far is below:
package arrayentry;
import java.util.Scanner;
public class Entry {
private Scanner scn = new Scanner(System.in);
private int[] count = new int[51];
public void countNumberEntry(int[] countArray){
int input = scn.nextInt();
for (int i=0; i<10; i++)
if (input == i)
count[i]++;
}
public void dataEntry(){
System.out.println("Please enter numbers between 1 and 50");
count = scn.nextInt[]();
}
}
Any ideas as to how I can get this to work would be greatly appreciated, this is driving me up the wall.
Thanks.
EDIT: To elaborate, I am have issues with everything. I for some reason can't get my head around it. I have read books etc but I can't get it. I need to store the entered numbers into an array of 50, then calculate the amount of times each number is entered and output as above.
To be honest I am just trying to get a grip / start on this.
You can create another array that will store number of occurences for you
public int [] countOccurences(int originalArray[]){
int countedOccurencesArray[]= new int [51];
for(int i=0;i<originalArray.length){
contedOccurencesArray[originalArray[i]]++;
}
return countedOccurences;}
This would actually be easier with a HashMap. Every time you read a number, check to see if it's in the map. If it is, increment the count, otherwise, insert it with a count of 1.
Since this assignment requires arrays, you'll want to create 2 50-cell arrays. In 1, store the value of the number read, in the second, store the count. Put both values in the cell that corresponds with the number read. Then just print off the values you need.
package arrayentry;
import java.util.Scanner;
public class Entry {
private Scanner scn = new Scanner(System.in);
private int[] numbers = new int[51];
private int[] count = new int[51];
public Entry() {
// All counts start at 0, all numbers start at -1 (invalid, so we know it's not from user input)
for (int cell = 0; cell < count.length; cell++) {
count[cell] = 0;
values[cell] = -1;
}
}
public void dataEntry(){
System.out.println("Please enter numbers between 1 and 50");
int[] input = scn.nextInt[]();
for (int value : input) {
numbers[value] = value;
counts[value] += 1;
}
}
public void printCounts() {
System.out.println("Number\tTimes Encountered.");
for (int cell = 0; cell < numbers.length; cell++) {
// Don't print counts of any number we didn't see in the input.
if (numbers[cell] > 0) {
System.out.println(numbers[cell] + "\t" + counts[cell]);
}
}
}
}