I need to find out out why the following code segment doesn't print the value in a swing application and how to resolve it.
String text = txtResults.getText();
StringTokenizer token = new StringTokenizer(text);
StringBuilder s = new StringBuilder();
while(token.hasMoreElements())
{
String value = token.nextElement().toString();
StringBuilder result = new StringBuilder();
for (int index = 0;index < value.length();index += 8) {
result.append((char) Integer.parseInt(value.substring(index, index + 8), 2));
s.append(result);
}
}
System.out.println(s);
Problem is with this line of code
StringTokenizer token = new StringTokenizer(text);
tokenizer breaks a string into tokens by a delimiter (default is " \t\n\r\f"). And as per your value of text that is binary (0010011001100111) will not be separated into tokens. Hope this helps.
Related
I am new to Java Strings.
Actually I have the code to reverse words:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test2 {
public static void main(String[] args) throws IOException
{
System.out.println("enter a sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String rev =br.readLine();
String [] bread = rev.split(" ");
for(int z =bread.length-1;z>=0;z--)
{
System.out.println(bread[z]);
}
}
}
For the above code I get:
Input :Bangalore is a city
Output: City is a Bangalore
But I want the output to be like below:
Input: Bangalore is a city
Output:cityaisba ng a lore
Another Example:
Input: Hello Iam New To Java.Java is object Oriented language.
Output: langu age Ori en tedo bjec ti sjava. javaToNe wIamolleH
Please help me out
Here is one way you could do it:
String rev = br.readLine();
String [] bread = rev.split(" ");
int revCounter = 0;
for(int z = bread.length - 1; z >= 0; z--)
{
String word = bread[z];
for(int i = 0; i < word.length(); i++)
{
// If char at current position in 'rev' was a space then
// just print space. Otherwise, print char from current word.
if(rev.charAt(revCounter) == ' ')
{
System.out.print(' ');
i--;
}
else
System.out.print(word.charAt(i));
revCounter++;
}
}
When I run your code I get following result:
city
a
is
Bangalore
So to have it in a single line, why don't you add a space and print a single line?
System.out.println("enter a sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String rev = br.readLine();
String[] bread = rev.split(" ");
for (int z = bread.length - 1; z >= 0; z--) {
System.out.print(bread[z] + " ");
}
I didn't check the validity of your code like GHajba did. But if you want spaces to remain on specific places it might be an option to remove all spaces and put them back according to their index in the original String.
Remove all
newBread = newBread.replace(" ", "");
Put them back
StringBuilder str = new StringBuilder(newBread);
for (int index = oldBread.indexOf(" ") ;
index >= 0 ;
index = oldBread.indexOf(" ", index + 1))
{
str.insert(index, ' ');
}
newBread = str.toString();
I came up with this quick and there might be better ways to do this, maybe without StringBuilder, but this might help you until you find a better way.
Try with this (i've used a string as input):
String original = "Bangalore is a city";
System.out.println("Original : "+original);
StringBuilder inverted = new StringBuilder();
StringBuilder output = new StringBuilder();
String temp = "";
String[] split = original.split("\\s+");
for (int i = split.length - 1; i >= 0; i--) {
inverted.append(split[i]);
}
temp = inverted.toString();
for (String string : split) {
int currLenght = string.length();
String substring = temp.substring(0,currLenght);
temp = temp.replaceAll(substring, "");
output.append(substring).append(" ");
}
System.out.println("Converted : "+output.toString());
Append the reversed words without the spaces into a StringBuffer.
StringBuffer b = new StringBuffer();
for (int i = bread.length-1; i >= 0 ; i--) {
b.append(bread[i]);
}
Then insert the spaces of the original String into the StringBuffer.
int spaceIndex, prevIndex = 0;
while ((spaceIndex = rev.indexOf(" ", prevIndex + 1)) != -1) {
b.insert(spaceIndex, ' ');
prevIndex = spaceIndex;
}
I am trying to read a PDF file in Java by using Itext. In my PDF file I have some calculation results. In a line there is an element and its two calculation results and they are not in a table. My PDF file looks like this :
I. Result X 12.551.734,75 9.284.925,26
. A. Result Y 8.583.482,18 416.187,03
. 1. result z 83.708,72 91.220,23
. 3. result a 8.499.773,46 324.966,80
. B. Result B 0,00 199.942,00
. 4. result c 0,00 199.942,00
. C. Result D 780.316,81 5.376.366,65
. 1. result e 66.041,73 3.962.399,52
. 2. result f 685.579,00 1.367.086,66
What I am trying to do is parse the string and its values. I couldn't find a proper way and I tried the code below. But the problem with this logic for the line :
. 1. result z 8.583.482,18 416.187,03
it prints just "." for the string then 1 and the first number. I couldn't get the whole ". 1. result z" part as string and then its values because it prints directly after seeing an int value and skips rest.
int page = 1;
PdfReader reader = new PdfReader(pdf);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
strategy = parser.processContent(page, new LocationTextExtractionStrategy());
Scanner scanner = new Scanner(strategy.getResultantText());
...
for (int j = page; j <= reader.getNumberOfPages(); j++) {
while (scanner.hasNextLine()) {
String nextToken = scanner.nextLine();
String rName = "";
StringTokenizer tok = new StringTokenizer(nextToken);
while (tok.hasMoreTokens()) {
String nToken = tok.nextToken();
try {
number = fmt.parse(nToken);
System.out.println(rName);
System.out.println(number);
while (tok.hasMoreTokens()) {
try {
nToken = tok.nextToken();
number = fmt.parse(nToken);
System.out.println(number);
} catch (ParseException e) {
if(rName.isEmpty()){
rName = nToken;
}else{
rName = rName + " " + nToken;
}
}
}
break;
} catch (ParseException e) {
if(rName.isEmpty()){
rName = nToken;
}else{
rName = rName + " " + nToken;
}
}
}
}
strategy = parser.processContent(++page, new LocationTextExtractionStrategy());
scanner = new Scanner(strategy.getResultantText());
}
How can I get these strings and their values correctly, could you help me please? Is there any other useful way to do it as I think this solution is not good enough?
Thank you for all the detail you provided. Typically you'd use a regular expression to parse complicated lines. Though sometimes programmatic parsing is a bit easier to follow. Rather than using the StringTokenizer to split the line, perhaps try:
String line = scanner.nextLine();
String[] tokens = line.split("\\s+");
String value1 = tokens[tokens.length-2];
String value2 = tokens[tokens.length-1];
String rowTitle = line.substring(0, line.indexOf(value1)).trim();
System.out.print(rowTitle + "\t");
System.out.print(value1 + "\t");
System.out.println(value2);
Am I reading the following input correctly?
Here is my code so far:
while ((line = br.readLine()) != null) {
line = line.substring(line.indexOf('[')+1, line.indexOf(']'));
String[] parts = line.split(",");
for (int i = 0; i< parts.length; i++) {
rangeNo[i]= Integer.parseInt(parts[i]);
System.out.println("{" + rangeNo[i] + "}");
}
}
and this is my input
[2,9], [3,11]
Also, when I try to print the value of rangeNo[3] it return 0 instead of 3
can someone help me out with this?
Do you expect [2,9], [3,11] to be in one line or two separate lines?
If its supposed to be one line then you might want to try something like this
Integer rangeNo[] = new Integer[10];
String line = "[2,9], [3,11]";
line = line.replace('[', ' ');
line = line.replace(']', ' ');
String[] parts = line.split(",");
for (int i = 0; i < parts.length; i++) {
rangeNo[i] = Integer.parseInt(parts[i].trim());
System.out.println("{" + rangeNo[i] + "}");
}
when you check here
line = line.substring(line.indexOf('[')+1, line.indexOf(']'));
it's matching first condition. i.e works fine for [2,9] not after that thus only 2 and 9 are getting stored here.
String[] parts = line.split(",");
so
parts[0]=2
parts[1]=9
parts[2]=0
I am working on a code-editor in java and i want to know how to auto-indent using brackets (open and close) like an actual code editor .
like this 1:
Array PrincipalVar = (Var => (OtherVar => (var3 => 3,
var4 => 8,
var6 => 1)
),
Var2 => (var => 1))
Editor is a JEditorPane. I tried some code, but nothing seem to work.
I have already file contening code, and I want to Re-Indent this file.
Code I already tried :
public String indentFileTry() throws FileNotFoundException{
LinkedList<Integer> inBracket = new LinkedList<Integer>();
String currentLine = "";
Scanner indent = new Scanner(new FileReader(f));
String ptu = "";
while(indent.hasNextLine()) {
currentLine = indent.nextLine();
currentLine = currentLine.trim();
char[] line = currentLine.toCharArray();
int i = 0;
while(i < line.length){ //Here I define the position of the Bracet for Indentation
if(line[i] == '('){
inBracket.addFirst(i);
}
i++;
}
if(!inBracket.isEmpty()){//here I indent with the position of the bracket and I remove the first(First In First Out)
if(!currentLine.contains(")")){
int spaceadded = 0;
String space ="";
while(spaceadded <= inBracket.getFirst()){
spaceadded++; space += " ";
}
currentLine = space + currentLine;
inBracket.removeFirst();
}else if(currentLine.contains(")")){
int spaceadded = 0;
String space ="";
while(spaceadded <= inBracket.getFirst()){
spaceadded++; space += " ";
}
currentLine = space + currentLine;
inBracket.removeFirst();
}
}
ptu += currentLine +"\n";
}
indent.close() ;
System.out.println(ptu);
return ptu;
}
If you expect automatically indentation you won't get such code. You should implement it yourself adding \n spaces (or \t) chars to format your code. JEditorPane does not understand your code logic. You (with your code parser) should define parent/child relation for lines of code you have.
One example for the case when parent/children are defined is XML. See the XMLEditorKit where nodes are indented.
For the response, What I do is easy.
I made a LinkedList, and I use it like a FILO (First in Last out) like this :
public String indentFile() throws FileNotFoundException{
LinkedList<Integer> positionBracket = new LinkedList<Integer>();
String currentLine = "";
Scanner indent = new Scanner(new FileReader(f));
String stringIndented = "";
while(indent.hasNextLine()) {
currentLine = indent.nextLine();
currentLine = currentLine.trim();
char[] lineInChar = currentLine.toCharArray();
int i = 0;
int spaceadded = 0;
String space ="";
if(!positionBracket.isEmpty()){
while(spaceadded <= positionBracket.getFirst()){
spaceadded++;
space += " "; // We put same space like the last opened bracket
}
}
while(i < lineInChar.length){
if(lineInChar[i] == '('){ //If opened bracket I put the position in the top of the Filo
positionBracket.addFirst(new Integer(i));
}
if(lineInChar[i] == ')' && !countCom){
positionBracket.removeFirst(); //If closed bracket I remove the position on the top of the Filo
}
i++;
}
stringIndented += space + currentLine +"\n";
}
}
return stringIndented;
}
I'm trying to add a count number for matching words, like this:
Match word: "Text"
Input: Text Text Text TextText ExampleText
Output: Text1 Text2 Text3 Text4Text5 ExampleText6
I have tried this:
String text = "Text Text Text TextText ExampleText";
String match = "Text";
int i = 0;
while(text.indexOf(match)!=-1) {
text = text.replaceFirst(match, match + i++);
}
Doesn't work because it would loop forever, the match stays in the string and IndexOf will never stop.
What would you suggest me to do?
Is there a better way doing this?
Here is one with a StringBuilder but no need to split:
public static String replaceWithNumbers( String text, String match ) {
int matchLength = match.length();
StringBuilder sb = new StringBuilder( text );
int index = 0;
int i = 1;
while ( ( index = sb.indexOf( match, index )) != -1 ) {
String iStr = String.valueOf(i++);
sb.insert( index + matchLength, iStr );
// Continue searching from the end of the inserted text
index += matchLength + iStr.length();
}
return sb.toString();
}
first take one stringbuffer i.e. result,Then spilt the source with the match(destination).
It results in an array of blanks and remaining words except "Text".
then check condition for isempty and depending on that replace the array position.
String text = "Text Text Text TextText ExampleText";
String match = "Text";
StringBuffer result = new StringBuffer();
String[] split = text.split(match);
for(int i=0;i<split.length;){
if(split[i].isEmpty())
result.append(match+ ++i);
else
result.append(split[i]+match+ ++i);
}
System.out.println("Result is =>"+result);
O/P
Result is => Text1 Text2 Text3 Text4Text5 ExampleText6
Try this solution is tested
String text = "Text Text Text TextText Example";
String match = "Text";
String lastWord=text.substring(text.length() -match.length());
boolean lastChar=(lastWord.equals(match));
String[] splitter=text.split(match);
StringBuilder sb = new StringBuilder();
for(int i=0;i<splitter.length;i++)
{
if(i!=splitter.length-1)
splitter[i]=splitter[i]+match+Integer.toString(i);
else
splitter[i]=(lastChar)?splitter[i]+match+Integer.toString(i):splitter[i];
sb.append(splitter[i]);
if (i != splitter.length - 1) {
sb.append("");
}
}
String joined = sb.toString();
System.out.print(joined+"\n");
One possible solution could be
String text = "Text Text Text TextText ExampleText";
String match = "Text";
StringBuilder sb = new StringBuilder(text);
int occurence = 1;
int offset = 0;
while ((offset = sb.indexOf(match, offset)) != -1) {
// fixed this after comment from #RealSkeptic
String insertOccurence = Integer.toString(occurence);
sb.insert(offset + match.length(), insertOccurence);
offset += match.length() + insertOccurence.length();
occurence++;
}
System.out.println("result: " + sb.toString());
This will work for you :
public static void main(String[] args) {
String s = "Text Text Text TextText ExampleText";
int count=0;
while(s.contains("Text")){
s=s.replaceFirst("Text", "*"+ ++count); // replace each occurrence of "Text" with some place holder which is not in your main String.
}
s=s.replace("*","Text");
System.out.println(s);
}
O/P:
Text1 Text2 Text3 Text4Text5 ExampleText6
I refactored #DeveloperH 's code to this:
public class Snippet {
public static void main(String[] args) {
String matchWord = "Text";
String input = "Text Text Text TextText ExampleText";
String output = addNumbersToMatchingWords(matchWord, input);
System.out.print(output);
}
private static String addNumbersToMatchingWords(String matchWord, String input) {
String[] inputsParts = input.split(matchWord);
StringBuilder outputBuilder = new StringBuilder();
int i = 0;
for (String inputPart : inputsParts) {
outputBuilder.append(inputPart);
outputBuilder.append(matchWord);
outputBuilder.append(i);
if (i != inputsParts.length - 1)
outputBuilder.append(" ");
i++;
}
return outputBuilder.toString();
}
}
We can solve this by using stringbuilder, it provides simplest construct to insert character in a string. Following is the code
String text = "Text Text Text TextText ExampleText";
String match = "Text";
StringBuilder sb = new StringBuilder(text);
int beginIndex = 0, i =0;
int matchLength = match.length();
while((beginIndex = sb.indexOf(match, beginIndex))!=-1) {
i++;
sb.insert(beginIndex+matchLength, i);
beginIndex++;
}
System.out.println(sb.toString());