Looking for best way to do this program [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have two .txt files, first one looks like this :
XXXXXXX
XX0X0XX
XX000XX
XXXX0XX
XXXXXXX
and second like this :
.1..
.111
...1
....
First file needs to be seen as a hole made out of zeros and second as a figure make out of ones. I need to write an algorithm that reads both files and checks if "figure" out of second txt file fits into "hole" out of first one. What do you think is the most efficient way to do that ?
I think the best way is to read both files into arrays and then make comparision between arrays, but this is just my first thoughts.
Also final file should look like this :
XXXXXXX
XX1X0XX
XX111XX
XXXX1XX
XXXXXXX

One way could be to:
Load the first file in one array
Iterate over the second file and compare what you have in the array with what you have read in the file.

You can read both files line by line. Pass nth line from both the files to the following method:
public static boolean isFit(String a, String b) {
return a.replace('X', '.').replace('0', '1').equals(b);
}
If it return false then it is a mis-match otherwise at the end you can say that it is a match.

Here's a small method I threw together that determines whether or not a particular line of the figure matches a particular line in the hole.
public static int figureLineFits(char[] figure, char[] hole){
// Since figure max length per line is 4 and hole is 5
// we have to try to match it on either one end or the other.
char[] hole1 = Arrays.copyOfRange(hole, 0, hole.length-1);
char[] hole2 = Arrays.copyOfRange(hole, 1, hole.length);
// We get rid of the extra holes in the hole array.
for (int i = 0; i < 4; i++){
if(figure[i] == '.'){
if(hole1[i] == '0') hole1[i] = 'X';
if(hole2[i] == '0') hole2[i] = 'X';
}
}
// Convert the arrays to Strings because I'm
// lazy to lookup equivalent array methods.
String compFigure = figure.toString();
String compHole1 = hole1.toString();
String compHole2 = hole2.toString();
// Replace the 0s with 1s and Xs with .s in the hole strings.
compHole1.replace('0', '1');
compHole1.replace('X', '.');
compHole2.replace('0', '1');
compHole2.replace('X', '.');
// Set up some comparison booleans.
boolean leftComparison = compFigure.equals(compHole1);
boolean rightComparison = compFigure.equals(compHole2);
// Do some boolean logic to determine how the figure matches the hole.
// Will return 3 if figure can be matched on both sides.
// Will return 1 if figure can be matched on left side.
// Will return 2 if figure can be matched on right side.
// Will return 0 if figure doesn't match on either side.
if(leftComparison && rightComparison) return 3;
if(leftComparison) return 1;
if(rightComparison) return 2;
return 0;
}
Then you read the first line of the figure and try to match it with the lines of the hole.
If you can match it (the figureLineFits function doesn't return 0) then you can try to match the second line of the figure to the next line of the hole.
If that comparison doesn't return 0 then you have to check if the match is adequate, e.g. if the first line returned 1 and the next one returned 2 then the figure doesn't match. If the first line returned 3 and the second line returned either 1 or 2 then the match is adequate since the "3" means that it matches on both sides.
If you see that the match is not adequate you have to then go back to the first line of the figure and continue to match it on the line after you matched the first figure line not the consecutive figure lines since the first figure line might also match the second hole line although the second figure line didn't match the second hole line.
Hopefully this will get your head going in the right direction.

Related

How to write a for loop for encoding and decoding in java? the program only encode one letter when I enter a string. College level 1 lesson [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I should write a encoding and decoding program in a class and then use it in main. The program needs the position for each letter to increase by 2.
When I run the program, the problem is that when I enter a string (like cookie), only the last letter is encoding. Here is a Screenshot of program running.
What is the problem for my program.
Thanks.
The lesson is very basic tho and the assignment are forbid students import any other java method like base64.Only use the starter code.
The code I will put here as well
public class SimpleCipher {
/*
* comments here to overview the method
*/
public String encode(String text) {
String result = "";
char[] chars = text.toCharArray();
int length = chars.length;
for (char x: chars) {
x+=2;
result = Character.toString(x);
}
// ToDo
// convert text into char array
// reverse the array using provided method (see below)
// loop over array adding 2 to each element
// convert the char array back to a String named result
// return the resulting String.
return result;
}
The main problem is that you are overwriting your result in each iteration.
Instead you want to append the character to the result string.
You can simply do that with
result = result + Character.toString(x);
result += Character.toString(x); // shorter version
result += x; // java can append characters to strings without explicit conversion
According to the comment that is - even tho it is working - not the desired solution anyways. The task is to create a new character array and fill it.
Do that by creating a new array of the same length as the original, iterating over the indexes of your arrays ( for (int i=0; i<chars.length; i++) ) and for each index write the updated character into the new array. The string class has a constructor that accepts a char array.

How can I fix my code to find a certain character in an array and make changes to that array

while (scan_file.hasNext()) {
String b = scan_file.nextLine();
// checks if string b contains the tag <h>
if (b.contains("<h>")) {
char arrayString[] = b.toCharArray();
for (int i = 0; i < arrayString.length; i++) {
if (arrayString[i] == '<') {
arrayString[i] = arrayString[i + 2];
}
System.out.print(arrayString[i]);
}
}
}
What I was expecting the program to do was(for now) iterate through the while loop and store each line as string 'b'.
I want to check if that string b contains a certain string like <h> for this example. And I want to convert string b into an array if it contains said string like <h> and iterate through that array to check for '<' and move the array up 2 spaces.
For example, string b had <h>hello, I wanted to eventually print hello because the program would have moved up 2 elements.
I feel like I got the loops and general idea on how I want to tackle the problem.. but when I ran the program, nothing printed so I don't know if I did the loops and if statements correctly.
I really don't know how to word my problem well, so bear with me and I'm sorry in advance.
All feedbacks are greatly appreciated (:
System.out.print(arrayString[i]); just print the ith character of arrayString, it's definitely not what you want.
In fact you don't have to convert a String to char[], String has many utils method can help you with your goal.
I won't give you full code , but I can give you some tips.
You can use String.indexof('<') to find the index of '<'.
You can use String.subString(startIndex) to get the subString start with the specified index.
Suppose your code scan_file.hasNext() and scan_file.nextLine() is work well. You can try code below to remove all from current line:
if (b != null && b.contains("<h>")) {
System.out.println(b.replaceAll("<h>", ""));
}

How should I print out the position of the first occurrence of a specific letter in a String? [duplicate]

This question already has answers here:
Java: method to get position of a match in a String?
(14 answers)
Closed 2 years ago.
Say my string is as follows
String str = "What is up tod?";
I want to use an accessor method to print out the position of the first occurrence of the letter "t". What is an efficient use of code to use? I also want to ensure that it doesn't try to tell me the occurrence of the second "t". Please keep in mind I am searching for how to do this in Java.
Any help or link to similar question is greatly appreciated.
Unless I'm missing something, use String.indexOf(int) like
String str = "What is up tod?";
System.out.println(str.indexOf('t'));
Which outputs the first match
3
Alternatively, iterate the characters of the String from left to right checking for 't'; if you find it, print the index and terminate the loop. Like,
String str = "What is up tod?";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 't') {
System.out.println(i);
break;
}
}

How to get part of string between something? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have the string aaabbbccc.What is the best way to get bbb part?
UPD:
How to get ccc from aaabbbcccdddfff?
s.substring(s.indexOf("b"), s.lastIndexOf("b")-1)
StringUtils.substringBetween("aaabbbccc", "aaa", "ccc")
using StringUtils.substringBetween(...) from here
In this specific case,
String bbbString = "aaabbbccc".substring(3,6);
In response to the bit you just added to your question, I would say use the following function
public String getRepetitiveSubstringOf(String string, char desiredCharacter)
{
String theSubstring = null;
char[] charArray = string.toCharArray(); //it is more efficient to use arrays
//get the beginning position
int beginPosition = string.indexOf(desiredCharacter);
//get the end position (the desired substring length might NOT be 3, but rather, in this case,
//where the character value changes)
int endPosition = beginPosition;
//looping until we have either found a different character, or until we have hit the end of the
//character array (at the end, we loop one more time so that we can hit a garbage value that
//tells us to stop)
while ((charArray[endPosition] == desiredCharacter) || (endPosition < charArray.length))
{
endPosition++;
}
//if we have hit the garbage value
if (endPosition == charArray.length)
{
//we substring all the way to the end
theSubstring = string.substring(beginPosition);
}
else
{
//now, we check to see if our desiredCharacter was found AT ALL in the string
if (desiredCharacter > -1)
{
theSubstring = string.substring(beginPosition, endPosition);
}
}
return theSubstring;
}
From there, you can check for a return value of null
Try StringUtils.subStringBetween
String value = "aaabbbccc";
StringUtils.substringBetween(value, "aaa", "ccc");
For the string that you have specified you can use the code:
String result=s.substring(s.indexOf('b'),s.lastIndexOf('b'));
where s is your string,
For a more general string:
String result =s.substring(first index,last index);
where first index and last index are range that you want to extract.
Example:
String S="rosemary";
String result=s.substring(4,s.length());
This will store "mary" in the result string.
You only need one line and one method call if you use regex to capture the target group:
String middle = str.replaceAll(".*aaa(.*)ccc.*", "$1");
The best way maybe regEx.You could use
String str = str.replaceAll(a

Novice programmer needs advice: "String index out of range" - Java

I'm pretty new to programming and I'm getting a error which I'm sure is a easy fix for more experienced people.
Here is what I have:
import java.io.*;
import java.util.Scanner;
public class ReadNamesFile
{
public static void main(String[] args) throws IOException {
// make the names.csv comma-separated-values file available for reading
FileReader f = new FileReader("names.csv");
BufferedReader r = new BufferedReader(f);
//
String lastName="unknown", firstName="unknown", office="unknown";
// get first line
String line = r.readLine();
// process lines until end-of-file occurs
while ( line != null )
{
// get the last name on the line
//
// position of first comma
int positionOfComma = line.indexOf(",");
// extract the last name as a substring
lastName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the first name as a substring
firstName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the office number as a substring
office = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+2);
//
//
//
// display the information about each person
System.out.print("\nlast name = "+lastName);
System.out.print("\t first name = "+firstName);
System.out.print("\t office = "+office);
System.out.println();
//
// get the next line
line = r.readLine();
}
}
}
Basically, it finds the last name, first name and office number in a .csv file and prints them out.
When I compile I don't get any errors but when I run it I get:
java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1955)
at ReadNamesFile.main(ReadNamesFile.java:34)
Before trying to do the office number part, the first two (last and first name) printed out fine but the office number doesn't seem to work.
Any ideas?
Edit: Thanks for all the posts guys, I still can't really figure it out though. Can someone post something really dumbed down? I've been trying to fix this for an hour now and I can't get it.
Let's work by example, what issues you have with your code.
Eg: line: Overflow,stack
{ length: 14 }
Taking your program statements line by line -
int positionOfComma = line.indexOf(","); // returns 9
lastName = line.substring(0,positionOfComma); // should be actually postionOfComma-1
Now lastName has Overflow. positionOfComma has 9.
line = line.substring(positionOfComma+1);
Now line has stack.
firstName = line.substring(0,positionOfComma);
Asking substring from 0 to 9. But stack is only of length 5. This will cause String index out of range exeception. Hope you understood where you are doing wrong.
From JavaDoc:
(StringIndexOutOfBoundsException) - Thrown by String methods to
indicate that an index is either negative or greater than the size of
the string.
In your case, one of your calls to .substring is being given a value that is >= the length of the string. If line #34 is a comment, then it's the line above #34.
You need to:
a) Make sure you handle the case if you DON'T find a comma (i.e. if you cannot find and extract a lastName and/or firstName string)
b) Make sure the value of "positionOfComma + N" never exceeds the length of the string.
A couple of "if" blocks and/or "continue" statements will do the trick nicely ;-)
You correctly find positionOfComma, but then that logic applies to the original value of line. When you remove the last name and comma, positionOfComma is no longer correct as it applies to the old value of line.
int positionOfComma = line.indexOf(",");
this line of code might not find a comma and then positionOfComma will be -1. Next you substring something with (0,-1) - eeek no wonder it gives StringIndexOutOfBoundsException. Use something like:
int positionOfComma = 0;
if(line.indexOf(",")!=-1)
{
positionOfComma = line.indexOf(",");
}
You do have to do lots of checking of things sometimes especially when the data is whacked :(
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)
PS I'm sure someone clever can make my coding look shabby but you get the point I hope :)

Categories

Resources