I have an array which has been initialised with another.
a1 = a2; //right hand side is actually a method returning an array
I can append the returned array elements to a JTextArea but printing them out produces null in the console.
for (int i = 0; i < a1.lenght; i++) {
outputTextArea.append(a1[i]);
System.out.println(a1[i]);
}
Why is this? Thank you.
This is the method:
public String[] searchString(ArrayList<String> content, String string){
stringArray = new String[content.size()];
for(int i = 0; i < content.size(); i++){
if(string.equals(content.get(i))){
if(content.indexOf(string) == 0) {
stringArray[i] = content.get(i) + " " + content.get(i+1) + "\n";
} else if ((content.indexOf(string) > 0) && (content.indexOf(string) < (content.size()-1))) {
stringArray[i] = content.get(i-1) + " " + content.get(i) + " " + content.get(i + 1) + "\n";
} else if ((content.indexOf(string)) == (content.size()-1)) {
stringArray[i] = content.get(i -1) + " " + content.get(i);
}
}
}
return stringArray;
}
The Output NULL not from a1 but from a2
you have if statement :
if (string.equals(content.get(i))) {
.....
}
without else , so if the string != content.get(i) , so it will return null in this index at (a2)
so you may need to initialize a2 with values , or make check like this : if(a1[i] != null)
for(int i = 0; i < a1.lenght; i++){
if(a1[i]!=null){///////////to avoid the null values
outputTextArea.append(a1[i]);
System.out.println(a1[i]);
}
}
the second problem you will face in this code (When you repeated your string in content array):
stringArray[i] = content.get(i) + " " + content.get(i + 1) + "\n";
if i = content.size() ,so ( i+1 ) will IndexOutOfBoundsException
Related
When I run this, I can see exact result "false" but I also want to see what difference there is. For instance
"ozer and gunthy" match but "albundy and aldy" does not
package start;
public class Start {
public static void main(String[] args) {
String[] a = {"ozer + gunthy + albundy"};
String[] b = {"ozer + günthy + aldy"};
boolean b1 = false;
if (a.length != b.length){
b1 = false;
}else {
for (int i = 0; i < a.length; i++){
if (a[i] == b[i]){
b1 = true;
}else {
b1 = false;
break;
}
}
}
System.out.println(b1);
}
}
You will want to replace
a[i] == b[i]
with
a[i].equals(b[i])
You will also need to fix your arrays
public static String[] list1 = {"ozer", "gunthy","albundy"};
public static String[] list2 = {"ozer", "günthy","aldy"};
then, you will need to write and call a method to properly analyze the arrays to your specification:
public String methodName(String[] list1, String[] list2)
{
String output = "";
if (list1.length != list2.length)
{
return "The Arrays differ in length";
}
else
{
for (int i = 0; i < list1.length; i++)
{
if (list1[i].equals(list2[i]))
{
output += "" + list1[i] + " is equal to " + list2[i] + "\n";
}
else
{
output += "" + list1[i] + " is not equal to " + list2[i] + "\n";
}
}
}
return output;
}
I need to do a method to check two string for example bod and bot or crab and rab. The method needs to print out what the user must do in order to make them equal. For example in bod and bot it will print "replace,2,d in the string". I used this code which seems to work.
if(a.length()==b.length()){
int i;
for(i=0; i<=a.length(); i++){
if(a.charAt(i)!=b.charAt(i)){
return "replace,"+ i + "," + b.charAt(i);
}
}
}
But I am having troubles if the two string are not equal in size. I use this but it doesn't work because one of the strings is bigger.
int aS = a.length();
int bS = b.length();
if(bS - aS == 1){
int i;
for(i=0; i<=b.length(); i++){
if(b.charAt(i)!=a.charAt(i)){
return "remove," + i;
}
}
}
Can you guys give me a suggestion what method I can use to check which is the extra letter or vice versa a letter I can add and then return a string saying either to remove a character or add an extra one. Thank you
Maybe something like this?
public ArrayList<String> createConversionList(String primary, String secondary){
//Determine which string is shorter.
String shorter;
String longer;
boolean primaryIsShorter = false;
if (primary.length() >= secondary.length()){
longer = primary;
shorter = secondary;
} else{
longer = secondary;
shorter = primary;
primaryIsShorter = true;
}
//Fills an array with all the character positions that differ between the
//two strings, using the shorter string as the base.
int[] posOfCharsToChange = new int[shorter.length()];
for(int i = 0; i < shorter.length(); i++){
if(shorter.charAt(i) != longer.charAt(i)){
posOfCharsToChange[i] = i;
} else{
posOfCharsToChange[i] = -1;
}
}
//Adds to an ArrayList all of the "Replace" strings.
ArrayList<String> conversionList = new ArrayList();
for(int pos: posOfCharsToChange){
if(pos != -1){
String s = "Replace " + secondary.charAt(pos) + " with " + primary.charAt(pos) + ". \n";
conversionList.add(s);
}
}
//Depending on which string was bigger, either adds "Add" or "Remove"
//strings to the ArrayList. If the strings were the same size, does
//nothing.
if(primary.length() != secondary.length()){
if(primaryIsShorter){
for(int i = primary.length(); i < secondary.length(); i++){
String s = "Remove " + secondary.charAt(i) + ". \n";
conversionList.add(s);
}
}
else{
for(int i = secondary.length(); i < primary.length(); i++){
String s = "Add " + primary.charAt(i) + ". \n";
conversionList.add(s);
}
}
}
return conversionList;
}
My Approach works as follows
1) We take the smaller string and put all its contents in an arraylist
2) We take the bigger string and put its contents in the arraylist only if its not present in the arraylist
3) The last character in the arraylist must be removed from the bigger string to make them equal
Ex 1:
a = rab
b = crab
1) arraylist = rab -> contents of a added
2) arraylist = rabc -> only unique content of b is added
Ex 2:
a = crab
b = rab
1) arraylist = rab
2) arraylist = rabc
similarly if the positions are in the middle or not at start ,
ex : a = racb
b = rab
1) arraylist = rab
2) arraylist = rabc
public class Replace {
public static void main(String args[]) {
int p = 0, j = 0;
String a = "rab";
String b = "crab";
if (b.length() < a.length()) {
ArrayList al = new ArrayList();
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String a");
} else {
ArrayList al = new ArrayList();
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String b");
}
}
}
Note - The program only works under your given contraints that strings only differ in one character and the ordering of both the strings is not different if we remove or add that charcter.
Before I get into the issue, let me describe the problem that the code is supposed to be solving.
The code is supposed to take in input from a file in the following syntax:
1,2,3,4;5
The code is supposed to take the integer that is after the semicolon and assign it to a variable, which it does. Then the code is supposed to take the values that are before the semicolon and find and return all two pairs of integers that add up to the value after the semicolon.
Example: if the input is
1,2,3,4;5
then the output should be
1,4;3,2
The problem I have is that my String result is not being edited by the nested for loops within the code. I get no compile time or runtime errors. It just does not edit the String result and I can't figure out why. Could you guys take a look?
import java.util.*;
import java.io.*;
public class NumberPairs2 {
public static void main (String[] args) throws IOException {
File file = new File("C:/Users/James/Desktop/txt.txt"); // Takes in a file as input
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
while ((line = buffer.readLine()) != null) {
String result = ""; // creates an empty string
line = line.trim(); // set the file contents equal to null
if (line.length() != 0){
int sumTest = Integer.parseInt(line.substring(line.indexOf(";") + 1));
String[] intArray = line.split(";");
String[] intArray2 = intArray[0].split(",");
for (int i = 0; i < intArray2.length - 1; i++){
for(int j = i + 1; i < intArray2.length; i++){
if (intArray2[i] != "," && intArray2[j] != "," && Integer.parseInt(intArray2[i]) + Integer.parseInt(intArray2[j]) == sumTest){
result += intArray[i] + ", " + intArray[j] + ";";
System.out.println(result);
}
}
}
//int compare = ()
}
else {
result = null;
System.out.println(result);
}
}
}
}
This may help
for (int i = 0; i < intArray2.length - 1; i++){
for(int j = i + 1; j < intArray2.length; j++){
if (Integer.parseInt(intArray2[i]) + Integer.parseInt(intArray2[j]) == sumTest){
result += intArray2[i] + ", " + intArray2[j] + ";";
}
}
}
System.out.println(result);
You need to use intArray2[i] & intArray2[j] when adding to result instead of intArray[i] & intArray[j]. Your code is currently getting an ArrayIndexOutOfBoundsException while trying to use intArray2 indices in intArray.
for (int i = 0; i < intArray2.length - 1; i++){
for(int j = i + 1; j < intArray2.length; j++){
if (Integer.parseInt(intArray2[i]) + Integer.parseInt(intArray2[j]) == sumTest){
result += intArray2[i] + ", " + intArray2[j] + ";";
System.out.println(result);
}
}
}
one option to remove the last semicolon would be to append to result as follows
//if not 1st pair, add semicolon
if(!result.equals("")){
result += "; ";
}
result += intArray2[i] + ", " + intArray2[j];
I'm pretty new to Java. Eclipse is giving me the error
This method must return a result of type
I want to return the String str, if I put str after all the for-loops I would get local variable not initialized. How could I code it so that
public String getQuadraticFactors() {
String str;
ArrayList<Integer> prFactors = new ArrayList<Integer>();
ArrayList<Integer> qsFactors = new ArrayList<Integer>();
ArrayList<Integer> p = getPRIntegerFactors(a), r = getPRIntegerFactors(a), q = getQSIntegerFactors(c),
s = getQSIntegerFactors(c);
System.out.println(p + "*********" + q);
System.out.println(p.get(0));
// String str2 = "jjjhljl";
String str2 = "(" + p + "x + " + q + ")(" + r + "x +" + s + ")";
for (int k = 0; k < p.size(); k++) {
// System.out.print(k);
for (int l = 0; l < q.size(); l++) {
// System.out.print(k);
for (int m = 0; m < p.size(); m++) {
for (int n = 0; n < q.size(); n++) {
if (p.get(k) * r.get(m) == a && p.get(k) * s.get(n) + q.get(l) * r.get(m) == b
&& q.get(l) * s.get(n) == c) {
System.out.println(a);
System.out.println(p.get(k) * r.get(m));
return str = "(" + p.get(k) + "x + " + q.get(l) + ")(" + r.get(m) + "x + " + s.get(n) + ")";
}
}
}
}
}
}
there is a slight possibility that you will never hit your return statement. To fix this, just add a return statement to the very bottom of your method that returns a empty string or whatever value you would like to send to say that
if (p.get(k) * r.get(m) == a && p.get(k) * s.get(n) + q.get(l) * r.get(m) == b
&& q.get(l) * s.get(n) == c)
this if statement is false for all cases. Sometimes you will never run into a situation where this if statement is false, but the JVM just needs reassurance that it has something to return if it is false.
Actually you need to have an alternative when some of your for-loops don't run. Just initialise your str with some value of better yet, check it at the bottom. If it is null throw an exception or initialize it (depending on your code style). When you check before returning it will always have a value (or you throw an exception).
How to get or print String from ArrayList<String[]>?
ArrayList<String[]> arrayList = new ArrayList<>();
arrayList.add(new String[]{"A1","A1","A3"});
arrayList.add(new String[]{"B1","B1","B3"});
arrayList.add(new String[]{"C1","C1","C3"});
System.out.println("*** 1 ***");
System.out.println(arrayList);
System.out.println("*** 2 ***");
for (int i = 0; i < arrayList.size(); i++) {
System.out.println((String[])arrayList.get(i));
}
System.out.println("*** 3 ***");
for (int i = 0; i < arrayList.size(); i++) {
System.out.println(arrayList.get(i).toString());
}
System.out.println("*** 4 ***");
for (int i = 0; i < arrayList.size(); i++) {
String[] strings = arrayList.get(i);
System.out.println(strings);
}
output:
*** 1 ***
[[Ljava.lang.String;#2a85f3d6, [Ljava.lang.String;#404b7c69, [Ljava.lang.String;#1bd4f279]
*** 2 ***
[Ljava.lang.String;#2a85f3d6
[Ljava.lang.String;#404b7c69
[Ljava.lang.String;#1bd4f279
*** 3 ***
[Ljava.lang.String;#2a85f3d6
[Ljava.lang.String;#404b7c69
[Ljava.lang.String;#1bd4f279
*** 4 ***
[Ljava.lang.String;#2a85f3d6
[Ljava.lang.String;#404b7c69
[Ljava.lang.String;#1bd4f279
Sadly, java's default toString() for arrays is useless. You must use the utility method Arrays.toString(). This will work:
for (String[] strings : arrayList)
System.out.println(Arrays.toString(strings));
In Java, each object has toString() method, the default is displaying the class name representation, then adding # and then the hashcode.
strings is an array of Strings. You should use Arrays#toString(), which is implemented this way (I advise you to go through it to better understand what's going on):
3860 public static String toString(int[] a) { {
3861 if (a == null)
3862 return "null";
3863 int iMax = a.length - 1;
3864 if (iMax == -1)
3865 return "[]";
3866
3867 StringBuilder b = new StringBuilder();
3868 b.append('[');
3869 for (int i = 0; ; i++) {
3870 b.append(a[i]);
3871 if (i == iMax)
3872 return b.append(']').toString();
3873 b.append(", ");
3874 }
3875 }
Or, you can loop on it and manually print the items:
for(String str: strings) {
System.out.println(str + " ");
}
Try to modify this :
**#Override
public String toString() {
return "abc [name=" + name + ", stage=" + stage
+ ", messageCode=" + messageCode + ", title=" + title
+ ", description=" + description + ", expiryTimeLeft="
+ expiryTimeLeft + ", holdLimit=" + holdLimit + ", points="
+ points];
}