This question already has answers here:
Cast Double to Integer in Java
(19 answers)
Closed 7 years ago.
I am having a ArrayList<String> abc in which I am getting this value [64.3, 25.1, 44.3, 34.2, 6.4, 48.5, 35.5, 59.5, 54.6, 26.6, 11.2, 50.3, 25.1]
Now I want to extract the integer values from it such as 64,25,44,34,6,48,35,59,54,26,11,50,25 and put these values in an integer array int[] cab
How can I get this? How to remove the decimal and after decimal values from it?
Here are three different (but similar) ways of doing it, depending on Java version and/or preferences:
ArrayList<String> abc = new ArrayList<>(Arrays.asList(
"64.3", "25.1", "44.3", "34.2", "6.4", "48.5", "35.5",
"59.5", "54.6", "26.6", "11.2", "50.3", "25.1" ));
System.out.println("abc = " + abc);
// Loop (all Java versions)
int[] cab1 = new int[abc.size()];
for (int i = 0; i < cab1.length; i++)
cab1[i] = (int)Double.parseDouble(abc.get(i));
System.out.println("cab1 = " + Arrays.toString(cab1));
// Java 8 stream with lambda expression
int[] cab2 = abc.stream()
.mapToInt(v -> (int)Double.parseDouble(v))
.toArray();
System.out.println("cab2 = " + Arrays.toString(cab2));
// Java 8 stream with method references
int[] cab3 = abc.stream()
.map(Double::valueOf)
.mapToInt(Double::intValue)
.toArray();
System.out.println("cab3 = " + Arrays.toString(cab3));
Output
abc = [64.3, 25.1, 44.3, 34.2, 6.4, 48.5, 35.5, 59.5, 54.6, 26.6, 11.2, 50.3, 25.1]
cab1 = [64, 25, 44, 34, 6, 48, 35, 59, 54, 26, 11, 50, 25]
cab2 = [64, 25, 44, 34, 6, 48, 35, 59, 54, 26, 11, 50, 25]
cab3 = [64, 25, 44, 34, 6, 48, 35, 59, 54, 26, 11, 50, 25]
Try This :
Integer cab[] = new Integer[abc.size()];
cab= abc.toArray(cab);
//iterating array
for (Integer cabs: cab) {
System.out.println("cab= " + cabs);
}
Simply iterate:
int[] cab = new int[abc.size()];
for(int i = 0; i < cab.length; i++){
cab[i] = (int)Float.parseFloat(abc.get(i));
}
In Java 8:
int[] cab = abc.stream()
.map(Double::valueOf)
.mapToInt(Double::intValue)
.toArray();
use this code
Iterator itr = al.iterator();
while(itr.hasNext()) {
String s1=itr.next().toString();
Double d=new Double(s1);
int s2=d.intValue();
System.out.print(s2 + " ");
}
string to double
double to int
for(int i = 0 ; i < abc.size(); ++i) {
tmp = Double.parseDouble(abc.get(i));
cab[i] = (int)tmp;
System.out.println(cab[i]);
}
ArrayList<Integer> newList = new ArrayList<Integer>(stringsList.size());
for (String myInt : strings){
int intVal = (int)Double.parseDouble(myInt);
newList.add(intVal);
}
where stringsList is your Arraylist
Related
import java.util.Random;
public class Practice_assignment {
public static void main(String[] args){
int[] winning_numbers = {0,0,0,0,0,0,0,0,0,0} ;
//The i++ for the first loop is in the second loop. I was trying to ensure it only goes to
the next value of the loop once a unique value has been gotten.
for (int i=0; i<10;){
int max = 99;
int min = 1;
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
for (int j=0;j<=i;j++){
if (j<i && winning_numbers[j]==randomNum){
break;
}
else if (j==i && i<10){
winning_numbers[i] = randomNum;
System.out.println(winning_numbers[i]+" ");
i++;
}
}
}
}
}
If I understood correctly what you are trying to achieve, I think you could use something like this:
public class RandomNumbers {
public static void main(String[] args) {
int[] winning_numbers = {0,0,0,0,0,0,0,0,0,0} ;
Random random = new Random();
for(int i = 0; i < winning_numbers.length; i++) {
OptionalInt generatedInt = random.ints(1, 0, 100).findFirst(); // generates a stream of 1 number between 0 and 99 and gets the first (and only) one generated
while (contains(winning_numbers, generatedInt)) {
generatedInt = random.ints(1, 0, 100).findFirst(); // while the generated number is already in the array, generate a new one
}
winning_numbers[i] = generatedInt.getAsInt();
}
System.out.println(Arrays.toString(winning_numbers));
}
// this method will check if the given array already contains the generated int
private static boolean contains(int[] arr, OptionalInt generatedInt) {
return Arrays.stream(arr).anyMatch(number -> generatedInt.getAsInt() == number);
}
}
I ran it a couple of times and here are some outputs I generated with this code:
[52, 54, 21, 62, 47, 13, 94, 36, 82, 25]
[35, 37, 16, 81, 22, 71, 17, 94, 56, 8]
[51, 50, 80, 62, 18, 88, 1, 53, 44, 79]
[16, 95, 18, 66, 31, 4, 1, 55, 52, 26]
[4, 11, 65, 68, 22, 76, 95, 67, 35, 92]
[49, 87, 34, 88, 71, 57, 12, 76, 70, 78]
It appears you want to generate an array of winning_numbers. Here is one ways to do it.
create a helper method to look for duplicate numbers and return true if a duplicate is found.
then iterate over the array checking for the current random number and adding it if unique.
note that min, max, and rand should be initialized outside the loop.
Random rand = new Random();
int[] winning_nummbers = new int[10];
int max = 99;
int min = 1;
for (int i = 0; i < 10;) {
int randomNum = rand.nextInt((max - min) + 1) + min;
// if does not contain a duplicate, then assign
if (!contains(winning_numbers, randomNum)) {
winning_numbers[i++] = randomNum;
}
}
System.out.println(Arrays.toString(winning_numbers));
Prints something like this.
[46, 91, 5, 2, 42, 58, 74, 24, 53, 36]
The helper method.
public static boolean contains(int[] array, int v) {
for (int i = 0; i < array.length; i++) {
if (array[i] == v) {
return true;
}
}
return false;
}
If you want to use streams you can do it like so using a Random instance.
stream values form min to max inclusive.
drop duplicates with distinct
limit(10) limits to 10 values.
put them in an array
int[] winning_numbers = rand.ints(min,max+1)
.distinct()
.limit(10)
.toArray();
I've got List<List<Integer>> with several objects. Each of inner element contains randomly shuffled indexes, for example (it's only a part of indexes).
[1, 4, 5, 2, 0, 3, 6]
[4, 2, 5, 3, 1, 6, 0]
[0, 3, 6, 1, 2, 4, 5]
I've got also an array with some values (int[][] array)
And I need to do a loop for each element to get value from indexes and move forward by 1 index and when I reach last index I need to get value from this index and the first one. After that loop end and sum values. It might look difficult but pictrue will show what I mean. But I dont know how to do this (loop is required for each element, I'm gonna have a massive List of List<Integer> inside and every object gonna have multiple indexes.
I'm reading data from file and write it to array
List<String> result = new ArrayList<>();
int[][] array = new int[][]{};
try (Scanner sc = new Scanner(theFile)) {
while (sc.hasNext()) {
result.add(sc.nextLine());
}
int max = Integer.parseInt(result.get(0).trim());
array = new int[max][max];
for (int i = 1; i < result.size(); i++) {
String[] tmp = result.get(i).trim().split(" ");
for (int j = 0; j < tmp.length; j++) {
array[i - 1][j] = Integer.parseInt(tmp[j]);
array[j][i - 1] = array[i - 1][j];
}
}
List<List<Integer>> collectionWithSubjects = new ArrayList<>();
for (int i = 0; i < 40; i++) {
List<Integer> sub = new ArrayList<>();
sub = sequence(0,51);
Collections.shuffle(sub);
collectionWithSubjects.add(sub);
}
You've done a decent job of explaining the problem. It sounds like you're getting caught up on trying to do everything in a single for loop, rather than breaking down the problem into two pieces.
This is your statement:
I need to do a loop for each element to get value from indexes and move forward by 1 index and when I reach last index I need to get value from this index and the first one.
This can be divided into two pieces:
I need to do a loop for each element to get value from indexes and move forward by 1 index
This is a for loop that iterates from 0 -> size() - 1. If we go from 0 -> size() we get an overflow.
for(int i = 0; i < list.size() - 1; i++) {
int firstCoord = list.get(i);
int secondCoord = list.get(i+1);
//do stuff
}
when I reach last index I need to get value from this index and the first one.
This is getting the last element and the first element.
int firstCoord = list.get(list.size() - 1);
int secondCoord = list.get(0);
Combine both together and you've got the framework for getting the coordinates.
for(int i = 0; i < list.size() - 1; i++) {
int firstCoord = list.get(i);
int secondCoord = list.get(i+1);
//do stuff
}
int firstCoord = list.get(list.size() - 1);
int secondCoord = list.get(0);
//do stuff
I'll leave the actual implementation up to you.
// given array
int[][] array = [[31, 21, 34, 22, 67, 14, 41],
[17, 42, 31, 57, 26, 23, 52],
[5, 92, 52, 52, 31, 22, 62],
[17, 42, 31, 57, 26, 23, 52],
[5, 92, 52, 52, 31, 22, 62],
[31, 21, 34, 22, 67, 14, 41],
[5, 92, 52, 52, 31, 22, 62]];
// given list of lists of randomly-ordered indices
List<List<Integer>> indexList = Arrays.toList([
Arrays.toList([1, 4, 5, 2, 0, 3, 6]),
Arrays.toList([4, 2, 5, 3, 1, 6, 0]),
Arrays.toList([0, 3, 6, 1, 2, 4, 5])
]);
// first, create a place to store the sums corresponding to each random list
List<Integer> sums = new ArrayList<Integer>();
// iterate over each of the lists of random elements
for(List<Integer> randomIndices: indexList){
// create a running sum for this list
int randomSum = 0;
// iterate over each element of the randomized index list
for(int j = 0; j < randomIndices.size(); j++){
// read the current and next index (using modulo to wrap around)
current = randomIndices.get(j);
next = randomIndices.get((j + 1) % randomIndices.size());
// add the relevant index in array to the running sum
randomSum += array[current][next];
}
// add the recorded randomSum to the sums list.
// Its index is the same as the random list we just iterated over
sums.add(randomSum);
}
System.out.println(sums);
You may iterate over the alues of each List<Integer> then look them by pair (use % to go back at the beginning) and use them to index the 2d array
for (List<Integer> l : list) {
int sum = 0;
for (int i = 0; i < l.size(); i++) {
int p1 = l.get(i % l.size());
int p2 = l.get((i + 1) % l.size());
sum += values[p1][p2];
}
System.out.println(sum);
}
With this as initial data
List<List<Integer>> list = List.of(List.of(1, 4, 5, 2, 0, 3, 6), List.of(4, 2, 5, 3, 1, 6, 0));
int[][] values = new int[][]{new int[]{31, 21, 34, 22, 67, 14, 41}, new int[]{17, 42, 31, 57, 26, 23, 52}, new int[]{5, 92, 52, 52, 31, 22, 62},
new int[]{17, 42, 31, 57, 26, 23, 52}, new int[]{5, 92, 52, 52, 31, 22, 62}, new int[]{31, 21, 34, 22, 67, 14, 41}, new int[]{5, 92, 52, 52, 31, 22, 62},};
it'll print
253
262
The question is to write a program which takes two arrays of 10 integers each, a and b. c is an array with 20 integers. The program should put array a and b into the array c, the first 10 integers of c from array a, the latter 10 from b. Then the program should display c. This is the code i have so far. It prints the values from arrayA into arrayC but i dont know how to print the values from arrayB into arrayC without overriding the information already in arrayC (arrayB).
public class questionTwo
{
public static void main(String[] args)
{
int [] arrayA = {31, 14, 5, 12, 50, 80, 100, 29, 58, 57};
int [] arrayB = {9, 13, 156, 78, 36, 46, 86, 98, 63, 2};
int [] arrayC = new int [20];
for (int i = 0; i < arrayA.length; i++)
arrayC[i] = arrayA[i];
for (int i = 0; i < arrayB.length; i++)
{
int element = 9;
arrayC[element] = arrayB[i];
element++;
}
System.out.println("The values of ArrayC are: ");
for(int val : arrayC)
{
System.out.println(val);
}
}
}
Before explaining how you might fix your current code, I would first suggest you create arrayC using the lengths of arrayA and arrayB (here that has the same practical result, but it has the advantage that you can add more elements to arrayA or arrayB without modifying the code). Next, in real code, I would use System.arraycopy to perform the copies. And use Arrays.toString(int[]) for printing. Like,
int[] arrayA = { 31, 14, 5, 12, 50, 80, 100, 29, 58, 57 };
int[] arrayB = { 9, 13, 156, 78, 36, 46, 86, 98, 63, 2 };
int[] arrayC = new int[arrayA.length + arrayB.length];
System.arraycopy(arrayA, 0, arrayC, 0, arrayA.length);
System.arraycopy(arrayB, 0, arrayC, arrayA.length, arrayB.length);
System.out.println(Arrays.toString(arrayC));
As for your original code, use arrayA.length and i to get the correct offset. Like,
int[] arrayC = new int[arrayA.length + arrayB.length];
for (int i = 0; i < arrayA.length; i++) {
arrayC[i] = arrayA[i];
}
for (int i = 0; i < arrayB.length; i++) {
arrayC[i + arrayA.length] = arrayB[i];
}
You were really close! Your second loop initializes element to 9 every time, while you should only assign it to 10 once at the beginning:
int element = 10;
for (int i = 0; i < arrayB.length; i++)
{
arrayC[element] = arrayB[i];
element++;
}
Make your function dynamic while you need to add more item into your arrays. I did not test yet, but I hope it work.
public class questionTwo
{
public static void main(String[] args)
{
int [] arrayA = {31, 14, 5, 12, 50, 80, 100, 29, 58, 57};
int [] arrayB = {9, 13, 156, 78, 36, 46, 86, 98, 63, 2};
int [] arrayC = new int [arrayA.length + arrayB.length];
for (int i = 0; i < arrayA.length; i++)
arrayC[i] = arrayA[i];
int element = arrayA.length;
for (int i = 0; i < arrayB.length; i++)
{
arrayC[element+i] = arrayB[i];
}
System.out.println("The values of ArrayC are: ");
for(int val : arrayC)
{
System.out.println(val);
}
}
}
The second loop is wrong. You can use the follow code:
int [] arrayA = {31, 14, 5, 12, 50, 80, 100, 29, 58, 57};
int [] arrayB = {9, 13, 156, 78, 36, 46, 86, 98, 63, 2};
int [] arrayC = new int [20];
System.arraycopy(arrayA, 0, arrayC, 0, arrayA.length);
System.arraycopy(arrayB, 0, arrayC, arrayA.length, arrayB.length);
System.out.println("The values of ArrayC are: ");
for(int val : arrayC) {
System.out.println(val);
}
Your second loop is incorrect because you are setting element to 9 within the loop each time; thus, its value is always reset upon beginning the next iteration. You could move it outside the loop to achieve the result you're looking for. Also, I'd recommend constructing arrayC based on the lengths of arrayA and arrayB, that way you can combine array's of any length.
In addition, I'd also recommend moving the code to combine the arrays to a method to keep things clean and reusable for future endeavors.
public class questionTwo {
private static int[] combineArrays(int[] arrayA, int[] arrayB) {
int[] arrayC = new int[arrayA.length + arrayB.length];
int idx = 0;
for (int x : arrayA) {
arrayC[idx] = x;
idx++;
}
for (int x : arrayB) {
arrayC[idx] = x;
idx++;
}
return arrayC;
}
public static void main(String[] args) {
int[] arrayA = {31, 14, 5, 12, 50, 80, 100, 29, 58, 57};
int[] arrayB = {9, 13, 156, 78, 36, 46, 86, 98, 63, 2};
int[] arrayC = combineArrays(arrayA, arrayB);
System.out.println("The values of ArrayC are: ");
for(int val : arrayC) {
System.out.println(val);
}
}
}
Also, it is often considered a poor practice to use Java's primitive arrays. Check out List and related objects for more flexible and full-featured options.
I'm using the code below to permute a string according to a specific table.
public static void main(String[] args) {
int[] IP = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 };
String text = "00000001 00100011 01000101 01100111 10001001 10101011 11001101 11101111".replace(" ", "");
text = Permute(text,IP);
System.out.println(text);
}
public static String Permute(String text,int [] table )
{
String keys = "0" + text;
StringBuilder sb = new StringBuilder ();
for (int i = 1 ; i <= table.length; i++)
{
sb.append(keys.charAt(table[i-1]));
}
return sb.toString();
}
UPDATED:Any idea to create another method to get the original string back? Something like :
public static String GetoriginalText(String TextafterPermutation,int [] table )
You can use a chararray that you populate according to your table mapping
public static String RePermute(final String text, final int[] table) {
final String keys = text;
char[] chararray = new char[table.length];
for (int i = 0; i < keys.length() && i < table.length; i++) {
chararray[table[i]-1] = keys.charAt(i);
}
return new String(chararray);
}
This code is iterating through your text, and writes the char of the current iteration at the chararray place specified in your table.
Note: There are some problems in your code that i left untouched.
For example I really don't get why you allways put "0" in front of your text.
Also you might want to handle situations where the passed text and table differ in length.
Edit: I removed the part where you add "0" in front of your passed text and instead changed the loop to start at i=0 instead i=1.
You can simplify your algorithm to use array of chars instead of StringBuilder:
public static String permute(String text,int [] table )
{
char[] chars = new char[table.length];
for (int i = 0 ; i < table.length; i++) {
chars[i] = text.charAt(table[i]-1);
}
return new String(chars);
}
After that reverse algorithm is more obvious. You just need to make reverse assignment:
public static String undo(String text,int [] table ) {
char[] chars = new char[table.length];
for (int i = 0; i < table.length; i++)
{
chars[table[i]-1] = text.charAt(i);
}
return new String(chars);
}
In the statement text = Permute(text,IP); you are assigning reference of String object returning from Permute function, so the original reference which text variable was holding is replaced by new reference returned by Permute function.
If you want to keep the original reference which text was holding, just use any other variable like String output = Permute(text,IP);.
You could use a simple program as mentioned below:
public static String dePermute(String text, int[] table){
String keys = text;
System.out.println(table.length);
String[] str = new String[table.length];
for (int i = 1; i <= table.length; i++) {
System.out.println("Coming "+table[i - 1]);
str[table[i - 1]-1] = ""+keys.charAt(i-1);
//sb.append(keys.charAt(table[i - 1]));
}
return Arrays.toString(str).replace("[", "").replace("]", "").replace(",", "").replace(" ", "");
}
You can use the concept explained in this program. I have just reverse the process which you are doing in Permute function.
assuming your permutation table doesn't change you can do this:
public static String GetoriginalText(String TextafterPermutation,int [] table ){
char[] chars=new char[table.length];
for(int i=0;i<table.length;i++){
chars[table[i] - 1] = TextafterPermutation.charAt(i);
}
return new String(chars);
}
I have 3 arrays iX, iY, and iZ with each holding 20 integers.
iX goes up by 5, iY goes up by 3, and iZ is the sum of both.
for (int i=5; i <=iX.length; i+=5)
{
iX[i] = i;
System.out.print (i + "\n");
}
for (int j=3; j <iY.length; j+=3)
{
iY[j] = j;
}
for (int k=0; k < iZ.length; k++)
{
iZ[k] = iX[k]+iY[k];
}
When I run it I get:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
at Quiz10RTN.main(Quiz10RTN.java:61)"
Line 61 is : iX[i] = i;
I can't seem to get it to even print out 20 numbers, because it seems to be treating my limit of 20 integers as a range to stop at. Any help would be great, Thanks.
Issue is here
for (int i=5; i <=iX.length; i+=5)
^
There is no index match with iX.length in your array.
index of array start with 0, So if size of array is n, then you only have indexes from 0 to n-1.
You can use following to avoid the exception. But you need to think some other way to archive your goal.
for (int i=5; i <iX.length; i+=5)
Edit: for your comment I was trying to print out "5, 10, 15, 20, 25...etc"
You can try something like following
for (int i=0; i <iX.length; i++) {
iX[i]=(i+1)*5; // now your array become 5,10,15,...
}
You are confusing your array indices with the values you are storing in the arrays.
So, for example, if you want your iX array to contain the 20 integers 5, 10, 15,...100, your first loop should look like:
for (int i=0; i < iX.length; ++i)
{
iX[i] = (i + 1) * 5;
System.out.print (iX[i] + "\n");
}
You aren't using the array indexes properly (they must be incremental). You might also use Arrays.toString(int[]) to print your arrays. I believe you wanted something like
int[] iX = new int[20];
int[] iY = new int[20];
int[] iZ = new int[20];
int valfive = 5; // <-- our five increments.
int valthree = 3; // <-- the three increments.
for (int i = 0; i < iX.length; i++) {
iX[i] = valfive;
iY[i] = valthree;
iZ[i] = valfive + valthree;
valfive += 5; // <-- add 5
valthree += 3; // <-- add 3
}
System.out.println("Multiples of five: " + Arrays.toString(iX));
System.out.println("Multiples of three: " + Arrays.toString(iY));
System.out.println("Sums of fives and threes: " + Arrays.toString(iZ));
Output is (formatted for SO)
Multiples of five: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70,
75, 80, 85, 90, 95, 100]
Multiples of three: [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42,
45, 48, 51, 54, 57, 60]
Sums of fives and threes: [8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96,
104, 112, 120, 128, 136, 144, 152, 160]