import java.util.Random;
import java.util.Scanner;
public class ArrayHelpers{
public static void main(String[] args){
String arr[] = {"M3", "M4", "M5", "M6", "X5M", "M750Li"};
String stockElements[] = {"BMW M2 Coupé","BMW M3 Sedan", "BMW M4 Coupé", "BMW M5 Sedan","BMW M6 Gran Coupé", "BMW X5 M", "BMW X6 M", "M 750Li"};
int size = 7;
printArrayQuantities(arr);
System.out.println(getRandomElement(arr));
System.out.println(getRandomArray(size, stockElements));
}
public static void printArrayQuantities(String[] arr){
int num[] = {2, 1, 3, 3, 5, 1};
for( int i = 0; i < num.length; i++){
System.out.println(arr[i] + " " + num[i]);
}
}
public static String getRandomElement(String[] arr){
int randomNum = 0 + (int)(Math.random() * 6);
return arr[randomNum];
}
public static String[] getRandomArray(int size, String[] stockElements){
String[] randArray = new String[size];
for( int i = 0; i < size; i++){
randArray[i] = getRandomElement(stockElements);
}
return randArray;
}
}
So I'm trying to return an array that has been randomly inserted with elements from stockElements through getRandomElement method. When I'm trying to print that array from line 12 (System.out.println(getRandomArray(size, stockElements));) it produces [Ljava.lang.String;#6d06d69c as output. I'm aware of the .toString() method, but a requirement of my assignment is that I do not use any built in array methods. How exactly would I go about doing this?
A simple solution is just to iterate over it with for each loop.
String[] myArray = getRandomArray(size, stockElements); // this stores a reference of the returned array.
for(String str : myArray){
System.out.println(str);
}
or with for loop if you prefer.
String[] myArray = getRandomArray(size, stockElements); // this stores a reference of the returned array.
for(int i = 0; i < myArray.length; i++){
System.out.println(myArray[i]);
}
Since your function is returning an array, when you try to print the array you should be iterating through each elements with a for/while loop and printing them individually. Since you're trying to print the array variable it instead prints java's handle for it. So try something like this
String[] randomArray = getRandomArray(size, stockElements);
for (String s : randomArray) {
System.out.println(s);
}
Replace System.out.println(getRandomArray(size, stockElements)); with
String [] output = getRandomArray(size, stockElements);
printArrayQuantities(output);
You already have the array returned, just need to assign it:
String[] newArray = getRandomArray(size, stockElements);
But... if you want to just print it go with the below.
Using Java 8:
String.join(delimiter, newArray);
or (for older Java):
StringBuilder builder = new StringBuilder();
for(String s : newArray) {
builder.append(s);
builder.append(delimeter);
}
return builder.toString();
Related
I am trying to separate String [] adr = {"Tel Iva +38712345", "Mail Iva ivag#gmail.com", "Tel Ana +12345678"} by looking at each of the element's first word. If the first word is Mail, it goes to String [] m, and if the first word is Tel, it goes to String [] t.
Here is my code:
public static void rep(String a, String []adr) {
int mail=0, tel=0;
for (int i=0; i<adr.length; i++) {
if(adr[i].substring(0, 3).equals("Mail")) {
mail++;
}
else tel++;
}
String [] m = new String [mail];
String [] t = new String [tel];
for(int i=0; i<adr.length; i++) {
if(adr[i].substring(0, 4).equals("Mail")) {
m[i]=adr[i].substring(5);
}
else t[i]=adr[i].substring(4);
System.out.println(adr[i].substring(0, 4));
}
}
But for some reason unknown to me, I get
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 1
which points at line m[i]=adr[i].substring(5). I really do not understand why. Any help would be appreciated.
Correct Solution. you need to two indices to track m and t array traversal.
public static void rep(String a, String []adr) {
int mail=0, tel=0;
for (int i=0; i<adr.length; i++)
{
if(adr[i].substring(0, 4).equals("Mail")) {
mail++;
}
else tel++;
}
String [] m = new String [mail];
String [] t = new String [tel];
int mIndex =0, tIndex = 0;
for(int i=0; i<adr.length; i++) {
if(adr[i].substring(0, 4).equals("Mail")) {
m[mIndex]=adr[i].substring(4);
mIndex++;
}
else
{
t[tIndex]=adr[i].substring(4);
tIndex++;
}
System.out.println(adr[i].substring(0, 4));
}
}
Well You can try this method, I once coded same type of problem when I was learning Java for the my academics. Well you can also try StringTokenizer method to do the same. Maybe they works better. I am expecting that you are going to insert the whole string not splitted one.
import java.util.*;
import java.lang.*;
import java.*;
public class stringtoken{
public static void main(String args[]){
List<String> m=new ArrayList<String>();
List<String> t=new ArrayList<String>();
String[] s={"Tel Iva +38712345", "Mail Iva ivag#gmail.com", "Tel Ana +12345678"};
for(int i=0;i<s.length;i++){
if(s[i].indexOf("Tel")==0){
t.add(s[i]);
}
else if(s[i].indexOf("Mail")==0){
m.add(s[i]);
}
}
for(int i=0;i<m.size();i++){
System.out.println(m.get(i));
}
for(int i=0;i<t.size();i++){
System.out.println(t.get(i));
}
}
}
Supposedly index you used in the substring method are correct and I will only talk about index of the array :
String [] adr = {"Tel Iva +38712345", "Mail Iva ivag#gmail.com", "Tel Ana +12345678"}
By this data,
mail array's size will be 1, max index can use for mail array is 0
tel array's size will be 2, max index can use for tel array is 1
for(int i=0; i<adr.length; i++) {
if(adr[i].substring(0, 4).equals("Mail")) {
m[i]=adr[i].substring(5);
}
else t[i]=adr[i].substring(4);
System.out.println(adr[i].substring(0, 4));
}
In this loop :
LOOP 1 : i = 0 -> t[0]=xxx; -> OK
LOOP 2 : i = 1 -> m[1]=xxx; -> ERROR, because size of m array is 1, index can only be 0
PS : you need to check the index used in substring method
suppose this sample address array (your parameter adr[])
adr[0] = Maila#a.com
adr[1] = Tele123456
adr[2] = Mailb#a.com
adr[3] = Tele123456
adr[4] = Mailc#a.com
After your first loop which is assign values to int mail and tel
mail = 3;
tel = 2
so your m and t array looks like below.
String [] m = new String [3];
String [] t = new String [2];
What happen is in your last for looping for adr (you parameter array) length which is 5.
and try to assign values to m or t, by index of adr array.
Ex : adr[3] = Tele123456
on your second loop when i = 3 your getting this value and try to assign this value to
t[3] = 123456
where actually t size is 2 and then it occur array out of bound exception.
Hope you understood the issue on your code.
Rather than array for m and t use List.
Consider below example.
public static void rep(String a, String []adr) {
List<String> mails = new ArrayList<>();
List<String> teles = new ArrayList<>();
for (int i=0; i<adr.length; i++) {
if(adr[i].substring(0, 3).equals("Mail")) {
mails.add(adr[i].substring(5));
} else {
mails.add(adr[i].substring(5));
}
}
}
**Note : please fix compile errors if there.
how can i print the result without brackets
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int i=0; i < n; i++){
arr[i] = in.nextInt();
}
int[] reverse =new int[n];
for (int i = 0; i < reverse.length; i++) {
reverse[i]=arr[arr.length-1-i];
}
in.close();
}
}
In java8, you can conveniently do any kind of String output using join, there you will have to do some manual reversing though:
String output = String.join(", ", arr);
You can't change the implementation of Arrays.toString() so you can't print your array like that.
Although, you can assign it to an string variable and then manipulate that string as you desire.
String str = Arrays.toString(reverse);
str = str.substring(1, str.length() - 1);
I'm currently doing an activity that requires me to write this:
Write a definition for a static method stringHeads that inputs an array of ints p and a String s. For each of the ints n in p, the method builds the substring consisting of the first n characters in s (or the whole of s, if n is greater than the length of s). The method returns the array of these substrings.
My code is currently something like this:
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p)
e = b - 1
for (int de = 0; rad.length > de; de++)
rad[de] = s.substring(0,e);
for (String str : rad)
return str;
}
//Just ignore the rest
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon"
stringHeads(a,b)
The output should be "Rado" , "Ra", "Rad", "Ra", "".
The error that I'm currently getting is that String cannot be converted to String[].
Basically my question is how to fix this error and if a better code can be written.
Three things:
e would be constant if you enter the second loop.
e could be larger than s.length() - you didn't handle this case.
You return a String instead of a String[]
And please always use braces if you use loops, even if the loop only contains one statement. It is much more readable and can avoid errors.
I think you will have to rethink your whole function. Don't know if it would be helpful to write the function for you.
Hints:
Write only one loop!
String[] rad = new String[p.length];
for (int i=0; i < p.length; i++) {
if (s.length() < ??) {
rad[i] = s.substring(0,??);
} else {
??
}
}
return rad;
I hope this will help you to get the answer yourself.
See my code below hope it helps:-
I provided the comments instead of explaining it in paragraph.
As for your error, you are returning String from method but expected is an array of String.
public static void main(String[] args){
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] output=stringHeads(a,b);
for(String s:output){
System.out.println(s);
}
}
Your method can be like below:
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
//Iterate over integer array
for(int index=0; index<p.length; index++){
//Extracting the integer value from array one by one
e=p[index];
//If integer value is greater than String length
if(e>s.length()){
//Put the entire String in String array
rad[index]=s;
}else{
//Put the Substring value with range 0 to e i.e. integer value
rad[index]=s.substring(0,e);
}
}
return rad;
}
You could simplify you code by just using a single iteration with an alternative variable.
public static void main (String[] args) throws java.lang.Exception
{
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] result = stringHeads(a,b);
for(String x : result) System.out.println(x);
//Or you can write a separate display method instead.
}
public static String[] stringHeads(int[] p, String s)
{
String[] rad = new String[p.length];
//Use this variable for array allocation/iteration.
int i=0;
//Simply iterate using this for-each loop.
// This takes care of array allocation/ substring creation.
for (int x : p)
rad[i++] = s.substring(0,x);
return rad;
}
Please check the code below
public static String[] stringHeads(int[] intArray, String str) {
String[] result = new String[intArray.length];
int count=0;
for (int intValue : intArray)
{
result[count] = str.substring(0,intValue);
count++;
}
return result;
} //Just ignore the rest
public static void main(String[] args) {
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] strArray=stringHeads(a,b);
int count=0;
for(String str:strArray)
System.out.println(++count+"" +str);
}
Change your method like this
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p) {
rad[e] = s.substring(0, b);
e++;
}
return rad;
}
For use this method
public static void main(String[] args) {
int[] a = {4, 2, 3, 2, 0};
String b = "Radon";
String[] stringHeads = stringHeads(a, b);
for (String stringHead : stringHeads) {
System.out.println(stringHead);
}
}
Output is
Rado
Ra
Rad
Ra
There is no need for the for loop that iterates through the integer array p
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
for (int de = 0; de < p.length; de++){
if (p[de] < s.length())
rad[de] = s.substring(0,p[de]);
else
rad[de]=s;
}
return rad;
}
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p) {
if(b<=s.length()){
rad[e] = s.substring(0, b);
}
e++;
}
return rad;
}
there. I faced a bit trouble with java programming
**Could someone give me a hint which of the method use in order to
string= "23578893762467290465" convert to array y= [2,3,5,7]....??**
I mean, that for example y[0]=2, y[1]=3, y[2]=5....
Thanks in advance
String.toCharArray()
From the official documentation:
It returns a newly allocated character array whose length is the
length of this string and whose contents are initialized to contain
the character sequence represented by this string.
Convert String to an integer array.
String string= "23578893762467290465";
int[] intArray = new int[string.length()];
for(int i = 0; i<string.length(); i++){
intArray[i] = Integer.parseInt(String.valueOf(string.charAt(i)));
}
public class StringToInt{
public int[] convert(String arg){
char[] characters = arg.toCharArray();
int[] integers = new int[arg.length()];
for ( int i = 0; i < characters.length; i++ )
integers[i] = Character.getNumericValue(characters[i]);
return integers;
}
private void prettyPrint(int[] result){
System.out.print("array: ");
for(int i : result){
System.out.print(i+" ");
}
}
public static void main(String[]args){
StringToInt converter = new StringToInt();
int[] result = converter.convert(args.length > 0?args[0]: "23578893762467290465" );
converter.prettyPrint(result);
}
}
ok, people beat me to it. But this'll work.
in essence:
Convert to char-array.
call Character.getNumericValue() for each character.
Another way may be:
int[] arr = new int[string.length()];
for(int i = 0; i<string.length(); i++){
arr[i] = Character.getNumericValue(string.charAt(i));
System.out.println(arr[i] + " ") ;
}
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]