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().
Related
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.
I have a sentence that contains message to be posted to the server like wow! superb pic #superb #pic #111 #222 enjoyed the pic
I want to extract the hastags and make them colored and leaving the rest of the text intact.
I tried the following code but not working.
private void spannableOperationOnHastag() {
mPostMessage = edPostMessage.getText().toString().trim();
String strPreHash = null;
String strHashText = "";
if (mPostMessage.contains("#")) {
try {
int index = mPostMessage.indexOf("#");
strPreHash = mPostMessage.substring(0, index);
SpannableString spannableString = new SpannableString(strPreHash);
String strHashDummy=mPostMessage.substring(index, mPostMessage.length());
int hashCount= StringUtils.countMatches(strHashDummy, "#"); // check for number of "#" occurrence and run forloop for getting the number of hastags in the string
int hasIndex=0;
for (int i = 0; i <hashCount ; i++) {
strHashText = strHashText+strHashDummy.substring(hasIndex, strHashDummy.indexOf(' '))+" ";
hasIndex =strHashText.indexOf(" "); // updating new space(" ") position in the index variable
}
SpannableString spannableStringBlue = new SpannableString(strHashText);
spannableStringBlue.setSpan(new ForegroundColorSpan(PublishPostActivity.this.getResources().getColor(R.color.blue)), 0, strHashText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
edPostMessage.setText(null); // clearing old string
edPostMessage.append(spannableString); // setting extracted coloured text
edPostMessage.append(spannableStringBlue);
} catch (Exception e) {
Log.d(TAG, "validatePostMessage() called with " + "e = [" + e + "]");
}
}
}
I solved the problem my self . I any one needs it can refer this code :)
private void spannableOperationOnHastag() throws Exception{
mPostMessage = edPostMessage.getText().toString()+" "; // extra space for spannable operations
List<Integer> listStartPos = new ArrayList<>();
List<Integer> listEndtPos = new ArrayList<>();
if (mPostMessage.contains("#")){
for (int i = 0; i < mPostMessage.length(); i++) {
if (mPostMessage.charAt(i) == '#') {
listStartPos.add(i);
Log.d(TAG, "startIndex of # = " + i);
}
}
for (int i = 0; i < listStartPos.size(); i++) {
int endIndex = mPostMessage.indexOf(' ', listStartPos.get(i));
listEndtPos.add(endIndex);
Log.d(TAG, "endIndex of # " + (endIndex));
}
SpannableString spanned = SpannableString.valueOf(mPostMessage);
for (int i = 0; i < listStartPos.size(); i++) {
spanned = new SpannableString(spanned);
spanned.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue)), listStartPos.get(i), listEndtPos.get(i), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Log.d(TAG, "substring " + mPostMessage.substring(listStartPos.get(i), listEndtPos.get(i) + 1));
}
mPostMessage.trim(); // removing extra space.
edPostMessage.setText(null);
edPostMessage.setText(spanned);
}
}
I see you've just posted your own answer, but as I'd nearly finished typing this up I thought I'd go ahead and post this anyway :). I typed it just now without an IDE so it may not be perfect.
private static SpannableString convertTextColorsAtChar(char trigger, String inputText) {
SpannableString spannedText = new SpannableString(inputText);
if (!inputText.contains(trigger)) {
return spannedText;
}
ArrayList<int[]> indexArr = getIndexes(trigger, inputText.toCharArray());
for (int[] indexes : indexArr) {
spannedText.setSpan(new ForegroundColorSpan(Color.RED), indexes[0], indexes[1], Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
returned spannedText;
}
private static ArrayList<int[]> getIndexes(char trigger, char[] inputText) {
ArrayList<int[]> values = new ArrayList<int[]>();
int firstIndex = -1;
int secondIndex; = -1
for (int i = 0; i < inputText.length; i++) {
if (firstIndex != -1 && inputText[i] == ' ') {
secondIndex = i;
values.add(new int[] { firstIndex, secondIndex });
firstIndex = secondIndex = -1;
}
if (trigger == inputText[i]) {
firstIndex = i;
}
}
return values;
}
You'd then call it with convertTextColorsAtChar('#', editText.getText().toString());
change your code as below
SpannableString spannableStringBlue = new SpannableString(strHashText);
spannableStringBlue.setSpan(new ForegroundColorSpan(new ForegroundColorSpan(Color.BLUE), 0, strHashText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
edPostMessage.setText(null); // clearing old string
edPostMessage.append(spannableString); // setting extracted coloured text
edPostMessage.append(spannableStringBlue);
SpannableStringBuilder builder = new SpannableStringBuilder();
String yourSentence = "Pic #superb #pic #111 #222 enjoyed the pic";
String [] newSent = yourSentence.split(" ");
for(int count = 0; count < newSent.length; count++){
if(newSent[count].contains("#")){
SpannableString redSpannable= new SpannableString(newSent[count]);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, newSent[count].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Log.v("Test", "color_string" + newSent[count]);
builder.append(redSpannable+" ");
} else{
builder.append(newSent[count]+" ");
Log.v("Test", "normal_string" + newSent[count]);
}
}
holder.PhName.setText(builder, TextView.BufferType.SPANNABLE);
I'm copying my program to convert binary data to hex format and print the data in 16bytes format line by line and I'm getting StringIndexOutOfBounds Exception even after data has been printed for some extent please help me solve this problem.
byte[] buffer = new byte[16];
while((line = bis.read(buffer)) != -1)
{
for(int i = 0; i < line; i++)
{
value = Integer.toHexString(0xFF & buffer[i] | 0x100).substring(1);
sb.append(value);//I think here is the problem
}
if(a == 0)
{
incValue = sb.substring(0, 32);
System.out.println(incValue);
}
else
{
counter = counter + 32;
incValue = sb.substring(counter, counter + 32);
System.out.println(incValue);
}
a++;
Output:
5e9d094ec7a7349725b8300212a5048f
b9ce351dfb869a7db694755981f7fbd3
acad5008e54ebd80b82a9676ebd02a0f
4775a61e52c3129c4aba3af1f28c8ee0
9050718e15a8189321d626399ab2612f
212f89f4f9ff0015d03b625cfb990c8a
1c36dc8c13e636f4e74b6df4af853207
49ea39e78c727df55b6f0d5bc90a54fd
f7aba3f8f258496d0256400474236335
Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 216896
instead of this:
incValue = sb.substring(counter, counter + 32);
you can use this:
if((counter+32)< sb.length())
{
incValue = sb.substring(counter, counter + 32);
}
else
{
incValue = sb.substring(counter) //The String is shorter than counter+32 chars
}
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.
I have a similar problem.This is a snippet of my source:
FileWriter fstream = new FileWriter("results_for_excel.txt");
BufferedWriter writer = new BufferedWriter(fstream);
String sourceDirectory = "CVs";
File f = new File(sourceDirectory);
String[] filenames = f.list();
Arrays.sort(filenames);
String[] res = new String[filenames.length];
for (int i = 0; i < filenames.length; i++) {
System.out.println((i + 1) + " " + filenames[i]);
}
for (int i = 0; i < filenames.length; i++) {
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
res[i] = filenames[i].substring(beg,end);
System.out.println((i+1)+res[i]);
writer.write(res[i] + "\n");
}
writer.flush();
writer.close();
I get an exception at res[i] = filenames[i].substring(beg,end);
I cant figure what's going on.Thanks in advance:)
P.S I have read all the duplicates but nothing happened:(
Add the following code after
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
This will display the filename that is in the wrong format;
if (beg == -1 || end == -1)
{
System.out.println("Bad filename: " + filenames[i]);
}
The error occurs, because a filename does not contain both '-' and '.'. In that case indexOf returns -1 which is not a valid parameter for substring.
Either beg or end is -1. This means the filename doesn't contain - or .. Simple as that:)
Either
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
is returning a -1, its possible there's a file which doesn't contain either.
One of characters in this code
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
is not found, so either beg or end equals -1. That's why you got the exception while calling substring with negative arguments.
The problem was at a KDE file called ".directory".Thank you very very much all of you:)