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());
Related
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);
}
}
How do I solve the following problem?
Please see link here.
My code only works when the data is entered horizontally.
How would I go about changing my code in order to be able to display the sums like my 2nd example above in the link?
Here's my code:
import java.util.Scanner;
public class sums_in_loop {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String code = scanner.nextLine();
String list[] = code.split(" ");
for( int counter = 0; counter < list.length; counter++) {
int sum = 0;
System.out.println(sum + " ");
}
}
}
Judging by the URL you provided, the solution is rather straight-forward.
Ask the user how many pairs to enter
Declare an array of integers with a size of the user input from step 1
Run a loop based on the user input from step 1
Declare an array of integers with a size of 2
Run a nested loop of two to get user input for the two integers
Add the two numbers into the array from step 2
Display results
With that in mind (I assume only valid data is being used):
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.print("How many pairs do you want to enter? ");
int numberOfPairs = input.nextInt();
int[] sums = new int[numberOfPairs];
for (int i = 0; i < numberOfPairs; i++) {
int[] numbers = new int[2];
for (int j = 0; j < numbers.length; j++) {
// Be sure to enter two numbers with a space in between
numbers[j] = input.nextInt();
}
sums[i] = numbers[0] + numbers[1];
}
System.out.println("Answers:");
for (int sum : sums) {
System.out.print(sum + " ");
}
}
Results:
How many pairs do you want to enter? 3
100 8
15 245
1945 54
Answers:
108 260 1999
I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers. Also who do i Enter numbers into an array without defining how many numbers will be entered?
import java.util.Scanner;
public class NumberArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many grades do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " grades now.");
for (int grades = 0 ; grades < array.length; grades++ )
{
array[grades] = input.nextInt();
}
System.out.println("These are the grades you have entered.");
printArray(array);
}
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " \t");
}
}
}
I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers.
From this question, it seems to indicate that you want the output to look like this:
1 2 3 4 5 6
7 8 9 ... n
This can be achieved quite simply.
Option 1 - The classic If statement
for(int x = 0; x < array.length; x++) {
System.out.print(array[x]);
if(x == 5) {
// 5 because we're counting from 0!
System.out.println();
}
}
Option 2 - Using the Ternary operator to keep it on one line
NOTE: This is more or less the same. It's just nice to be complete in these sorts of answers.
for(int x = 0; x < array.length; x++) {
System.out.print(array[x] + x == 5? "\n":"");
}
Edit
If you meant that you want 6 items on each line, like so:
1 2 3 4 5 6
7 8 9 10 11 12
...
Then you can use the % (The modulus operator) to print out a new line on every output. This is actually quite easy to change, but you'll need to make sure that you're checking the value before you're outputting the content. This can be shown in this IDEOne.
Use modulus operator (%) to break to a new line line:
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
if(i % 6 == 0) // if you don't want the initial newline, check for i > 0
System.out.println()
System.out.print(arr[i] + " \t");
}
}
you can also use printf() method to format the line; which is probably better:
System.out.printf("%5d", arr[i]);
The reason why this is better, is because you can easily format the output to a specific justification, column width, etc., which will make your output look better.
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
Cant find the error in coins array. when i tried to initialize the array with n+10 elements it worked. but actually it should be using only the n elements. where am i getting it wrong?
import java.util.Scanner;
public class MaximumContiguousSum {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int amount, n;
System.out.print("Enter number of types of coins : ");
n = in.nextInt();
int[] coins = new int[n];
System.out.print("Enter coins values : ");
for(int i=0; i<n; i++){
coins[i] = in.nextInt();
}
System.out.print("Enter the amount : ");
amount = in.nextInt();
int[] arr = new int[amount+1];
arr[1]=1; arr[0]=0;
for(int i=2; i<=amount; i++){
arr[i]=100;
int j=0;
//Error in the following line
while(coins[j]<=i && j<n){
arr[i]=min(arr[i], 1+arr[i-coins[j]]);
j++;
}
}
System.out.println("The number of coins to be used : " + arr[amount]);
in.close();
}
private static int min(int a, int b) {
// TODO Auto-generated method stub
return (a<b)?a:b;
}
}
Output:
Enter number of types of coins : 3
Enter coins values : 1 2 7
Enter the amount : 10
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at MaximumContiguousSum.main(MaximumContiguousSum.java:22)
You have an off-by-one error. Your line:
while(coins[j]<=i && j<=n)
Will try to grab coins[n] before it quits, and the final index of your array is actually n-1
Don't check greater than or equal on the error line
change this while(coins[j]<=i && j<n){ to while(coins[j]<i && j<n){ in your code
This
int[] coins = new int[n];
declares coins to have n elements with maximum index n - 1
this
while(coins[j]<=i && j<=n){
arr[i]=min(arr[i], 1+arr[i-coins[j]]);
Will attempt to access coins[n] when j = n which is past the end
Edit: arr[i-coins[j]] is protected against.
finally this:
while(coins[j]<=i && j<n)
should be this
while(j < n && coins[j]<=i)