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.
Related
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
Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}
I can't get Collections.rotate to work. When I enter qwerty into userInputCharacters and run this code, it just ends up outputting qwerty again. Any recommendations?
Collections.rotate(Arrays.asList(userInputChararacter), 2);
for(int index = 0; index <= characterAmount - 1; index++)
System.out.print(userInputChararacter[index]);
UPDATE: Here is my full program.
import java.util.*;
public class WrapAround
{
public static void main(String[] args) throws java.io.IOException
{
//Create a scanner to read the users input.
Scanner userInput = new Scanner(System.in);
//Get the amount of characters the user wants to input.
System.out.println("How many character do you want to enter?");
int characterAmount = userInput.nextInt();
//Get and put the user's characters into an array.
System.out.println("Please enter your " + characterAmount + " characters.");
String userInputString;
userInputString = userInput.next();
char[] userInputChararacter = new char[characterAmount];
for(int index = 0; index <= characterAmount - 1; index++)
userInputChararacter[index] = userInputString.charAt(index);
//Get what number character the user wants to start with.
System.out.println("Which character do you want to start with?");
int startingCharacterIndex;
startingCharacterIndex = userInput.nextInt();
startingCharacterIndex--;
//Give the user their characters in order.
System.out.println("Here are all your characters, beginning with number " + (startingCharacterIndex + 1) + ".");
userInputChararacter = Collections.rotate(Arrays.asList(userInputChararacter), (startingCharacterIndex - 1));
for(int index = 0; index <= characterAmount - 1; index++)
System.out.print(userInputChararacter[index]);
/*
for(int index = startingCharacterIndex; index <= characterAmount - 1; index++)
System.out.print(userInputChararacter[index]);
for(int index = 0; index <= startingCharacterIndex - 1; index++)
System.out.print(userInputChararacter[index]);
*/
System.out.println();
}
}
The reason it doesn't work is that Arrays.asList(new char[]{'q','u','e'}) will create a list of size 1, not 3. It's different from Arrays.asList('q','u','e') where elements will be correctly autoboxed to Character and list of size 3. Consequently your rotation is not going to change anything.
You should create your own List<Character> instance by adding elements or creating a wrapper class for the underlying array.
Or, perhaps easier to eliminate char altogether and represent even single chars as Strings.
Im very new to Java, and I'm trying to write a program using arrays and arraylists where you enter in however many values you want, and it outputs how many values are between two parameters using asterisks.
ex:
[5,14,23,43,54,15]
1-10: *
11-20: **
21-30:*
31-40:
41-50:*
51-60: *
And so on. Here's what I have so far, but I'm getting errors and out of bounds exceptions. Can anyone say whether or not I'm on the right track or not? Any help is appreciated!
package arraylists;
import java.util.ArrayList;
import java.util.Scanner;
public class numberslists {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
ArrayList numbers = new ArrayList();
int [] number = new int[10];
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
System.out.println("enter in those numbers please");
for (x=0; x < count; x++){
number[x] = reader.nextInt();
numbers.add(number[x]);
}
System.out.println(numbers);
int x10 = numbers.indexOf(number[x] < 10);
numbers.remove(x10);
System.out.println(numbers);
}
}
In short, as Lahiru said, you need to change the line: int x10 = numbers.indexOf(number[x] < 10);
The main problem with your code is the expression number[x] < 10 which returns a boolean (true or false). Therefore the numbers.indexOf(number[x] < 10) is going to return 1 or -1.
Finally, when the code gets to numbers.remove(x10); and if is -1 (for false) then you will get java.lang.ArrayIndexOutOfBoundsException because there is no way to do a numbers.remove(-1);. See the documentation.
There is room for improvement in your code. Below is a suggestion to what you could do. But just look at this suggestion after you try fixing your own code (so you can have a better learning experience).
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CountOcurrancesInArray {
private static Scanner reader = new Scanner(System.in);
private static List<Integer> numbers = new ArrayList<Integer>(); // Use generics when possible: <Integer>
public static void main(String[] args) {
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
System.out.println("enter in those numbers please");
for (x=0; x < count; x++){
// I don't see a need for this line. number[x] = reader.nextInt();
numbers.add(reader.nextInt());
}
System.out.println(numbers);
int[] comparingNumbers = requestComparingNubers();
System.out.println("You entered these numbers: " + numbers);
String matchingNumbers = checkForNumbersInTheList(comparingNumbers);
System.out.println("Numbers between " + comparingNumbers[0] + "-" + comparingNumbers[1] + ":" + matchingNumbers);
}
/**
* Counts how many entries are in the list between 'comparingNumbersInput'
* #param comparingNumbersInput
* #return number of entries as asterisks "*"
*/
private static String checkForNumbersInTheList(int[] comparingNumbersInput) {
String result = "";
for(Integer i : numbers) {
if (i >= comparingNumbersInput[0] && i <= comparingNumbersInput[1]) {
result += "*";
}
}
return result;
}
/**
* Asks the user to enter 2 numbers to be compared against the all the numbers in the list.
* #return returns a int[2] sorted ascendingly
*/
private static int[] requestComparingNubers() {
int [] result = new int[2];
System.out.println("Counting how many numbers there are in between x and y.");
System.out.println("What is the first number?");
result[0]=reader.nextInt();
System.out.println("What is the second number?");
result[1]=reader.nextInt();
// Sort comparingList
if (result[0] > result[1]) {
int temp = result[1];
result[1] = result[0];
result[0] = temp;
}
return result;
}
}
Declare Array after getting count from user.
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
int [] number = new int[count];
Also have a look at the Line of code that caused the error.
To me, this makes more sense as a Map, where you store a counter for each range found in the array of inputs. Now that means you have to first figure out what the range if that each input fits within, then update your counter that matches the range. Since we have to calculate the range as a String for output and you want the counter to be represented as a String of asterisk anyway, Storing the range as a String for the Map.key and the counter as a String of asterisk as the Map.value works nicely.
Here is some example code that does just that, where numbers is the ArrayList of the original values input by a user.
//Declare a Map that stores the range as a String ( "01-10") as the key
//and a counter in astericks as the value
Map<String,String> counters = new HashMap<>();
//Loop over the array ov values
for(Integer value: numbers){
//For each value calculate the diviser by diving by 10
Integer lowRange = value / 10;
//To get the low range, multiply the diviser by 10 and add 1
lowRange = (10 * lowRange) + 1;
//The high range is 9 mor ethan the low range
Integer highRange = lowRange + 9;
//Finally calcualte what the range looks like as a String
//Note that it handles "1" as a special case by prepending a "0" to make the value "01"
String rangeString = ((lowRange < 10) ? "0" + lowRange : lowRange) + "-" + highRange;
//Now check the map to see if the rangeString exists as a key, meaning
//we have previously found a value in the same range
String count = "";
if(counters.containsKey(rangeString)){
//If we found the same range, get the previous count
count = counters.get(rangeString);
}
//Place the count back into the map keyed off of the range and add an asterick to the count String
counters.put(rangeString, count + "*");
}
//Finally iterate over all keys in the map, printing the results of the counters for each
for(String range: counters.keySet()){
System.out.println(range + " " + counters.get(range));
}
As an example of output, if the user inputs the values:
[5,14,23,43,54,15,41]
The output would be:
01-10 *
11-20 **
41-50 **
51-60 *
21-30 *
Java arrays are zero-based index. For example, if you declare an array with 10 elements, the index of these elements will be from 0 to 9.
In your code snippet below, when java finishes the "for" loop
for (x=0; x < count; x++){
number[x] = reader.nextInt();
numbers.add(number[x]);
}
The value of x variable will be equal to the number of elements you have inputted to the number array (x = count).
So, when you get the element at x position as below:
int x10 = numbers.indexOf(number[x] < 10);
If x < 10, you will get -1 for x10. Then an exception will occur at:
numbers.remove(x10);
If x >= 10, an ArrayIndexOutOfBoundsException will occur at number[x]
Yet another Homework question
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
public class numberlists {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
LinkedList < Integer > numbers = new LinkedList < Integer > ();
//int [] number = new int[10]; no need, and the input is variable size
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
System.out.println("enter in those numbers please");
Map < Integer, Integer > range_numbers = new HashMap < Integer, Integer > ();
for (x = 0; x < count; x++) {
//number[x] = reader.nextInt(); no need
numbers.add(reader.nextInt());
int rs = ((int) numbers.getLast() / 10) * 10 + 1; //range start for number i.e rs(15)=11
if (!range_numbers.containsKey(rs)) { //check if has number in that range
range_numbers.put(rs, 1);
} else { //gets the prev count, add 1 and stores back for range
range_numbers.put(rs, range_numbers.get(rs) + 1);
}
}
System.out.println(numbers);
Map < Integer, Integer > sortedpairs = new TreeMap < Integer, Integer > (range_numbers); // need to sort
for (Map.Entry < Integer, Integer > pair: sortedpairs.entrySet()) {
System.out.printf("\n%d-%d: %s", pair.getKey(), pair.getKey() + 9,
new String(new char[pair.getValue()]).replace("\0", "*"));
//little trick to repeat any string n times
}
}
}
Enjoy.
I want to make a list going to n numbers depending on user input. I then want to put a second number in each place and print the entire table. As for testing I have tried with a length 4 and numbers 1,2,3,4 but I get a error: ArrayIndexOutOfBounds. I wanted it to print 1,2,3,4.
Scanner keyboard = new Scanner (System.in);
System.out.println("Whats the length of the table?");
int lengde = keyboard.nextInt();
int[] minTabell = new int[lengde];
for (int i =1; i <= lengde+ 1; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
System.out.println(minTabell);
keyboard.close();
Indexes in Java arrays are 0-based, while your for-loop starts from 1. So,
for (int i =1; i <= lengde+ 1; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
should be
for (int i =0; i < lengde; i++) {
// ^ ^^^^^^^^
System.out.println((i+1) + (" give a number"));
// ^^^
minTabell[i] = keyboard.nextInt();
}
As for printing the content of the array, I suggest you use
for (int i : minTabell)
System.out.println(i);
In Java array indexing starts at 0. The first element is positioned at minTabel1[0]. Your for-loop runs from 1 to lengde + 1, which means that you will try to fill a position outside of the array.
The first element of an array has the index 0. The last valid index of your array is lengde-1.
Try this:
for (int i=0; i < lengde; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
To print the array, i suggest the following:
System.out.println(Arrays.toString(minTabell));