JAVA: Populating an array then display using for loop - java

I'm trying to populate an array [C], then display it using a for loop.. I'm new to arrays and this is confusing the hell out of me, any advice is appreciated!
Below is my code:
public static void main(String[] args) {
int A[] = new int[5];
int B[] = new int[5];
String C[] = new String[5];
int D[] = new int[5];
C[] = {"John", "Cook", "Fred"};
for(String name: C)
System.out.println(C);
}}

You can define and populate an array in two ways. Using literals:
String c[] = {"John", "Cook", "Fred"};
for(String name : c) { // don't forget this { brace here!
System.out.println(name); // you want to print name, not c!
}
Or by setting each index element:
int d[] = new int[2];
d[0] = 2;
d[1] = 3;
for(int num: d) {
System.out.println(num);
}
(You can only use the literal when you first define the statement, so
String c[];
c = {"John", "Cook", "Fred"};
Will cause an "illegal start of expression" error.)

You want to print name instead of C.

C is the name of the array, while name is the name of the String variable. Therefore you must print name instead of C
System.out.println(name);

for(int i=0;i<=2;i++){
System.out.println(C[i]);
}
here 2 is the last index of the array C
You cannot simply print an array you have to provide an index to your item
where C[0] is john and C[1] is Cook and so on
and if you want to use a for each loop then this is how it goes
for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}

Try specifying at what index you want to add the element.
Example:
C[0] = "hej";
Also, print the element in the array, not the actual array. (System.out.println(name);)

Related

Merge two or more elements of ArrayList

Is there any possibility to merge two elements of ArrayList?
This is my array = [u,s,m,a,t,t]
and I want to have something like this = [us,matt]
I've tried to use toString(), and replace('',''), but it merges whole array [usmatt].
Any other options?
I don't know exactly what you mean but what you try to achieve could be done this way:
Pseudo-code:
String[] array1 = [u,s,m,a,t,t]
String a = array[0]+array[1]
String b = array[2]+array[3]+array[4]+array[5]
String[] array2 = [a,b]
Try this: (For any length ArrayList.)
public static void MergeArrayList() {
ArrayList<Character> Array = new ArrayList<Character>() {{ add('u');add('s');
add('m');add('a');add('t');add('t');}};
ArrayList<String> newArray = new ArrayList<>();
int n=2; // Change this to indicate where you need to make the cut.
String str="";
for (int i=0;i<Array.size();i++) {
if (i==n) {
newArray.add(str);
str="";
}
str += Array.get(i);
}
newArray.add(str);
System.out.println(Array);
System.out.println(newArray);
}

storing a string into an array causes an ArrayIndexOutOfBoundsException error

int x = 0;
String[] QEquivalent = {};
String s = sc.nextLine();
String[] question2 = s.split(" ");
for (int i = 0; i < question2.length; i++) {
System.out.println(question2[i]);
x++;
} //debug
System.out.println(x);
String s2 = sc2.nextLine();
String[] Answer = s2.split(" ");
for (int c = 0; c < Answer.length; c++) {
System.out.println(Answer[c]);
} //debug
int y;
String u = sn.nextLine();
String[] t = u.split(" ");
for (y = 0; y < question2.length; y++) {
for (int w = 0; w < t.length; w++) {
if (t[w].equals(question2[y])) {
QEquivalent[y] = "ADJ";
System.out.println(QEquivalent[y]);
break;
}
}
}
this is the line of codes that I have as of now. when a string in question2 is found in String[] t, it should store the string "ADJ" in String[] QEquivalent. I can't seem to fix the error. can someone please help me?
You are creating an empty array here:
String[] QEquivalent = {};
So, any index you try to access will be out of bounds. You should creating an array using a fixed size.
Or, you can better use an ArrayList instead, which can dynamically grow in size:
List<String> qEquivalent = new ArrayList<String>();
and then add elements using:
qEquivalent.add("ADJ");
And please follow Java Naming conventions. Variable names should start with lowercase letters.
You create an empty array:
String[] QEquivalent = {};
and then set some elements at index y > 0:
QEquivalent[y] = "ADJ";
You can either:
compute the final dimension of the array and be sure to instantiate it: String[] QEquivalent = new String[SIZE];
use a dynamic structure like an ArrayList
eg:
ArrayList<String> QEquivalent = new ArrayList<QEquivalent>();
QEquivalent.add("ADJ");
Your array QEquivalent is an empty array . It is of length 0 , hence even QEquivalent[0] will throw ArrayIndexOutOfBoundsException.
One fix I can see is assign it a length :
String[] question2 = s.split(" ");
// Just assign the dimension till which you will iterate finally
// from your code `y < question2.length` it seems it should be question2.length
// Note you are always indexing the array using the outer loop counter y
// So even if there are n number of nested loops , assigning the question2.length
// as dimension will work fine , unless there is something subtle you missed
// in your code
String[] QEquivalent = new String[question2.length];
Better use any implementation of List , like an ArrayList.
List<String> qEquivalent = new ArrayList<String>();
......
if (t[w].equals(question2[y])) {
qEquivalent.add("ADJ");
System.out.println(qEquivalent.get(y));
break;
}
Give some size to the array String[] QEquivalent = new String[100];
You statement String[] QEquivalent = {}; creates an array with zero size.
You are declaring your QEquivalent array as an empty String array.
When you access the index QEquivalent[y], that index doesn't exist, hence the ArrayIndexOutOfBoundsException.
I strongly suggest you use a List<String> instead.
Such as:
List<String> qEquivalent = new ArrayList<String>(); // replaces the array declaration and uses Java conventional naming
...
qEquivalent.add("ADJ"); // replaces the indexing of the array and adds the item
Possibly QEquivalent variable makes the error.Because when you declare that variable, its length is 0.So declare the variable as with new and a size.
Or move it after you split the string into question2 and use:
String[] QEquivalent = new String[question2.length];

How do I declare a variable with an array element?

I have an array of elements and I want to use the elements in the array as variables.
I want to do this because I have an equation, the equation requires multiple variable inputs, and I want to initialize an array, iterate through it, and request input for each variable (or each element of the array).
So I have an array like this:
String variableArray[] = {"a", "b", "c"}
And now I'm iterating through this array and getting the input from the user:
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", variableArray[i]);
int variableArray[i] = keysIn.nextInt();
}
The problem is this line doesn't compile:
int variableArray[i] = keysIn.nextInt();
In essence, I want to use the elements of the array variableArray[] (i.e. a, b, and c) as variables so I don't have to do the same process for each variable. I can't imagine how it's done when there are many variables to input (I wouldn't want to type that all out).
tl;dr I want to streamline the process of inputting values for multiple variables.
You initialized your array as:
String variableArray[] = {"a", "b", "c"}
i.e. an array of Strings.
If you want to refer later to the i-th element, you just write:
variableArray[i]
without any int before - you can't initialize single entries in a array.
Java doesn't work like that. "a" is a string literal, and you can't use it as if it were a variable. There's no magical way to go from having an array element whose value is "a" to having an int variable called a.
There are, however, some things you can do that are probably equivalent to what you want.
String variableArray[] = {"a", "b", "c"}
int valueArray[] = new int[variableArray.length];
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", variableArray[i]);
valueArray[i] = keysIn.nextInt();
}
To get the value of "a", do valueArray[0].
Here's another more sophisticated suggestion:
String variableArray[] = {"a", "b", "c"}
HashMap<String, Integer> variableValues = new HashMap<String, Integer>();
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", variableArray[i]);
variableValues.put(variableArray[i], keysIn.nextInt());
}
To get the value of "a", do variableValues.get("a").
Two things;
Firstly you've declared your array as and array of Strings so variableArray[i] = keysIn.nextInt() won't work any way, int can't be stored in a String array.
Secondly, int variableArray[i] = keysIn.nextInt(); is incorrect, because variableArray has already been declared (as a String array and variableArray[i] is a String element of that array)
The line should read variableArray[i] = keysIn.next();, but this will store the text the user has entered, not a numerical value.
What it could look like is...
String labelArray[] = {"a", "b", "c"}
int variableArray[] = new int[3];
// You could declare this as
// int variableArray[] = {0, 0, 0};
// if you wanted the array to be initialized with some values first.
for(int i=0; i<3; i++) {
System.out.printf("Enter value for %s: ", labelArray[i]);
variableArray[i] = keysIn.nextInt();
}
UPDATED
int a = variableArray[0];
int b = variableArray[1];
int c = variableArray[2];
Please use with caution, but after reading your comments to the other answers, you might get a little closer to the way you want it using reflection:
import java.lang.reflect.Field;
import java.util.Scanner;
public class VariableInput {
public static class Input {
public int a;
public int b;
public int c;
}
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException {
Scanner keysIn = new Scanner(System.in);
Field[] fields = Input.class.getDeclaredFields();
Input in = new Input();
for (int i = 0; i < 3; i++) {
System.out.printf("Enter value for %s: ", fields[i].getName());
fields[i].set(in, keysIn.nextInt());
}
int d = in.a + in.b + in.c;
System.out.println("d=" + d);
}
}
What you are actually looking for is a Map. It's a collection of mappings from one value to another value. In your case, you can use it to assign an integer value (the value of a variable) to a string that represents the name of a variable.
Therefore you would create an instance of a Map<String, Integer> - read "a map from String to Integer".
See this tutorial for details on the subject.
Now what would your code look like with it:
String[] variableNames = { "a", "b", "c" };
// create the map object
Map<String, Integer> variableValues = new LinkedHashMap<String, Integer>();
// read variable values and put the mappings into the map
for (int i = 0; i < variableNames.length; i++) {
System.out.printf("Enter value for %s: ", variableNames[i]);
variableValues.put(variableNames[i], keysIn.nextInt());
}
// print value of each variable
for (int i = 0; i < variableNames.length; i++) {
String varName = variableNames[i];
System.out.println(varName + " = " + variableValues.get(varName));
}
Output:
Enter value for a: 5
Enter value for b: 4
Enter value for c: 8
a = 5
b = 4
c = 8

Converting ArrayList to Array in java

I have an ArrayList with values like "abcd#xyz" and "mnop#qrs". I want to convert it into an Array and then split it with # as delimiter and have abcd,mnop in an array and xyz,qrs in another array. I tried the following code:
String dsf[] = new String[al.size()];
for(int i =0;i<al.size();i++){
dsf[i] = al.get(i);
}
But it failed saying "Ljava.lang.String;#57ba57ba"
You don't need to reinvent the wheel, here's the toArray() method:
String []dsf = new String[al.size()];
al.toArray(dsf);
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[list.size()])
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[0]);
if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.
import java.util.*;
public class arrayList {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<String > x=new ArrayList<>();
//inserting element
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
//to show element
System.out.println(x);
//converting arraylist to stringarray
String[]a=x.toArray(new String[x.size()]);
for(String s:a)
System.out.print(s+" ");
}
}
String[] values = new String[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
values[i] = arrayList.get(i).type;
}
What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29
Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:
for(String str : dsf){
System.out.println(str);
}
What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.
package com.v4common.shared.beans.audittrail;
import java.util.ArrayList;
import java.util.List;
public class test1 {
public static void main(String arg[]){
List<String> list = new ArrayList<String>();
list.add("abcd#xyz");
list.add("mnop#qrs");
Object[] s = list.toArray();
String[] s1= new String[list.size()];
String[] s2= new String[list.size()];
for(int i=0;i<s.length;i++){
if(s[i] instanceof String){
String temp = (String)s[i];
if(temp.contains("#")){
String[] tempString = temp.split("#");
for(int j=0;j<tempString.length;j++) {
s1[i] = tempString[0];
s2[i] = tempString[1];
}
}
}
}
System.out.println(s1.length);
System.out.println(s2.length);
System.out.println(s1[0]);
System.out.println(s1[1]);
}
}
Here is the solution for you given scenario -
List<String>ls = new ArrayList<String>();
ls.add("dfsa#FSDfsd");
ls.add("dfsdaor#ooiui");
String[] firstArray = new String[ls.size()];
firstArray =ls.toArray(firstArray);
String[] secondArray = new String[ls.size()];
for(int i=0;i<ls.size();i++){
secondArray[i]=firstArray[i].split("#")[0];
firstArray[i]=firstArray[i].split("#")[1];
}
This is the right answer you want and this solution i have run my self on netbeans
ArrayList a=new ArrayList();
a.add(1);
a.add(3);
a.add(4);
a.add(5);
a.add(8);
a.add(12);
int b[]= new int [6];
Integer m[] = new Integer[a.size()];//***Very important conversion to array*****
m=(Integer[]) a.toArray(m);
for(int i=0;i<a.size();i++)
{
b[i]=m[i];
System.out.println(b[i]);
}
System.out.println(a.size());
This can be done using stream:
List<String> stringList = Arrays.asList("abc#bcd", "mno#pqr");
List<String[]> objects = stringList.stream()
.map(s -> s.split("#"))
.collect(Collectors.toList());
The return value would be arrays of split string.
This avoids converting the arraylist to an array and performing the operation.
NameOfArray.toArray(new String[0])
This will convert ArrayList to Array in java
// A Java program to convert an ArrayList to arr[]
import java.io.*;
import java.util.List;
import java.util.ArrayList;
class Main {
public static void main(String[] args)
{
List<Integer> al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
Integer[] arr = new Integer[al.size()];
arr = al.toArray(arr);
for (Integer x : arr)
System.out.print(x + " ");
}
}

Using String.split() to access numeric values

i tried myself lot but can't get a solution so i'm asking help.
i have an string String input="---4--5-67--8-9---";
now i need to convert in into an string array which will look like:
String [][]output={{4},{5},{67},{8},{9}};
i tried with split() and
java.util.Arrays.toString("---4--5-67--8-9---".split("-+")
but can't find the desired answer. so what to do?
actually i need the value 4,5,67,8,9.but i'm not sure how to find them. i will treat the values as integer for further processing
String[] numbers = "---4--5-67--8-9---".split("-+");
String[][] result = new String[numbers.length][1];
for (int i = 0; i < numbers.length; i++) {
result[i][0] = numbers[i];
}
Update: to get rid of the initial empty value, you can get a substring of the input, like:
int startIdx = 0;
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i ++) {
if (Character.isDigit(chars[i])) {
startIdx = i;
break;
}
}
input = input.substring(startIdx);
(or you can check them for not being empty (String.isEmpty()) when processing them later.)
First, here is the answer to your question. This code will generate a two-dimensional array where each element is an array consisting of a single numeric string.
final String input = "---4--5-67--8-9---";
// desired output: {{4},{5},{67},{8},{9}}
// First step: convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create the two-dimensional array with the correct size
final String[][] arrayOfArrays = new String[arrayOfStrings.length][];
// Loop over single-dimension array to initialize the two-dimensional one
for(int i = 0; i < arrayOfStrings.length; i++){
final String item = arrayOfStrings[i];
arrayOfArrays[i] = new String[] { item };
}
System.out.println(Arrays.deepToString(arrayOfArrays));
// Output: [[4], [5], [67], [8], [9]]
However, I think what you really need is an array of Integers or ints, so here is a revised solution:
final String input = "---4--5-67--8-9---";
// Convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create an array of Integers and assign the values from the string
final Integer[] arrayOfIntegers = new Integer[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfIntegers[i] = Integer.valueOf(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfIntegers));
// Output: [4, 5, 67, 8, 9]
// Or alternatively an array of ints
final int[] arrayOfInts = new int[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfInts[i] = Integer.parseInt(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfInts));
// Output: [4, 5, 67, 8, 9]
Whether you use the Integer or the int version really depends on whether you want to just do some math (int) or need an object reference (Integer).
String[] result = "---4--5-67--8-9---".split("-+");
int i;
for (i = 0; i < result.length; i++) {
if (result[i].length() > 0) {
System.out.println(result[i]);
}
}
gives me output:
4
5
67
8
9
public class split{
public static void main(String[] argv){
String str="---4--5-67--8-9---";
String[] str_a=str.split("-+");
}
}
This seems to working for me.
Using a regex pattern seems more natural in this case:
public class split {
public static int[] main(String input) {
ArrayList<String> list = new ArrayList() ;
Pattern pattern = Pattern.compile("[0-9]") ;
Matcher matcher = pattern.matcher(input) ;
String match = null ;
while( ( match = matcher.find() ) === true ) {
list.add(match) ;
}
String[] array = list.toArray( new String[ ( list.size() ) ]() ) ;
return array ;
}
}
String input="---4--5-67--8-9---";
Scanner scanner = new Scanner(input).useDelimiter("-+");
List<Integer> numbers = new ArrayList<Integer>();
while(scanner.hasNextInt()) {
numbers.add(scanner.nextInt());
}
Integer[] arrayOfNums = numbers.toArray(new Integer[]{});
System.out.println(Arrays.toString(arrayOfNums));
I thought the following is quite simple, although it uses List and Integer arrays, Its not that an overhead for small strings:
For simplicity, I am returning a single dimension array, but can be easily modified to return an array you want. But from your question, it seems that you just want a list of integers.
import java.util.*;
public class Test {
public static void main(String[] args) throws Throwable {
String input = "---4--5-67--8-9---";
System.out.println(split(input).length); // 5
}
public static Integer[] split(String input) {
String[] output = input.split("\\-+");
List<Integer> intList = new ArrayList<Integer>(output.length);
// iterate to remove empty elements
for(String o : output) {
if(o.length() > 0) {
intList.add(Integer.valueOf(o));
}
}
// convert to array (or could return the list itself
Integer[] ret = new Integer[intList.size()];
return intList.toArray(ret);
}
}
I might be late to the party but I figured I'd give the guava take on this.
String in = "---4--5-67--8-9---";
List<String> list = Lists.newArrayList(Splitter.on("-").omitEmptyStrings().trimResults().split(in));
System.out.println(list);
// prints [4, 5, 67, 8, 9]

Categories