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.
Related
String index value accessThis question is a part of my previous question .
Example 1:
Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"]
Output: eeebffff
Explanation: a starts at index 0 in S, so it's replaced by eee.
cd starts at index 2 in S, so it's replaced by ffff.
Example 2:
Input: S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"]
Output: "eeecd"
Explanation: "ab" starts at index 0 in S, so it's replaced by "eee".
"ec" doesn't starts at index 2 in the original S, so we do nothing.
public class Q833 {
public static void main(String args[]){
String S="abcd";
int[] indexes = {0, 2};
String[]sources={"ab","cd"};
String[] targets = {"eee", "ffff"};
Solve833 ob833=new Solve833();
System.out.println(ob833.findReplaceString(S,indexes,sources,targets));
}
}
class Solve833{
public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
char[] array = S.toCharArray();
StringBuilder result = new StringBuilder();
int counter = 0;
String s = "";
for (String n:sources)
s+= n;
char[] c = s.toCharArray();
for (int i = 0; i < array.length; i++) {
if(array[indexes[counter]]==c[counter]){
result.append(targets[counter]);
if(counter<=indexes.length) {
counter++;
}
}
else
result.append(array[i]);
}
return result.toString();
}
}
Code Output: for 1st example
Expected output:Output: "eeebffff".
My output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Leetcode.Solve833.findReplaceString(Q833.java:30) at
Leetcode.Q833.main(Q833.java:16)
Code Output:2nd example
Expected Output: "eeecd"
My Output: eeebcd. So here a b missing. How can I handle it?
Your problem is that you should NOT do array[indexes[counter]]==c[counter] to determine that if the i-thsource string is presented in the S at index i. Your juegement only check for the first character of the source string.
The key of this problem is how can we find the index correctly, as when we are trying to get the result, the index(where to replce the source string with target string) may change.
try this code:
public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
StringBuilder sb=new StringBuilder(S);
int[] offsets=new int[indexes.length];
for(int i=0;i<indexes.length;i++){
if(S.substring(indexes[i],indexes[i]+sources[i].length()).equals(sources[i])){
int offset=0;
for(int j=0;j<i;j++){
if(indexes[j]<indexes[i])
offset+=offsets[j];
}
sb.replace(indexes[i]+offset,indexes[i]+sources[i].length()+offset,targets[i]);
offsets[i]=targets[i].length()-sources[i].length();
}
}
return sb.toString();
}
You can change your method like this to print the result,
public class Q833 {
public static void main(String args[]) {
String S = "abcd";
int[] indexes = {0, 2};
String[] sources = {"a", "cd"};
String[] targets = {"eee", "ffff"};
Solve833 ob833 = new Solve833();
System.out.println(ob833.findReplaceString(S, indexes, sources, targets));
}
}
class Solve833 {
public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
StringBuffer result = new StringBuffer(S);
for (int i = 0; i < indexes.length; i++) {
if (sources[i].equals(result.substring(indexes[i], indexes[i] + sources[i].length()))) {
result.replace(indexes[i], indexes[i] + sources[i].length(), targets[i]);
if (i < indexes.length - 1)
indexes[i + 1] = indexes[i + 1] + targets[i].length() - sources[i].length();
}
}
return result.toString();
}
}
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();
So i've been trying to take a txt file which has input like this for eg -
abcddhdj
efghdd
ijkl
to get this -
j
d
hd
dd
dhl
cgk
bfj
aei
i have tried to do this using 2d char array which gave nullexception and arrayoutofbound error and didnt work mostly,then tried string array , arraylist of arraylist of char , and lastly i have been trying using arraylsit of string
here is the closest i got to my solution after lot of searching by using string[] -
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt")); // PUT YOUR FILE LOCATION HERE
int k=0,i,j=0,x;
String line[] = new String[10] ; //SET THE APPROXIMATE NUMBER OF ROWS
while((line[k] = br.readLine()) !=null)
{System.out.println(line[k]); //print to check input - verified
k++;
}
for(x=0;x<k;x++)
{if(j<line[x].length())
{j=line[x].length()-1;} //this part not working in above loop
}
System.out.println(j); // verified but not working inside previous loop for some reason
System.out.println(k);
for(x=j-1;x>=0;x++) //without this loop,its perfect, but with it gives indexoutofbound error , doesnt run at x=j
{ for(i=0;i<k;i++)
{ System.out.print(line[i].charAt(x));
}
System.out.println();
}
}
here is one output
run:
abcd
efgh
ijkl
4 //should have come as 3 since i did length-1
3
chl //notice the d missing , every char of first row shifted,just why
bgk //in outofbound error , it only prints d at the end, need explanation
afj
ei
BUILD SUCCESSFUL (total time: 0 seconds)
if i add a space after abcd it gives indexoutofbound and no output after k
at end i used another method which adds spaces to make all length equal
yet still the output was wrong, plus there is something wrong with this way of thinking , there should be better method
so i tried arraylist , this is giving me more problems again
trying to work this out by any method understandable.
This ought to do the trick:
The key here is that I pad all the line arrays with empty chars so that each character array is the same length as the longest line.
public static void main(String[] args)
{
try (BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt")))
{
String line;
List<List<Character>> lines = new ArrayList<>();
int longestLine = 0;
while((line = br.readLine()) !=null)
{
line = line.trim();
if (line.length() > 0)
{
List<Character> currList = new ArrayList<>();
for (char c : line.toCharArray())
{
currList.add(c);
}
if (currList.size() > longestLine)
{
longestLine = currList.size();
}
lines.add(currList);
}
}
// pad all lists to be the same as the longest
for (List<Character> currList : lines)
{
while (currList.size() < longestLine)
{
currList.add(Character.MIN_VALUE);
}
}
// go through each list backwards
for (int i = longestLine - 1; i >= 0; i-- )
{
for (List<Character> currList : lines)
{
System.out.print(currList.get(i));
}
System.out.println();
}
}
catch (Throwable t)
{
t.printStackTrace();
}
}
Example Input:
abcd
efgh
ijkl
g
Example Output:
dhl
cgk
bfj
aeig
Assuming input is read into the arraylist
ArrayList<String> inputList = new ArrayList<String>();
inputList.add("abcddhdj");
inputList.add("efghdd");
inputList.add("ijkl");
int maxSize = 0;
for (String input : inputList) {
if (input.length() > maxSize) {
maxSize = input.length();
}
}
String outputList[] = new String[maxSize];
for (int i = 0; i < maxSize; i++) {
String output = "";
for (String input : inputList) {
if(i<input.length())
output=output+input.charAt(i);
}
outputList[maxSize-(i+1)]=output;
}
Store all to direct 2d array and transpose in printing loop
final char[][] matrix = Files.lines(Paths.get(fileName)).map(String::toCharArray).toArray(char[][]::new);
final int width = Arrays.stream(matrix).mapToInt(a -> a.length).max().getAsInt();
for (int i = 0; i < width; ++i ) {
final int idx = width-i-1;
String s = Arrays.stream(matrix).map(a -> a.length > idx ? String.valueOf(a[idx]) : " ").collect(Collectors.joining());
System.out.println(s);
}
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;
}
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]