I'm confused with my first Java assignment! I followed my teacher's pseudocode and tried to make it look like the example we did in class, but I'm getting an error saying "String index out of range: -1" I looked around but really didn't find the error happening in this way, or maybe I just couldn't figure out how to use that information to solve my problem.
Can someone help me out?
// MarkdownTranslator -- Converts input text written in Markdown format
// into equivalent HTML.
import java.util.*; // needed for the Scanner class
public class MarkdownTranslator
{
public static void main (String [] args)
{
String input = getUserInput();
String output = "";
Scanner text = new Scanner(input);
while(text.hasNextLine()){
String line = text.nextLine();
if (line.length() == 0){
line = "<p></p>";
}
else{
String working = "";
int index = line.indexOf("*");
if(index > -1) {
working = line.substring(0, index);
line = line.substring(index+1, line.length());
index = line.indexOf("*");
String subject = line.substring(0, index);
working = working + translateEmphasis(subject);
working = working + line.substring(index+1, line.length());
line = working;
working = "";
}
index = line.indexOf("**");
if(index > -1) {
working = line.substring(0, index);
line = line.substring(index+2, line.length());
index = line.indexOf("**");
String subject = line.substring(0, index);
working = working + translateStrongEmphasis(subject);
working = working + line.substring(index+2, line.length());
line = working;
working = "";
}
index = line.indexOf("`");
if(index > -1) {
working = line.substring(0, index);
line = line.substring(index+1, line.length());
index = line.indexOf("`");
String subject = line.substring(0, index);
working = working + translateCode(subject);
working = working + line.substring(index+1, line.length());
line = working;
working = "";
}
index = line.indexOf("![");
if(index > -1) {
working = line.substring(0, index);
line = line.substring(index+2, line.length());
index = line.indexOf("](");
String altText = line.substring(0, index);
line = line.substring(index+2, line.length());
index = line.indexOf(" \"");
String imgPath = line.substring(0, index);
line = line.substring(index+2, line.length());
index = line.indexOf("\")");
String titleText = line.substring(0, index);
line = line.substring(index+2, line.length());
working = working + translateImage(altText, imgPath, titleText);
working = working + line.substring(index+2, line.length());
line = working;
working = "";
}
index = line.indexOf("[");
if(index > -1) {
working = line.substring(0, index);
line = line.substring(index+1, line.length());
index = line.indexOf("](");
String linkText = line.substring(0, index);
line = line.substring(index+2, line.length());
index = line.indexOf(")");
String urlText = line.substring(0, index);
line = line.substring(index+1, line.length());
working = working + translateHyperlink(linkText, urlText);
working = working + line.substring(index+1, line.length());
line = working;
working = "";
}
}
output = output + line + "\n";
}
System.out.println(output);
}
public static String translateEmphasis (String text)
{
return "<em>" + text + "</em>";
}
public static String translateStrongEmphasis (String text)
{
return "<strong>" + text + "</strong>";
}
public static String translateHyperlink (String text, String url)
{
return "" + text + "";
}
public static String translateImage (String alt, String path, String title)
{
return "<img src =" + path + " alt =" + alt + " title =" + title + ">";
}
public static String translateCode (String text)
{
return "<code>" + text + "</code>";
}
// DO NOT MODIFY THE FOLLOWING HELPER METHOD
private static String getUserInput()
{
Scanner in = new Scanner(System.in);
boolean done = false;
System.out.print("Please enter one or more lines of text. When you are ");
System.out.print("finished, enter a single\nperiod on a line by itself ");
System.out.println("to exit (the period will not be included in your\ninput):");
String result = "";
while (!done)
{
String line = in.nextLine();
// Check to see if we received a single period as input
if (line.trim().equals("."))
{
done = true; // terminate the loop
}
else
{
// Add the current line to the buffer and keep going
result = result + line;
result = result + "\n"; // restore the newline that nextLine() ate
}
}
return result;
}
}
Related
I create an app that fetch all pdf documents from Phone storage... But in Android 10 devices , all pdfs not retrieved ... and even when I shall be tried to rename the pdf file , the pdf file is gone...
this is my code :
#NonNull
public ArrayList getAllPdfs(#NonNull Context context1) {
String str = null;
Uri collection;
ArrayList<PdfModel> arrayList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
collection = MediaStore.Files.getContentUri("external");
}
// collection = MediaStore.Files.getContentUri("external");
try {
final String[] projection = new String[]{
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
};
Context context = getActivity();
SharedPreferences save_preferences = homeContext.getSharedPreferences(MY_SORT_PREF,
MODE_PRIVATE);
SharedPreferences preferencesOrder = homeContext.getSharedPreferences("Order", MODE_PRIVATE);
String order_by_descending = preferencesOrder.getString("order", "descending");
String order = null;
switch (order_by_descending) {
case "descending":
String sort = save_preferences.getString("sorting", "SortByDate");
switch (sort) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " DESC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " DESC";
break;
}
break;
case "ascending":
String sort_date = save_preferences.getString("sorting", "SortByDate");
switch (sort_date) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " ASC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " ASC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " ASC";
break;
}
break;
}
final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
final String[] selectionArgs = new String[]{mimeType};
CursorLoader cursorLoader = new CursorLoader(context1, collection, projection, selection,
selectionArgs, order);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null && cursor.moveToFirst()) {
do {
int columnName = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
String path = cursor.getString(columnData);
if (new File(path).exists()) {
#SuppressLint("Range")
File file = new
File(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)));
if (file.exists()) {
Log.d(TAG, "getAllPdfs: a " + file.length());
PdfModel pdfModel = new PdfModel();
//------------------------------Remove (.pdf) extension------------------------
String fileName = file.getName();
if (fileName.indexOf(".") > 0)
fileName = fileName.substring(0, fileName.lastIndexOf("."));
Uri imageUri = Uri.fromFile(file.getAbsoluteFile());
Log.d(TAG, "getAllPdfs: bb " + file.getName());
pdfModel.setId(file.getName());
pdfModel.setName(removeExtension(file.getName()));
pdfModel.setAbsolutePath(file.getAbsolutePath());
pdfModel.setParentFilePath(Objects.requireNonNull(file.getParentFile()).getName());
pdfModel.setPdfUri(file.toString());
pdfModel.setLength(file.length());
pdfModel.setLastModified(file.lastModified());
//pdfModel.setThumbNailUri(file.);
arrayList.add(pdfModel);
} else {
Log.d(TAG, "getAllPdfs: ");
}
}
} while (cursor.moveToNext());
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return arrayList;
}
Please solve this problem ....
My code involves both Processing and Arduino. 5 different photocells are triggering 5 different sounds. My sound files play only when the ldrvalue is above the threshold.
The Null Pointer Exception is highlighted on this line
for (int i = 0; i < ldrValues.length; i++) {
I am not sure which part of my code should be changed so that I can run it.
import processing.serial.*;
import processing.sound.*;
SoundFile[] soundFiles = new SoundFile[5];
Serial myPort; // Create object from Serial class
int[] ldrValues;
int[] thresholds = {440, 490, 330, 260, 450};
int i = 0;
boolean[] states = {false, false, false, false, false};
void setup() {
size(200, 200);
println((Object[])Serial.list());
String portName = Serial.list()[3];
myPort = new Serial(this, portName, 9600);
soundFiles[0] = new SoundFile(this, "1.mp3");
soundFiles[1] = new SoundFile(this, "2.mp3");
soundFiles[2] = new SoundFile(this, "3.mp3");
soundFiles[3] = new SoundFile(this, "4.mp3");
soundFiles[4] = new SoundFile(this, "5.mp3");
}
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}
You're approach is shall we say optimistic ? :)
It's always assuming there was a message from Serial, always formatted the right way so it could be parsed and there were absolutely 0 issues buffering data (incomplete strings, etc.))
The simplest thing you could do is check if the parsing was successful, otherwise the ldrValues array would still be null:
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
// double check parsing int values from the string was successfully as well, not just buffering the string
if(ldrValues != null){
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}else{
// print a helpful debugging message otherwise
println("error parsing ldrValues from string: " + myString);
}
}
(Didn't know you could parse a int[] with int(): nice!)
public void loadFileRecursiv(String pathDir)
{
File fisier = new File(pathDir);
File[] listaFisiere = fisier.listFiles();
for(int i = 0; i < listaFisiere.length; i++)
{
if(listaFisiere[i].isDirectory())
{
loadFileRecursiv(pathDir + File.separatorChar + listaFisiere[i].getName());
}
else
{
String cuExtensie = listaFisiere[i].getName();
String nume = cuExtensie.split(".")[0];
String acronimBanca = nume.split("_")[0];
String tipAct = nume.split("_")[1];
String dataActString = nume.split("_")[2];
//Date dataAct = new SimpleDateFormat("dd-MM-yyyy").parse(dataActString);
//String denBanca = inlocuireAcronim(acronimBanca);
insertData(listaFisiere[i], cuExtensie, acronimBanca, tipAct, dataActString);
//fisiere[i].renameTo(new File("u02/ActeConstitutive/Mutate"));
}
}
}
I have a simple code that checks all files and folders recursevely when a path is given. Unfortunately, i have a NULLPOINTEREXCEPTION for for(int i = 0; i < listaFisiere.length; i++) this line. What can be the problem? Thank you!
check whether listaFisiere is null or not
If not null, change this line as for(int i = 0; i < listaFisiere.length(); i++)
and
you can change your code as below
for(File path:listaFisiere)
{
if(path.isDirectory())
{
loadFileRecursiv(pathDir + File.separatorChar + path.getName());
}
else
{
String cuExtensie = path.getName();
String nume = cuExtensie.split(".")[0];
String acronimBanca = nume.split("_")[0];
String tipAct = nume.split("_")[1];
String dataActString = nume.split("_")[2];
//Date dataAct = new SimpleDateFormat("dd-MM-yyyy").parse(dataActString);
//String denBanca = inlocuireAcronim(acronimBanca);
insertData(path, cuExtensie, acronimBanca, tipAct, dataActString);
//fisiere[i].renameTo(new File("u02/ActeConstitutive/Mutate"));
}
}
I have a Dojo table with list of key value pairs. Both fields are editable, once a value is modified i am doing:
var items = grid.selection.getSelected();
However, the modified value is not picked up only the old value is picked.
I tried the following:
dojo.parser.parse()
dojo.parser.instantiate([dojo.byId("tableDiv")]);
but none of them worked. Can any one sugggest a solution for this.
function getAllItems() {
var returnData = "";
//dojo.parser.parse();
//dojo.parser.instantiate([dojo.byId("tableDiv")]);
//grid._refresh();
var items = grid.selection.getSelected();
function gotItems(items, request) {
var i;
for (i = 0; i < items.length; i++) {
var item = items[i];
var paramName = grid.store.getValues(item, "paramName");
var paramValue = grid.store.getValues(item, "paramValue");
if (returnData == "") {
returnData = paramName + "&" + paramValue;
} else {
returnData = returnData + "#" + paramName + "&"
+ paramValue;
} document.getElementById("returnData").value = returnData;
document.getElementById("successFlag").value = "true";
}
}
//Called when loop fails
function fetchFailed(error, request) {
alert("Error reading table data");
}
//Fetch the data.
jsonStore.fetch({
onComplete : gotItems,
onError : fetchFailed
});
}
I want to use NameValueCollection in windows phone 8, but I can not see this option in WP8 SDK. Can you help me please?
This function has been removed.
But a query can be manipulated using parsing and a SortedDictionary. i.e. This snippet sorts a query string:
public string sortQuery(string myUrl)
{
string url = myUrl.Substring(0, myUrl.IndexOf("?") + 1);
string q = myUrl.Substring(myUrl.IndexOf("?") + 1);
string[] pr = q.Split('&');
SortedDictionary<string,string> d = new SortedDictionary<string,string>();
foreach (string s in pr)
{
string[] prm = s.Split('=');
string key = prm[0];
string value = "";
if (prm.Length > 1) { value = "=" + prm[1]; }
d.Add(key, value);
}
string result = "";
foreach (var k in d.Keys)
{
result += k + d[k] + "&";
}
result = result.Substring(0, result.Length - 1);
return url + result;
}