transfer an int [] to a numeric series - java

How is it possible in java to have an int array and add all values from the array to a numerical series.
For example:
int[] num= new int[9];
for(int i=0; i<num.length; i++) {
num[i] = i;
}
and I need one integer variable like:
int a = 12345678910
copied from the array.
thx a lot in advance!

There are 2 problems in your code which you'll need to fix first:
your array index is bigger than the size of the array (11 > 9)
the number you're assigning to 'a' is too big for the integer type
You could try this as a solution:
StringBuilder numbers = new StringBuilder();
int[] num = new int[9];
for (int i = 0; i < num.length; i++) {
num[i] = i;
numbers.append(i);
}
long a = Long.valueOf(numbers.toString());
System.out.println(a);
Note that you'll still need to check that the final output of 'numbers' is not too big for a long. If it is you'll need to use a data type that can accommodate the resulting value.

It seems most natural to use the StringBuilder class, as this handles your appending 2 digit numbers most easily:
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 11; i++) {
sb.append(i);
}
int a = Integer.parseInt(sb.toString());

int a;
String aStr = "";
int[] num= new int[9];
for(int i=0; i<11; i++) {
aStr = aStr + num[i];
}
a = new Integer(aStr);

Related

How to accept integers into 2 different int arrays simultaneously and form a new array in java in the same order?

If you are accepting integers simultaneously one after another for a different array each time an int is accepted, then how do you form a third array with the digits of the 2 other arrays in the order in which they are accepted?
import java.util.Scanner;
class Integer_Acceptor
{
public static void main()
{
System.out.println("\f");
Scanner sc = new Scanner(System.in);
int a[] = new int[5];
int b[] = new int[10];
int c[] = new int[10];
System.out.println("Enter an integer into each array simultaneously");
for (int i = 0; i < 5; i++)
{
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
for (int i = 0; i < 10; i++)
{
if (i%2 != 0)
{
c[i] = a[i];
c[i+1] = b[i];
}
}
System.out.println("Array contents are");
for (int i = 0; i < 10; i++)
{
System.out.println(c[i]+"\t");
}
}
}
This is the program I made but obviously it doesn't work (ArrayOutofBounds) as the integer in array increases by 2 every time. How do I make this program give the combined integers of both arrays in the order in which they are accepted?
The idea of separating the inputs is interesting, but it seems to be giving you more problems than solutions when trying to join them together later.
Why not just accept everything into a single array, and when reading it, you test its index to see where it should go? If you have two possible uses for your numbers, odd and even positions will get you there; if three, multiples of 3 plus or minus one, and so on.
This seems to be a simpler solution, and both the input and data storage are as straightforward as can be.
The code you provided will give an ArrayOutofBounds error as you mentioned because c[10] does not exist. (In the second for loop when i = 9, you will be trying to set c[10] which does not exist).
From what I understand, you want array c to contain the following elements:
c = { a[0], b[0], a[1], b[1], a[2], b[2], a[3], b[3], a[4], b[4] }
What I did was to create two separate indices that will help navigate through array a and array b and set c[i] according to whether i was even or odd and then incrementing the respective aIndex or bIndex. I wrote this code below that works the way I described
System.out.println("\f");
Scanner sc = new Scanner(System.in);
int a[] = new int[5];
int b[] = new int[10];
int c[] = new int[10];
System.out.println("Enter an integer into each array simultaneously");
for (int i = 0; i < 5; i++)
{
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
// Fixed code snipped
int aIndex = 0;
int bIndex = 0;
for (int i = 0; i < 10; i++)
{
// even index
if(i%2 == 0){
c[i] = a[aIndex];
aIndex++;
}
else
{
c[i] = b[bIndex];
bIndex++;
}
}
////
System.out.println("Array contents are");
for (int i = 0; i < 10; i++)
{
System.out.println(c[i]+"\t");
}
Let me know if you need further clarification on how this works so I can edit in a more in-depth explanation.

I'm not able to sort the splited strings properly using comparedTo method. What can I do to correct it?

This is my code, but I know this is not right. I have written a lot of code for such a simple task.
Sample input is:
welcome
Sample output is:
com
elc
lco
ome
wel
It should print:
your first string is 'com'
and
your last string is 'wel'
Code:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int k = sc.nextInt();
int k1 = k;
int j = 0;
int t = str.length();
String [] s = new String [1000];
for (int i = t, a = 0; i >= k; i--, a++) {
s[a] = str.substring(j, k1);
j++;
k1++;
}
String[] s1 = new String[j];
for (int i = 0 ; i < j; i++) {
s1[i] = s[i];
}
for (int y = 0; y < j; y++) {
for (int z = y + 1; z < j; z++) {
if(s1[z].compareTo(s1[y]) < 0) {
String temp = s1[z];
s1[z] = s1[y];
s1[y] = temp;
}
}
}
System.out.println(s1[0]);
System.out.println(s1[1]);
}
}
Note: I split my strings, but I'm not able to arrange strings in alphabetical order, and feel that I have used a lot of arrays. Is there a better way to do this?
You can
reduce the number of variables,
use collections (list in this case) instead of Arrays to avoid having to set a size (1000)
Sort using the framework
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int k = sc.nextInt();
List<String> cutStrings = new ArrayList<String>();
for (int i = 0; i < str.length() - k; i++) {
cutStrings.add(str.substring(i, i + k));
}
Collections.sort(cutStrings);
System.out.println(cutStrings.get(0));
System.out.println(cutStrings.get(cutStrings.size()-1));
}
You can easily sort your String[] array by simply using
Arrays.sort(s);
This will sort your strings in the default order. If you need any other kind of order you can pass the comparator as a second parameter.
You can get first and last by getting s[0] and s[s.length-1]
I did a quick implementation of your requirements. It might not be exactly what you're looking for but it should get you started. :)
So, I used an ArrayList to grab the substrings and the use the Collections library to do the sorting for me. This is just one of the many ways of solving the problem, btw. The input word can vary in size so I felt that a list would be appropriate for this situation.
String s = "welcome";
List<String> words = new ArrayList<String>();
for (int i = 0; i < s.length() - 2; i++) {
String chunk = s.charAt(i) + "" + s.charAt(i + 1) + ""
+ s.charAt(i + 2);
words.add(chunk);
System.out.println(chunk);
}
Collections.sort(words);
System.out.println(words.toString());
Feel free to let me know if you have any questions or if I have made a mistake in the code.
Good luck!
Actual problem of your code is splitting. Sorting will work. If j value 1 and k1 value 3 then wel substring is coming. Next loop, (after incrementation of both j and k1 by 1) j value 2 and k1 value 4 then elc substring is coming, etc.
So, instead of
String [] s = new String [1000];
for (int i = t, a = 0; i >= k; i--, a++) {
s[a] = str.substring(j, k1);
j++;
k1++;
}
use
int k = sc.nextInt();
String [] s = new String [(str.length()/3)+1] ;
for ( int i = 0,a = 0; i<(str.length()-k); i+=k,a++)
{
s[a] = str.substring(i,(i+k));
System.out.println(s[a]);
}
s[s.length-1]=str.substring((str.length()-k),str.length());//to add remaining values
Arrays.sort(s);//sorting alphabatically
for(int i = 0; i < s.length; i++)
System.out.println(s[i]);
}
i value will be incremented by 3. In the for loop (i+=k) where k=3.
Output:
amp
com
e s
ple
wel

Can't perform arithmetic operations on an ArrayList

I am trying to find the sum of the integers in an ArrayList, however I am having issues with data types.
Here is the code I have at the moment:
int sum = 0;
for (int i = 0; i < InputArray.size(); i++) {
sum = sum + InputArray.get(i)
}
However this is giving me the error:
error: bad operand types for binary operator '+'
I have also tried:
int sum = 0;
for (int i = 0; i < InputArray.size(); i++) {
int foo = Integer.parseInt(InputArray.get(i));
sum = sum + foo;
}
However this is giving me the error:
error: no suitable method found for parseInt(object)
The ArrayList contains integers only.
What could be the problem?
ArrayList InputArray = new ArrayList(); is what I declared it as
Elements of collections that use raw types need to be cast to access the methods of the reference types. Generics were introduced to avoid this. Replace
ArrayList InputArray = new ArrayList();
with
List<Integer> inputArray = new ArrayList<>();
//If your list should only Integers, there's no reason not to do this
ArrayList<Integer> InputArray = new ArrayList<Integer>();
//Add some integers
InputArray.add(1);
InputArray.add(2);
InputArray.add(100);
//Create your sum variable
int sum = 0;
//You could use a foreach loop
for(int i : InputArray) {
sum += i;
}
You have to define the type of your ArrayList;
ArrayList<Integer> a = new ArrayList<Integer>();
for (int i=0; i < 10; i++) {
a.add(i);
}
int sum = 0;
for (int i=0; i < 10; i++) {
sum = sum + a.get(i);
}
System.out.println(sum);
First you need to make sure that the ArrayList is created the correct way with the desired type:
ArrayList<Integer> list = new ArrayList<Integer>();
Then you can make a loop:
int sum = 0;
for (int i=0; i<list.size(); i++
{
sum += list.get(i);
}
System.out.println(sum);
Try this. Good luck!
Here is a working code using an input array of strings as you should have strings as input from user (from input.nextLine):
import java.util.ArrayList;
import java.util.List;
public class Sum {
public static void main(String[] args) {
List<String> InputArray = new ArrayList<String>();
InputArray.add("1");
InputArray.add("2");
int sum = 0;
for(String element : InputArray) {
sum += Integer.valueOf(element);
}
System.out.println(sum);
}
}
Try this instead.
int sum = 0;
for (int i = 0; i < InputArray.size(); i++) {
int foo = Integer.parseInt(InputArray.get(i).toString());
sum = sum + foo;
}
The reason it doesn't work is because you're trying to parse an int from something that's not a String.
By adding the .toString() method, you'll get around this.

subtract integer from a string of integers

Suppose I have a string array as follows:
String[] str = {"2","4","5"};
Now I want to subtract 1 from each of its elements, ie, I want the string to be like this now:
str = {"1","3","4"};
How do I do it? Is there any way other than converting it into an integer array?
Try this,
String str[]= {"2","4","5"};
for(int i=0;i<str.length;i++)
{
str[i]=String.valueOf(Integer.parseInt(str[i])-1));
}
You have to convert them into integers, but not necessarily store into an array of integers. You can do the math in-place instead:
for(int i = 0; i < str.length; i++) {
str[i] = Integer.toString(Integer.parseInt(str[i]) - 1);
}
However, this is a code smell to me. Strings do not tend to be the best choice when doing math in general. You might also want to work with an int[] internally and convert them to strings when needed.
You would need to convert them to Integers.
If you could make some crazy constraints, you could get it a little better, for example...
Only having single digit integers in an array of characters, strictly greater than zero. You could then do the "math" by subtracting 1 from their ASCII value, but this is a pretty crazy situation to even ever have.
convert string to int : int foo = Integer.parseInt("1234");
Subtract 1 from it
Convert back to string Integer.toString(i)
That makes
for (int i = 0; i < strn.length; i++)
strn[i] := String.valueOf(Integer.parseInt(strn[i]) - 1);
}
for (int i = 0; i < str.length; i++)
str[i] := String.valueOf(Integer.parseInt(str[i]) - 1);
}
Hope this will helps you.
public String[] stringCal(String[] ele,int numbr){
String[] sCalulated = new String[ele.length];
for(int i = 0; i < ele.length ; i ++){
sCalulated[i] = String.valueOf(Integer.parseInt(ele[i])-numbr);
}
return sCalulated;
}
public static void main(String[] args) throws IOException {
String str[] = subtractOn(new String[]{"2","4","5"});
for(int k=0;k<str.length;k++){
System.out.println("Integer is :" +str[k]);
}
}
public static String[] subtractOn(String str[]){
int intArray[] = new int[str.length];
String stres[] = new String[str.length];
for(int i=0;i<str.length;i++){
intArray[i] = Integer.parseInt(str[i]);
}
for(int j=0;j<intArray.length;j++){
stres[j] = String.valueOf(intArray[j]-1);
}
return stres;
}
You can use org.apache.commons.lang3.math library to solve it in an elegant way.
for(int i = 0; i < str.length; i++) {
str[i] = NumberUtils.toInt(str[i]) - 1;
}

Convert String into 2D int array

I have problem with conversion from String into two dimension int array.
Let's say I have:
String x = "1,2,3;4,5,6;7,8,9"
(In my program it will be String from text area.) and I want to create array n x n
int[3][3] y = {{1,2,3},{4,5,6},{7,8,9}}
(Necessary for next stages.) I try to split the string and create 1 dimensional array, but I don't have any good idea what to do next.
As you suggest I try split at first using ; then , but my solution isn’t great. It works only when there will be 3 x 3 table. How to create a loop making String arrays?
public int[][] RunMSTFromTextFile(JTextArea ta)
{
String p = ta.getText();
String[] tp = p.split(";");
String tpA[] = tp[0].split(",");
String tpB[] = tp[1].split(",");
String tpC[] = tp[2].split(",");
String tpD[][] = {tpA, tpB, tpC};
int matrix[][] = new int[tpD.length][tpD.length];
for(int i=0;i<tpD.length;i++)
{
for(int j=0;j<tpD.length;j++)
{
matrix[i][j] = Integer.parseInt(tpD[i][j]);
}
}
return matrix;
}
After using split, take a look at Integer.parseInt() to get the numbers out.
String lines[] = input.split(";");
int width = lines.length;
String cells[] = lines[0].split(",");
int height = cells.length;
int output[][] = new int[width][height];
for (int i=0; i<width; i++) {
String cells[] = lines[i].split(",");
for(int j=0; j<height; j++) {
output[i][j] = Integer.parseInt(cells[j]);
}
}
Then you need to decide what to do with NumberFormatExceptions
Split by ; to get rows.
Loop them, incrementing a counter (e.g. x)
Split by , to get values of each row.
Loop those values, incrementing a counter (e.g. y)
Parse each value (e.g. using one of the parseInt methods of Integer) and add it to the x,y of the array.
If you have already created an int[9] and want to split it into int[3][3]:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
toArray[i][j] = fromArray[(3*i) + j);
}
}
Now, if the 2-dimensional array is not rectangular, i.e. the size of inner array is not same for all outer arrays, then you need more work. You would do best to use a Scanner and switch between nextString and next. The biggest challenge will be that you will not know the number of elements (columns) in each row until you reach the row-terminating semi-colon
A solution using 2 splits:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
String[][] result = new String[x.length][];
for (int i = 0; i<x.length; i++) {
result[i] = x[i].split(",");
}
This give a 2 dimension array of strings you will need to parse those ints afterwards, it depends on the use you want for those numbers. The following solution shows how to parse them as you build the result:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
int[][] result = new int[x.length][];
for (int i = 0; i < x.length; i++) {
String[] row = x[i].split(",");
result[i] = new int[row.length];
for(int j=0; j < row.length; j++) {
result[i][j] = Integer.parseInt(row[j]);
}
}
Super simple method!!!
package ADVANCED;
import java.util.Arrays;
import java.util.Scanner;
public class p9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String x=sc.nextLine();
String[] array = x.split(",");
int length_x=array.length;
int[][] two=new int[length_x/2][2];
for (int i = 0; i <= length_x-1; i=i+2) {
two[i/2][0] = Integer.parseInt(array[i]);
}
for (int i = 1; i <= length_x-1; i=i+2) {
two[i/2][1] = Integer.parseInt(array[i]);
}
}
}

Categories

Resources