Collections.rotate not working - java

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.

Related

How to create a system that turns an input into a combination of numbers in java

I'm trying to create a system that takes a key from the user. e.g. 'ab'. Convert the letters into their position on the alphabet, (ab = 1, 2) and then add them together. So an example would look like.
Input: abc
Output: 6
This is what I've tried so far.
String alphabet = ("abcdefghijklmnopqrstuvwxyz");
System.out.println("Please input a key");
Scanner key = new Scanner(System.in);
String keyInput = key.nextLine();
for (int i = 0; i < keyInput.length(); i++) {
char letter = keyInput.charAt(i);
int[] alphLetter = new int[alphabet.indexOf(letter)];
System.out.println(alphLetter[i]);
You can get a character's position in the alphabet by subtracting 'a' from it (and adding one, since you want it one-based). I think the easier approach would be to stream the characters of the string, convert them to their positions and sum them:
int result = key.chars().map(c -> c - 'a' + 1).sum();
It's not clear if alphabet will always be in the standard order or if it could be shuffled?
If you're just dealing with the standard alphabet you can do something simple like this:
int sum = 0;
for(int i=0; i<keyInput.length(); i++)
{
sum += 1 + keyInput.charAt(i) - 'a';
}
System.out.println("Sum: " + sum);
If the alphabet could be shuffled you'll first need to build a map of character positions. You can use a simple array for this.
String alphabet = "mgpqrhivwxjklostufncbyzade";
int[] charPos = new int[alphabet.length()];
for(int i=0; i<alphabet.length(); i++)
charPos[alphabet.charAt(i)-'a'] = i + 1;
int sum = 0;
for(int i=0; i<keyInput.length(); i++)
{
sum += charPos[keyInput.charAt(i)-'a'];
}
System.out.println("Sum: " + sum);

Java: Print out each number in an array without printing its an repeats of that number?

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 + " ");
}
}

How to print out even-numbered indexes for arrays in Java?

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] + " ");
}
}
}

Tables trouble. I need help to make them

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));

using two dimensional integer arrays

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.

Categories