If I have a String array as follows.
String[] name = {"aval", "H ---- ", "Singh", "Sawh", "Raman", " ---- ", "parminder", "kaur", "jaspreet", "asneet", " ---- "};
I want to copy all the contents from between "H ---- " to " ---- ". That is it should be "SinghSawhRaman" (excluding "H ---- " and " ---- ".
Something like this:
String keywords = "";
int j = 0;
for(int i = 0; i < name.length; i++){
if(name[i].contains("H ---- ")){
for(j = i; j < 5; j++){
// There problem is j < 5. I want to give a condition when name[i].contains(" ---- ")
// but not sure how should I be able to do it.
keywords = keywords + name[j];
}
Can someone please show me the best way to do this?
for(j = i; !name[j].contains(" ---- "); j++){
keywords = keywords + name[j];
}
That should work for you, you can set the break condition of a for loop to be any boolean expression.
Edit: Need the ! in there as loop breaks when condition is false.
Any reason that you use contains instead of equals ?
If using equals is also fine for you, you could use a List :
String[] name = {"aval", "H ---- ", "Singh", "Sawh", "Raman", " ---- ", "parminder", "kaur", "jaspreet", "asneet", " ---- "};
List<String> s = Arrays.asList(name);
StringBuilder sb = new StringBuilder();
for(int i = s.indexOf("H ---- ")+1; i < s.indexOf(" ---- "); i++)
sb.append(s.get(i));
System.out.println(sb);
I would do it like so
private static String copyFrom(String[] in, String begin, String end) {
StringBuilder sb = new StringBuilder();
boolean start = false;
if (in != null) {
for (String s : in) {
if (!start) {
start = s.equals(begin);
} else {
start = !s.equals(end);
if (start) {
sb.append(s);
}
}
}
}
return sb.toString();
}
public static void main(String[] args) {
String[] name = {"aval", "H ---- ", "Singh", "Sawh",
"Raman", " ---- ", "parminder", "kaur",
"jaspreet", "asneet", " ---- "};
String keywords = copyFrom(name, "H ---- ", " ---- ");
System.out.println(keywords);
}
Outputs
SinghSawhRaman
String keywords = "";
boolean append = false;
for(j = 0; j <= name.length; j++) {
if(name[j].contains("H----")
append = true;
if(append)
keywords += name[j];
if(name[j].contains("----") {
append = false;
break;
}
}
Notice that, if you move the if(name[j].contains("H----") block below the if(append) block, you will exclude the H--- from the keywords string;
Simply break out of the outer loop once your condition has been reached:
boolean capture = false;
for (String n : name) {
if (n.contains("H ---- ")) {
capture = true;
} else if (n.contains(" ---- ")) {
break;
} else if (capture) {
keywords = keywords + n;
}
}
If there are multiple occurrences of H ---- and ----, then don't break out of the loop, but simply set capture = false instead of break.
With two nested loops, you will be reading any elements that make up part of a name twice, which is inefficient. Unless it is possible to have names with nested H ----, you are better off removing the inner loop.
String[] name = {"aval", "H ---- ", "Singh", "Sawh", "Raman", " ---- ", "parminder", "kaur", "jaspreet", "asneet", " ---- "};
String key ="";
boolean flag = false;
for(String s : name){
if(s.equals("H ---- ")){
flag = true;
}
if(s.equals(" ---- ")){
flag = false;
}
if(flag && !s.equals("H ---- ")){
key+=s;
}
}
System.out.println(key);
Related
I've tried this to put white space between every '{':
String str = "t{esting";
StringBuilder sb = new StringBuilder(str);
int i;
for(i = 0; i<str.length(); i++) {
if(str.charAt(i)=='{'){
sb.insert(i, " ");
sb.insert(i+2, " ");
}
}
System.out.println(sb.toString());
}
It works fine for one '{':
t { esting
but if there are multiple '{' it does not work. for example: t{estin{g =
t { est i n{g where I want t { estin { g.
Thank you for having a look.
Simply replace every "{" by " { " like this:
String str = "t{esting";
String newStr = str.replace("{", " { ");
The following code implements the fixes suggested in Stephen C's comment
String str = "t{esting{";
StringBuilder sb = new StringBuilder(str);
for (int i = 0; i < sb.length(); i++) { // use sb.length
if (sb.charAt(i) == '{') { // check the character in sb (not str)
sb.insert(i, ' ');
sb.insert(i + 2, ' ');
i += 2; // jump over the shifted `{`
}
}
System.out.println("'" + sb.toString() + "'");
Output:
't { esting { '
However, String::replace or String::replaceAll methods are more suitable for such task.
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];
My array is:
String[][] name = new String[15][2];
int rowNumber = 0;
My add button is:
name[rowNumber][0] = firstName.getText();
name[rowNumber][1] = lastName.getText();
I do not know what to put in my list button (lists the first name and last name) into my TextArea called outPut.
The Whole Code:
`
public class StudentGradesView extends FrameView {
String[][] name = new String[15][2];
double[][] testMark = new double[15][4];
int rowNumber = 0;
private void btnAddMouseClicked(java.awt.event.MouseEvent evt) {
name[rowNumber][0] = firstName.getText();
name[rowNumber][1] = lastName.getText();
rowNumber ++;
}
private void btnListMouseClicked(java.awt.event.MouseEvent evt) {
String outputStr = "";
for(int i=0; i < rowNumber; i++) {
outputStr += name[rowNumber][0] + " " + name[rowNumber][1] + "\n";
}outPut.setText(outputStr);
}
}`
Okay, I think I get what you want now.
First we take the inputs...
name[numberOfInputs][0] = firstName.getText();
name[numberOfInputs][1] = lastName.getText();
numberOfInputs += 1;
Now you want to output this to a textarea...
String outputStr = "";
for(int i=0; i < numberOfInputs; i++) {
outputStr += name[i][0] + " " + name[i][1] + "\n";
}
Then set your output textarea
outPut.setText(outputStr);
You are getting nulls because you are specifying a static array size but you (probably) are not filling up the array with test cases up to that amount. So you are printing elements of the array that are simply not populated.
Edit: for comments.
String st = "";
for (int i = 0; i < 15; i++)
st += name[i][0] + " " + name[i][1] + "\n";
outPut.setText(value);
This loops over the array and creates a string containing all the full names, separated by a line break.
This then sets the text using outPut.setText(value);
for(String[] s1d : s2d)
for(String s : s1d)
System.out.println(s);
A simple way using for() construct
The easiest way to print any array to any depth is to use Arrays.deepToString():
System.out.println(Arrays.deepToString(array));
try this:
import java.util.Arrays;
.
.
.
String[][] a = { { "john" },
{ "jones" }
};
System.out.println(Arrays.deepToString(a)); //whole string array
System.out.println(Arrays.deepToString(a[0])); //john
System.out.println(Arrays.deepToString(a[1])); //jones
If I change the text to two words the program wont output anything. Not a clue on how to fix this, thanks in advance.
public class test {
public static void main(String args[]) {
String text = "The cat sat on the mat!"; //Change the string to "Hello there!"
int wordLengthCount [] = new int [20];
String wordCountText = "";
String sentence[] = text.split("[,\\-:\\?\\!\\ ]");
for (int i = 0; i < sentence.length; i++)
{
wordLengthCount[sentence[i].length()]++;
}
for(int wordLength=0; wordLength<sentence.length; wordLength++)
{
if (wordLengthCount[wordLength] != 0){
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
System.out.println(wordCountText);
}
}
You need to iterate over all wordLengthCount
Quick fix:
for (int wordLength = 0; wordLength < wordLengthCount.length; wordLength++) {
if (wordLengthCount[wordLength] != 0) {
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
Live demo