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
Related
Hello guys and thank you in advance for your help!
I am trying to do a matrice calculator in java
that reads two matrices from the same file like this:
2 2
34 78
89 -12
#
2 2
67 76
123 5
first line is the rank
second and third line are the first matrix
the "#" splits the first and the second matrix
and that's the code I came up with and I didn't
find anything similar to this problem... can someone help me please?
String [] line = new String[30];
int counter = 2;
int rank[] = new int[2];
int matrixa[][] = new int [3][3];
try {
BufferedReader MyReader = new BufferedReader(new FileReader("matrix.txt"));
while(line != null) {
line = MyReader.readLine().split(" ");
}
rank[0] = Integer.parseInt(line[0]);
rank[1] = Integer.parseInt(line[1]);
for(int i = 0; i <rank[0];i++) {
for (int j=0;j<rank[1];j++) {
matrixa[i][j] = Integer.parseInt(line[counter]);
counter++;
System.out.print(matrixa[i][j] + " ");
}
System.out.println();
} }catch (Exception e) {}
Leaving a ticker variable at when your lines is equal to "#"
int ticker;
for(int i = 0; i < lines.length; i++){
if(lines[i].equals("#")) ticker = i;
}
This ticker then can be used to break the array. This could also be used earlier to break up the array into 2 separate arrays if that is expected.
String currentLine;
String[] line = new String[15];
String[] line2 = new String[15];
int i = 0;
while(line != null && !currentLine.equals("#")){
line = MyReader.readLine().split("");
currentLine = line[i];
if(currentLine.equals("#")) line[i] = null;
i++;
}
while(line2 != null)){
line2 = MyReader.readLine().split("");
}
They can be parsed into matrices and then math can be done on them from there.
Best of luck with your endeavors.
I have a CSV file with the following information:
2,Cars
5,Cars
5,Planes
5,Boats
10,Planes
10,Boats
28,Planes
I want to split the numbers from the type of transportation. How can I count the total of cars + planes + boats to be '3' and not '7'?
I am using the following Java code that someone else provided to split the CSV:
try {
BufferedReader br2 = new BufferedReader(new FileReader("transport.csv"));
System.out.println("\nTESTING");
String sCurrentLine2;
java.util.HashMap<String, String>();
while ((sCurrentLine2 = br2.readLine()) != null) {
String[] information2 = sCurrentLine2.split(",");
String transCode = information2[1];
System.out.println(transCode);
}
} catch (IOException e) {
e.printStackTrace();
}
In the array String transCode = information2[1]; when I change to 0 it will give the numbers, when I change to 1 gives the names.
while((sCurrentLine2 = br2.readLine()) != null{
String[] entries = sCurrentLine2.split(",");
Set<String> types = new Hashset<>();
for(int i = 0; i < entries.length; i++){
String[] entry = entries[i].split(" ");
types.add(entry[0]);
}
System.out.println(types.size());
}
I modified the code you provided. Maybe there is another way to do it better, but this is what I did. I forced it a little and gave '3' as result. But it should have done it counting the words not considering duplicated.
while ((line2 = br2.readLine()) != null) {
String[] entries = line2.split(",");
for (int i = 0; i < entries.length; i++) {
String[] entry = entries[i].split(" ");
termsDup.add(entry[0]);
}
}
System.out.println(termsDup.size()-4);
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 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 have written the following code to read a tile map from a text file, however I am getting a null point exception error for a reason I can't figure out.
Code of the reader:
BufferedReader br = new BufferedReader(new FileReader(s));
readMapWidth = Integer.parseInt(br.readLine());
readMapHeight = Integer.parseInt(br.readLine());
map = new int[readMapHeight][readMapWidth];
for(int row = 0; row < readMapHeight; row++) {
String line = br.readLine();
System.out.println(line);
String[] tileValues = line.split(",");
for(int col = 0; col < readMapWidth; col++){
map[row][col] = Integer.parseInt(tileValues[col]);
}
}
}
The text file content:
What the command console returns as an error:
java.lang.NullPointerException
at TileMap.<init>(TileMap.java:58)
which is line:
String[] tileValues = line.split(",");
The lines read perfectly and I can draw the map to the screen. however I need an actually stored 2d array to use for pathfinding later, but this line is returning a null value and I can't understand why.
Here is what the "System.out.println(line)" returns that confuses me:
[final line of the map here, map lines print as normal]
null
The null? I don't understand, my text file only has 27 lines where is the null exception regarding split coming from?
It seems you have reached the end of file or encountered an empty line, causing your line String to be null here:
String[] tileValues = line.split(",");
better you put a check for end of file or at least put a null check on line before you operate on it to split it.
for(int row = 0; row < readMapHeight; row++) {
String line = br.readLine();
if(line == null || line.isEmpty()) {
System.out.println("Line is empty or null");
} else {
System.out.println(line);
String[] tileValues = line.split(",");
for(int col = 0; col < readMapWidth; col++){
map[row][col] = Integer.parseInt(tileValues[col]);
}
}
}
Two things stand out...
br.readLine() returns null when it reaches the end of the file.
Your file only contains 25 lines of data (after the height and width lines). Ie 27 - 2 = 25
A better approach might be to do something like...
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(s));
readMapWidth = Integer.parseInt(br.readLine());
readMapHeight = Integer.parseInt(br.readLine());
map = new int[readMapHeight][readMapWidth];
int row = 0;
String text = null;
while ((text = br.readline()) != null) {
System.out.println(line);
String[] tileValues = line.split(",");
for(int col = 0; col < readMapWidth; col++){
map[row][col] = Integer.parseInt(tileValues[col]);
}
row++;
}
// Zero index rows...
if (row < readMapHeight - 1) {
throw IOException("Expected title height does not match actual row height");
}
} finally {
try {
br.close();
} cacth (Exception exp) {
}
}
If your texture size is correct, you might be expecting a total of 27 lines, not just 27 lines for the texture, so you would need to adjust the row count accordingly
you should replace your data file before start
var readed_data:String = read whole data as String;
while (readed_data.search("\r") != -1) //MAC line reset cmd
{
readed_data = readed_data.replace("\r", ""); //replace to nullstring
{
while (readed_data.search("\r") != -1) //UNIX line reset cmd
{
readed_data = readed_data.replace("\n", ""); //replace to nullstring
{
//And so Windows uses both of "\n" and "\r" strings in text files as a quarantee, now you can read your data as you wish... now all data is single line data and you can split with "," comma after this time easily and without unneeded characters