Get the index of the start of a newline in a Stringbuffer - java

I need to get the starting position of new line when looping through a StringBuffer.
Say I have the following document in a stringbuffer
"This is a test
Test
Testing Testing"
New lines exist after "test", "Test" and "Testing".
I need something like:
for(int i =0;i < StringBuffer.capacity(); i++){
if(StringBuffer.chatAt(i) == '\n')
System.out.println("New line at " + i);
}
I know that won't work because '\n' isn't a character. Any ideas? :)
Thanks

You can simplify your loop as such:
StringBuffer str = new StringBuffer("This is a\ntest, this\n\nis a test\n");
for (int pos = str.indexOf("\n"); pos != -1; pos = str.indexOf("\n", pos + 1)) {
System.out.println("\\n at " + pos);
}

System.out.println("New line at " + stringBuffer.indexOf("\n"));
(no loop necessary anymore)

Your code works fine with a couple of syntactical modifications:
public static void main(String[] args) {
final StringBuffer sb = new StringBuffer("This is a test\nTest\nTesting Testing");
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '\n')
System.out.println("New line at " + i);
}
}
Console output:
New line at 14
New line at 19

Related

How can I align my text in the terminal? (Java)

My code accepts 3 arguments, first (args[0]) is the text file, second (args1) is the number of characters per line and the final argument (args[2]) is not yet implemented but is the option of the alignment (Left, Center or Justify).
Right now, I am trying to implement the left alignment and here is my code (the alignment code comes the last):
try {
System.out.println("usage: java AlignText" + args[0] + " " + args[1] + "
" + args[2]);
String[] text = FileUtil.readFile(args[0]);
int paragraphs = Integer.parseInt(args[1]);
StringBuilder builder = new StringBuilder();
for (String string : text) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(string);
}
String str = builder.toString();
StringBuilder sb = new StringBuilder();
int i = str.indexOf(" ",paragraphs);
while (i>0){
sb.append(str.substring(0, i).trim());
sb.append("\n");
str = str.substring(i);
if(str.length()>paragraphs){
i = str.indexOf(" ", paragraphs);
}
else {
i = -1;
}
}
sb.append(str.trim());
sb.toString();
//System.out.println(sb.length());
String[] lines = new String[100];
int count = 0;
int index = 0;
for(int j=0;j<sb.length();j++){
if(sb.charAt(j) == '\n') {
lines[index] = sb.substring(count,j).trim();
System.out.printf("%20s"+"\n", lines[index]);
//System.out.println("\n");
count = j;
index++;
}
}
And here is my output:

Reverse a string as per length of first word

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;
}

store 1d array from text file java

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

AutoIndent bracket in Java Swing JeditorPane

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;
}

How can I write this .txt file into a 2D int array and not receive a NumberFormatException?

I have been attempting to save a 9x9 2D array of ints from a .txt file. I have been on this website for a very long time attempting to get this to work and after doing a ton of tweaking, I am very close to getting it. The only problem is that nothing saves to the array!
Here is my code:
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.awt.*;
public class test {
public static void main(String[] args) throws IOException {
int[][] thing = new int[9][9];
int row = 0;
int rows = 9;
int columns = 9;
File fin = new File("C:\\Users\\David\\workspace\\tester\\initial.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fin));
String line = reader.readLine();
int lineNum = 0;
while (line != null) {
lineNum++;
System.out.println("line " + lineNum + " = " + line);
line = reader.readLine();
String [] tokens = line.split(",");
for (int j=0; j<tokens.length; j++) {
System.out.println("I am filling the row: " + row);
thing[row][j] = Integer.parseInt(tokens[j]);
}
row++;
}
System.out.println("I am printing the array for testing purposes: ");
for (int i=0; i < rows; i++) {
for (int j = 0; j < columns; j++)
System.out.print(thing[i][j]);
System.out.println("");
}
} catch (IOException error) {
} finally {
if (reader != null) reader.close();
}
}
}
I should say that I am doing this as a test for a sudoku game I am trying to create as a mere side project, I am just super frustrated.
This was also my first post on this site so go easy on me for the formatting. Thanks all!
Edit: I made the change codaddict told me too and now I get the output:
line 1 = 5 3 0 0 7 0 0 0 0
I am filling the row: 0
Exception in thread "main" java.lang.NumberFormatException: For input string: "6 0 0 1 9 5 0 0 0"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at test.main(test.java:36)
You are doing:
while (line != null) {
lineNum++;
System.out.println("line " + lineNum + " = " + line);
line = reader.readLine();
}
// At this point you've already reached the end of the file
// and line is null, so you never go inside the next while.
while (line != null) {
// you need to split on space not comma
String [] tokens = line.split(" ");
for (int j=0; j<tokens.length; j++) {
System.out.println("I am filling the row: " + row);
thing[row][j] = Integer.parseInt(tokens[j]);
}
row++;
}
To fix this you need to process each line in the outer while loop:
while (line != null) {
lineNum++;
System.out.println("line " + lineNum + " = " + line);
line = reader.readLine();
String [] tokens = line.split(",");
for (int j=0; j<tokens.length; j++) {
System.out.println("I am filling the row: " + row);
thing[row][j] = Integer.parseInt(tokens[j]);
}
row++;
}
The string line is already null after exiting the first while loop and hence the second while loop is never executed, and hence no values get assigned to the array cells, the default value of int array cells being zero which gets printed. Insert the assigning part in the first loop to solve the problem.
you have read the whole file in the first while loop itself.
So, you are unable to print the values in the second loop.
Make sure you are storing the values from the text file in the first while loop.
while (line != null) {
lineNum++;
System.out.println("line " + lineNum + " = " + line);
line = reader.readLine();
String [] tokens = line.split(",");
for (int j=0; j<tokens.length; j++) {
System.out.println("I am filling the row: " + row);
thing[row][j] = Integer.parseInt(tokens[j]);
}
row++;
}

Categories