So I have to print out an array which:
The first cell defines the dimension of the square array. So, I have the input Scanner.
On the first row of the array, every cell has to be the triple of the previous one minus one.
For every next row, every cell has to have the double of the same column of the previous line, plus the number of the column.
For example: if the input of the dimensions is 4, like showArrray(creerArray(4));, then it should print something like:
4 11 32 95
8 23 66 193
16 47 134 389
32 95 270 781
I already coded the part for the input dimension, but I am stuck at trying to figure out how to code this sequence:
public static void showArray() {
}
public static void createArray() {
int square= 0;
int[][] int2D = new int[square][square];
java.util.Scanner input = new Scanner(System.in);
square= input.nextInt();
System.out.println("Enter the dimension of the array:" + square);
int counter=0;
for(int i=0; i<square; i++) {
for(int j=0; j<square; j++){
int2D[i][j]=counter;
counter++;
}
input.close();
}
****i have to start coding the sequence here
}
It's all a matter of where you place your calculations within the for loops to generate the 2D Array, for example:
// Get Array size from User...
Scanner userInput = new Scanner(System.in);
int aryLength = 0; // To hold the square 2D Array Rows and Columns length.
while (aryLength == 0) {
System.out.print("Enter 2D Array square size: --> ");
String len = userInput.nextLine();
/* Is the supplied value valid...
The Regular Expression passed to the String#matches() method
will return boolean true is the variable len only contains
a string representation of a signed or unsigned integer
value. */
if (len.matches("-?\\d+")) {
// Yes it is:
aryLength = Integer.valueOf(len);
}
else {
System.err.println("Invalid numerical value (" + len + ") supplied!");
System.err.println();
}
}
// Declare and initialize the 2D Array
int[][] array = new int[aryLength][aryLength];
int startVal = aryLength; // Used to calculate the first cell of every array Row
// Iterate array Rows...
for (int i = 0; i < array.length; i++) {
// Iterate Columns of each array row...
int cellVal = startVal; // Used for the cell values for all columns in each row
for (int j = 0; j < aryLength; j++) {
array[i][j] = cellVal;
cellVal = ((array[i][j] * 3) - 1); // calculate cell value
}
startVal = startVal * 2; // Calculate first cell value for very row.
}
// Display the 2D Array
System.out.println();
for (int i = 0; i < array.length; i++) {
System.out.println(Arrays.toString(array[i]).replaceAll("[\\[\\]]", ""));
}
You cant change array size in Java please read here once it is created. I suggest you should ask user first before creating the array
Scanner input = new Scanner(System.in);
System.out.print("Enter the dimension of the array:"); // ask user
int square= input.nextInt(); //accept user input here
int[][] int2D = new int[square][square]; //and then create the array
EDIT: You cant put the "square" variable in the print because it hasnt been created yet
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);
}
}
I'm trying to find the majority element using Boyer and Moore approach. The program should ask the user to input "n" number of lines on the first line, then there will be "n" numbers followed "n" lines as input. (Ex: user input 5 on the first line, then there will be 5 numbers followed)
Next, use Boyer and Moore approach to find the majority element of an input array. If the majority element doesn't exist in the input array, then execute -1. My program output shows 0 no matter what input I entered. Would you please check it and correct my program?
Output example:
4
12
12
1
12
12
/Or: 3 11 2 13 -1
public static void main (String[]args)
{
int a[] = new int [1000000];
Scanner sc = new Scanner (System.in);
// User input n number of lines
int numberOfLine = sc.nextInt();
//Loop to have n elements as input
for (int i = 1; i<= numberOfLine; i++)
{
a[i] = sc.nextInt();
}
// Call method to display majority element
getMajorityElement(a);
sc.close();
}
//Method to Find M.E using Boyer & Moore approach
public static void getMajorityElement(int [] array)
{
int majorityElement = array[0];
int count = 1;
for (int index = 1; index<array.length; index++)
{
if(majorityElement==array[index])
{
count++;
}
else if(count==0)
{
majorityElement = array[index];
count = 1;
}
else
{
count --;
}
}
// Check if candidate M.E occur more than n/2 times
count = 0;
for (int index = 0; index<array.length; index++)
{
if(array[index]==majorityElement)
{
count++;
}
}
if (count > array.length/2)
{
System.out.println(majorityElement);
}
else
{
System.out.println("-1");
}
}
The reason you get this behavior is that your array of 1,000,000 elements has a majority element of zero: only the initial three or four items are set, while the rest of the items are occupied by zeros - the default value of an int in Java.
Fix this problem by allocating at size once the length is entered. You also need to fix the code that reads input to make sure that the data ends up at indexes 0..numberOfLine-1:
Scanner sc = new Scanner (System.in);
// User input n number of lines
int numberOfLine = sc.nextInt();
int a[] = new int [numberOfLine];
//Loop to have n elements as input
for (int i = 0 ; i < numberOfLine ; i++) {
a[i] = sc.nextInt();
}
I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}
I would like to read a file which is in the form of a matrix, so i tried reading a file put it in String arraylist and then converted to integer array. Now I need a 2D integer array. Can anyone help? Is there any better way to do this.
public class readMat {
private static ArrayList<String> list = new ArrayList<String>();
public static void main (String[] args)
{
// read file and put in arraylist
try
{
Scanner s = new Scanner(new File("link_info_test.txt"));
while (s.hasNext())
{
list.add(s.next());
}
}
catch (Exception e)
{
e.printStackTrace();
}
String[] stockArr = new String[list.size()];
stockArr = list.toArray(stockArr);
int[] sum= Convert(stockArr);
}
// convert string arraylist to integer 1 dimensional array private static int[] Convert(String[] stockArr)
{
if (list != null)
{
int intarray[] = new int[stockArr.length];
for (int i = 0; i < stockArr.length; i++)
{
intarray[i] = Integer.parseInt(stockArr[i]);
}
return intarray;
}
return null;
}
}
Let's say you have temperature data for each day of the week for 10 weeks (that is 70 pieces of data). You want to convert it to a 2d array with rows representing weeks and columns representing days. Here you go:
int temp[70] = {45, 43, 54, ........}
int twoD[30][7]
for(int i=0; i < 70; i++) {
twoD[i / 7][i % 7] = temp[i]
}
That's it.
After the line
int[] sum= Convert(stockArr);
you have your entire file in a 1D array of integers. At this point, you have to determine the width and height of the 2D array.
Let's say you want the 2D array to have 3 rows and 4 columns as an example. Do this:
int[][] int_table = new int[3][4];
for(int j = 0; j < 3; j++)
{
for(int i = 0; i < 4; i++)
{
int_table[j][i] = sum[j * 4 + i];
}
}
The equation I'm using within sum's index is a conversion function that goes from 1D to 2D coordinates. Starting at both j and i being equal to 0, sum[j * 4 + i] = sum[0 * 4 + 0] = sum[0]. The variable i would increment by one at the next step, and we would have sum[0 * 4 + 1] = sum[1]. At the end of the row, i would reset to 0 and j would increment by 1. At that point, we would have sum[1 * 4 + 0] = sum[4], or sum's fifth element. This makes sense if you consider the first four elements as those of the first row. now that we're on a new row, we can fill it with the next four. The "four" that I've been mentioning is the width of the row that we defined earlier while declaring the 2D array.
Keep in mind that the 2D array's width and height can't multiply together to be larger than the total number of integers in the 1D array. You'll get an IndexOutOfBoundsException if you try to read beyond that size.
Assuming that each entry of your String array consists of some integers, separated by some delimiter (comma, dot, hyphen, etc), then you can use the String.split() method. For instance, if your delimiter is a comma, then you would do something like this:
String Integer1;
String Integer2;
String[] TotalString;
TotalString = stockArr[i].Split(",");
Integer1 = TotalString[0];
Integer2 = TotalString[1];
Then just parse the Strings into integers and put them into your array.
If i understood, your question correctly you want to convert 1D array to 2D array ... You can use following method
public static int[][] convertArrayTo2DArray(final int[] _1darray) {
int[][] _2dArray = null;
int size = _1darray.length / 2;
if (_1darray.length % 2 == 0) {
_2dArray = new int[2][size];
} else {
_2dArray = new int[3][size];
}
int index = 0;
outter: for (int i = 0; i < _2dArray.length; i++) {
for (int j = 0; j < _2dArray[i].length; j++) {
if (index == _1darray.length) {
break outter;
}
_2dArray[i][j] = _1darray[index];
index++;
}
}
return _2dArray;
}
Basically, I need to prompt the user for the rows and columns of an array without asking how many rows and columns there are. How do I improve the following code to do that?
System.out.println("Please input the first set of integers separated by spaces" );
String givenSet1 = console.readLine();
set1 = givenSet1.split(" ");
set1Values = new int[set1.length];
for(int i = 0; i < set1.length; i++)
{
set1Values[i] = Integer.parseInt(set1[i]);
}
while(counter <= set1Values.length)
{
numbers = new int[set1Values.length][];
numbers[counter] = set1Values[counter];
}
for(int a = 0; a < set1Values.length; a++)
{
System.out.println("Please input the set of integers that are to be associated with element " + a + ", separated by spaces" );
String givenSet2 = console.readLine();
set2 = givenSet2.split(" ");
set2Values = new int[set2.length];
numbers[a] = new int[set2Values.length];
System.out.println(numbers[a]);
for(int b = 0; b < set2Values.length; b++)
{
}
}
You can use Array.length() function to return number of elements in an array.
Your question is unclear and it is difficult to understand what you are trying to do from your code but I took a shot in the dark...
It seems as if you want to create a two dimensional array based on the user's input. The total amount of numbers inputted by the user would define the amount of columns in the array, with the user providing a set integers to store as associated numbers for each of those columns. The result would be a two dimensional array as long as the user always entered the same amount of numbers to associate with each column, but just incase I coded it to create a jagged array.
Code:
import java.util.Scanner;
public class Create2DArray {
public static void main(String[] args)
{
int[][] jaggedArray; //declare 2D array
String[] userInput; //declare array for user input
String[] userInput2; //declare array for ints to associate with first input
Scanner input = new Scanner(System.in); //scanner to read
System.out.println("Please input the first set of integers separated by spaces: " );
userInput = input.nextLine().split(" "); //parsing first set of string input
jaggedArray = new int[userInput.length][]; //create 2D array based on no. of columns defined in first set of user input
// array elements will be referenced by x and y, like coordinates.
for (int x = 0; x < jaggedArray.length; x++) //cycle through first set of numbers to prompt for associate numbers
{
System.out.println("Please input the set of integers that are" +
"to be associated with element " + userInput[x] + ", separated by spaces: " );
userInput2 = input.nextLine().split(" "); //parse and store the set to be associated with userInput[x]
jaggedArray[x] = new int[userInput2.length + 1]; //create a new int array in column x of jagged array, +1 to hold userInput[x] then associated values
for (int y = 0; y < jaggedArray[x].length; y++) // cycle through the new array # column x
{
if (y == 0)
jaggedArray[x][y] = Integer.parseInt(userInput[x]); //if y = 0 then copy the "column header" first
else
jaggedArray[x][y] = Integer.parseInt(userInput2[y-1]); // else copy the new elements at position y-1 due to jagged array being +1 more than userInput2 array
}
}
System.out.println();
for (int x = 0; x < jaggedArray.length; x++) //cycling through the array to print it all
{
System.out.print("For integer: " + jaggedArray[x][0] +
" the following integers are associated with it. ");
for (int y = 1; y < jaggedArray[x].length; y++)
{
System.out.print(jaggedArray[x][y] + " ");
}
System.out.println();
}
}
}
Next time please try to provide more information about your desired end results as well as more complete example code. It would be slightly easier to understand your code and requirements if we knew certain things such as what type of objects some of the variables in your example were. The more information the better.
Hopefully this won't be too hard to follow, and it's what you actually wanted.