Need to port Visual Basic .NET code to Java - java

Try
Dim sr As New IO.StreamReader(Mapfile & ".txt")
'Dim intValue As String = ""
Dim strLine As String = ""
Dim X As Integer = 0
Dim Y As Integer = 0
Do Until sr.EndOfStream
strLine = sr.ReadLine
strLine = strLine.Replace(strLine.LastIndexOf(","), "")
For Each item As String In Split(strLine, ",", -1)
'MsgBox("X:" & X & " Y:" & Y & "= " & item)
If item = "" Then
item = 0
End If
If X <= MapWidth Then
Map(X, Y, 0) = Int(item)
End If
X = X + 1
Next
X = 0
Y = Y + 1
Loop
sr.Close()
sr.Dispose()
Catch ex As Exception
MsgBox("Map: " & Mapfile & " could not be loaded." & vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.Critical, "ERROR")
IsOn = False
End Try
Trying to port this code over from Visual Basic To Java. I've Tried using Buffered Reader but nothing seems To Make it happen. The Code Above is for Visual Basic, The Code below is my java port that doesnt seem to be working the same. http://pastebin.com/freXYTi3
public void readFile(Context c) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(c.getAssets().open("map1.txt")));
String line = null;
String newLine = "";
int x = 0;
int y = 0;
while ((line = br.readLine()) != null) {
int length = line.length();
String lastChar = line.substring(length-1);
if (lastChar.contains(",")) {
newLine = line.substring(0,length-1) + "";
}
//line = line.substring(0, line.lastIndexOf(",")) + "";
for (String str : line.split(",", -1)) {
System.out.println(str);
if(str == ""){
str = "0";
}
if(x <= mapwidth){
System.out.println(x + " " + y);
int N = Integer.parseInt(str);
Map[x][y] = N;
}
x = x + 1;
}
x = 0;
y = y + 1;
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}

Without knowing the exact line you are failing on (the error codes give line numbers, but I don't know the correlation to your file), the only thing I notice is that this line:
if(x <= mapwidth){
MIGHT be a one-off bug. I think VB is 1-based and Java is zero based, but it's just a guess that you might want < rather than <= Can you let us know what line the NPE was on.
Also this is wrong:
if(str == ""){
needs to be "str.equals("")" or "str.length()==0"
but I don't see anything that could cause an NPE within the loop
Also you assign newline in the loop and you never use it within that scope, so if it exits and you have another "newline" and you expect it to be set--don't hold your breath.

If you post the error you are getting then you might get a better answer but without knowing the content you are trying to parse it looks like you are making assumptions around the data you are parsing.

Related

My array Printing NULL

In the method, i have all these initialize
Scanner input = new Scanner(System.in);
File file = new File("order.dat");
File viewOrder = new File("ViewOrder.dat");
String orderNo, itemNo, itemNameHolder, qtyHolder, priceHolder, status;
int hold, count = 0, countArray = 0;
double tempPriceHolder, totalPrice = 0;
String tempStatus = "";
String[] holdItemNo = null;
String[] holdName = null;
Integer[] holdQty = null;
Double[] holdTotal = null;
String[] holdStatus = null;
After, i try to read all my content in the file and store the content into holdX array
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while ((line = br.readLine()) != null) {
String tokens[] = line.split(";");
orderNo = tokens[0];
itemNo = tokens[1];
itemNameHolder = tokens[2];
qtyHolder = tokens[3];
priceHolder = tokens[4];
status = tokens[5];
if (orderNo.equalsIgnoreCase(userOrderNo)) {
tempPriceHolder = Double.parseDouble(priceHolder);
hold = Integer.parseInt(qtyHolder);
tempPriceHolder = tempPriceHolder * hold;
totalPrice += tempPriceHolder;
countArray++;
holdItemNo = new String[countArray];
holdName = new String[countArray];
holdQty = new Integer[countArray];
holdTotal = new Double[countArray];
holdStatus = new String[countArray];
if (status.matches("s")) {
tempStatus = "Success";
} else if (status.matches("p")) {
tempStatus = "Partially Full";
} else if (status.matches("o")) {
tempStatus = "Out of Stock";
}
holdItemNo[count] = itemNo;
holdName[count] = itemNameHolder;
holdQty[count] = hold;
holdTotal[count] = tempPriceHolder;
holdStatus[count] = tempStatus;
count++;
}
}
} catch (Exception e) {
System.out.println("Error");
}
Final, i write all my array into a new file.
System.out.printf("%s %15s %15s %10s %10s\n", "Item No", "Description", "Quantity", "Total", "Status");
for (int i = 0; i < holdItemNo.length; i++) {
System.out.printf("\n%-11s %-18s %-13s $%-8s %s \n", holdItemNo[i], holdName[i], holdQty[i], holdTotal[i], holdStatus[i]);
}
System.out.println("-----------------------------------------------------------------------");
System.out.printf("%46s %s\n", "$", totalPrice);
System.out.print("Print Order to file Y/N: ");
String choice = input.next();
if (choice.equalsIgnoreCase("y")) {
try {
PrintWriter bw = new PrintWriter(new FileWriter("ViewOrder.dat", true));
for (int i = 0; i < holdItemNo.length; i++) {
bw.write(userOrderNo + ";" + holdItemNo[i] + ";" + holdName[i] + ";" + holdQty[i] + ";" + holdTotal[i] + ";" + holdStatus[i] + "\n");
bw.flush();
}
bw.flush();
bw.close();
System.out.println("Sucessfull!");
} catch (Exception e) {
System.out.println("Error");
}
} else if (choice.equalsIgnoreCase("n")) {
System.out.println("");
}
but the problem is even my code is working but the output is not what i expected. It printed out the printed out the last content and also the sub price is working as well but the rest is only printed out NULL.
Example
Also, it gave me warning of Derefencing possible null pointer on the array.length
for (int i = 0; i < holdItemNo.length; i++) {
bw.write(userOrderNo + ";" + holdItemNo[i] + ";" + holdName[i] + ";" + holdQty[i] + ";" + holdTotal[i] + ";" + holdStatus[i] + "\n");
bw.flush();
}
Guessing:
holdItemNo = new String[countArray];
and the following lines: you are creating these new array objects within your reading loop (inside a condition).
So probably that condition never goes true; therefore your arrays stay all null. But even when the condition is met - you probably expect that to happen more then once. And guess what: you are creating completely new arrays then. While throwing away the previously created array. Each time the if condition turns true you will lose previously stored values!
So the answer is: create your arrays before entering the loop. This means that you either have to query "how many slots to create" upfront; or you have to create an array with say 100 empty slots; and within your loop you then have to check if you still have free slots.
Or you start using java.util.List resp. ArrayList - which allows for dynamic adding of elements.

issue with loop not reaching the end of a file - Java

I'm working on a Java assignment for school. The assignment is to deal with 2 files reading the first, using the second to make adjustments on the first, and finally, outputing into a new file.
Scanner inputRecords = new Scanner(new File("Records.txt"));
Scanner inputTransactions = new Scanner(new File("Transactions.txt"));
BufferedWriter outputFile = (new BufferedWriter(new FileWriter("NewRecords.txt", true)));
char code; // transaction code
String lineTran = "";
String lineRecord = "";
String midS = "";
String tidS = "";
int tid = 0, mid= 0;
for (int x = 0; x < 6; x++)
{
lineTran = inputTransactions.nextLine();
code = lineTran.charAt(0);
System.out.println(code);
tidS = lineTran.substring(2,11);
tid = Integer.parseInt(tidS);
lineRecord = inputRecords.nextLine();
midS = lineRecord.substring(0,9);
mid = Integer.parseInt(midS);
if (mid < tid) // add a new record lineTran.substring(2,lineTran.length()
{
outputFile.write(lineRecord);
outputFile.newLine();
lineRecord = inputRecords.nextLine();
}
else if (mid == tid )
{
if (code == 'C') //change record
{
outputFile.write(lineTran.substring(2,lineTran.length()));
outputFile.newLine();
lineTran = inputTransactions.nextLine();
}
else if (code == 'D') //delete record
{
lineTran = inputTransactions.nextLine();
lineRecord = inputRecords.nextLine();
}
else // add error
{
System.out.println(lineRecord + " Already Exists...add error");
lineTran = inputTransactions.nextLine();
}
}
else
{
if (code == 'A') // add record
{
outputFile.write(lineTran.substring(2,lineTran.length()));
outputFile.newLine();
lineTran = inputTransactions.nextLine();
}
else if (code == 'C') // change error
{
System.out.println(lineRecord + " Record already exist...Change Error");
lineTran = inputTransactions.nextLine();
}
else // delete error
{
System.out.println(lineRecord + " Record does not exist...delete error");
lineTran = inputTransactions.nextLine();
}
}
Note that:
Records.txt has 10 lines of information (example: ######### lastname firstname occupation)
Transactions.txt has 6 lines of information (example: 'A,D,or C' ######### lastname firstname occupation)
The issue I'm having is no matter the type of loop i run i reach one of 2 deadends.
1) in the case of the for loop above
D
A
C
A
C
386326383 Slim Kan personalTrainer No changes were found...Change Error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at fileHandling.main(fileHandling.java:26)
is the outcome and nothing writen to file.
2) If I run for loop through x<5 program runs fine and, however, skips the last transaction.
I tried "do while" and "while" loops but only got similar results. any suggestions?
On the if condition you have assign lineTran = inputTransactions.nextLine(); then on the top of for loop you assign it again. Means that you are dismiss 1 line every loop. So that, in transaction file you have 6 lines, then you loop will run more loop than the number of line in the file because of you have read .nextLine() more than the number of lines.

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

Is it possible to write a few StringArray values into one String?

I'm trying to write a part of an String array into a String but I just stuck at a problem.
The disposal of the value of line is always like this: "status.test.status.close.name = Closed".
The only static of this value is "status." and ".name". I just want to get the part between "status." and ".name". With the code below I get this result: "status.test.status.close". My question now is, is it possible to delete parts of an array, for example: technicalNames.delete["status."];? Or does anyone has another hint how to realize it?
public void setTechnicalName(File javaFile) throws IOException {
if(javaFile.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(javaFile));
String line = null;
while((line = reader.readLine()) != null)
if (line.contains("In approval") || line.contains("In Approval") || line.contains("In review") || line.contains("In Review") || line.contains("Closed")){
System.out.println(line);
String[] technicalNames = line.split(".name");
String technicalName = technicalNames[0];
System.out.println(technicalName);
}
reader.close();
}
}
That is the .xml file i read out:
status.test.status.close.name = Closed
status.test.status.in.approval.name = In approval
status.test.status.in.review.name = In review
test.field.approver1 = Approver
test.field.lookupworkflow =
test.field.temp = temp
Thanks in advance!
I am assuming that you are interested in parts between status and .name. You can try this way of doing it.
public static void setTechnicalName(File javaFile) throws IOException {
if(javaFile.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(javaFile));
String line = null;
int statusOffet = "status.".length();
while((line = reader.readLine()) != null){
int indexOfStatus = line.indexOf("status");
int indexOfName = line.lastIndexOf(".name");
boolean isReqLine = line.contains("In approval")
|| line.contains("In Approval")
|| line.contains("In review")
|| line.contains("In Review")
|| line.contains("Closed");
if(isReqLine && indexOfStatus != -1 && indexOfName != -1){
System.out.println(line);
String stage = line.substring(indexOfStatus + statusOffet, indexOfName);
System.out.println(stage);
}
}
reader.close();
}
}
EDIT : as per comment to match format, I have included "." when calculating offset and used indexOf
When you want to split your given line into parts, you can do it similar to
final String string = "status.test.status.close.name = Closed";
final String[] split = string.substring(0, string.indexOf("=")).split("\\.");
System.out.println("split = [" + split[0] + ", " + split[1] + ", " + split[2] + ", " + split[3] + ", " + split[4] + "]"); // split = [status, test, status, close, name ]
and pick the appropriate values out of split afterwards.
Well, you have status defined twice. So assuming you are referring to the first status, and the desired result is to print out test.status.close you could do this if you knew that indexes 0 and n-1 would be not of interest:
StringBuilder builder = new StringBuilder();
String[] parts = line.split(".name")[0].split("\\.");
for(int i = 1; i < parts.length - 1; i++){
builder.append(parts[i]);
if(i < parts.length - 1){
builder.append(".");
}
System.out.println(builder.toString())

Reading method in java with starting and ending position gone wrong

So basically, I have an exam question that said "Add your directory to this method" and the follow up questions require that I use this method. My classmates that own macs, alongside with the examiner for some reason managed to get the file working.
public static String GetTextFromFile(int startPosition, int endPosition) {
String gotText = "";
String outText = "";
try {
Scanner fileInp = new Scanner(new File(
"C:/Users/Ted/Desktop/diary.txt"));
while (fileInp.hasNextLine()) {
gotText = gotText + fileInp.nextLine();
gotText = gotText + "\n";
}
// System.out.println(gotText);
for (int i = startPosition; i <= endPosition; i = i + 1) {
outText = outText + gotText.charAt(i - 1);
}
fileInp.close();
return outText;
} catch (IOException e) {
return outText;
}
}
I'm using a windows, why does this not work for me?
This is what an error says with an input of
Starting point 1 and ending point 9
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at java.lang.String.charAt(String.java:658)
at secretmessages.SecretMessages.GetTextFromFile(SecretMessages.java:78)
at secretmessages.SecretMessages.EveryNthCharacterSteganography(SecretMessages.java:199)
at secretmessages.SecretMessages.main(SecretMessages.java:322)
if you did not get any text from your fiel then gotText will still be "", so change this line
for(int i = startPosition; i <= endPosition; i = i + 1)
to
for(int i = startPosition; i <= endPosition && gotText.length () > 0; i = i + 1)
Also I would rather use String.substring
Also log your exceptions
catch(IOException e)
{
e.printStackTrace ();
return outText;
}
Issue in your code is you not check for empty string and use SrtingBuilder rather than String.check endPosition value.
endPosition value could not be greater than total length of string.
See following code may Resolve your Problem.
StringBuilder sb=new StringBuilder("");
while (fileInp.hasNextLine()) {
sb.append(fileInp.nextLine()).append("\n");
}
String gotText=sb.toString();
// System.out.println(gotText);
for (int i = startPosition; i <= endPosition; i = i + 1) {
outText = outText + gotText.charAt(i - 1);
}
if(!gotText.equals("")){
if(endPosition > gotText.length())
endPosition=gotText.length()-1;
for (int i = startPosition; i <= endPosition; i = i + 1) {
outText = outText + gotText.charAt(i - 1);
}
}
outText = outText + gotText.charAt(i - 1);
I think here if in the beginning i==0 then i-1 will throw the out of bound exception. And do check the endPosition it should not go beyond gotText.length().

Categories