This is my code:
String bericht = "";
while (cur.moveToNext()) {
if (cur.getString(cur.getColumnIndex("address")).equals("SAH")) {
bericht += cur.getString(cur.getColumnIndex("body"));
adress = getadress(bericht); //basically cutting a part out
datum = getdatum(bericht); //same
afspraken[x][0] = datum;
afspraken[x][1] = adress;
x++;
}
cur.moveToNext();
bericht = "";
}
It works without the bericht = ""; at the end but I want to reset the string with every loop!
I tried:
String bericht;
bericht = cur.getString(cur.getColumnIndex("body"));
Error message:
E/AndroidRuntime(3171): java.lang.StringIndexOutOfBoundsException: length=0; index=2
It seems you reset the string in every iteration anyway. You can just declare bericht inside iteration as you don't need it outside.
while (cur.moveToNext()) {
if (cur.getString(cur.getColumnIndex("address")).equals("SAH")) {
String bericht = cur.getString(cur.getColumnIndex("body"));
adress = getadress(bericht); //basically cutting a part out
datum = getdatum(bericht); //same
afspraken[x][0] = datum;
afspraken[x][1] = adress;
x++;
}
cur.moveToNext();
}
Also, it seems that the heart of the problem lies in getadress(bericht); or getdatum(bericht);. Check how you process your string there.
A bit of a guess here since the exception doesn't occur in the code parts posted, but this might help:
String bericht = "";
while (cur.moveToNext()) {
if (cur.getString(cur.getColumnIndex("address")).equals("SAH")) {
bericht = cur.getString(cur.getColumnIndex("body"));
if (bericht != null && !bericht.trim().isEmpty()) {
adress = getadress(bericht); //basically cutting a part out
datum = getdatum(bericht); //same
afspraken[x][0] = datum;
afspraken[x][1] = adress;
x++;
}
}
cur.moveToNext();
}
What's changed is that we check if the String we put in bericht is something we can reasonably expect to work when calling getadress(...) and getdatum(...) with it. You may want to check even more (minimum length of X for example), but since I can't see what the methods do I can't really tell you what that would be.
Related
currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already
the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.
==========================================================================
what I need to read is this:
\\name - id - dateOfBirth - gender - degree - speciality - city - availability
Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true
=======================================================================
this is the code:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The problem is membersList doesn't exist when you call .size() on it
instead of
ArrayList<UniversityMember> membersList;
you need to initialize it
ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
You need to initialize the ArrayList.
Like that ArrayList membersList = new ArrayList();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.
You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on
String str;
for(int i = 0; i < str.length(); i++){
System.out.println("hey");
}
also you need to declare the array list like this
ArrayList<Method name> membersList = new ArrayList<Method name>();
also don't forget to import the ArrayList class
import java.util.ArrayList;
nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull
==================================================
The code after fixing it:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) {
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
Hi.
I'm making an app that receives data from bluetooth by using stringbuilder
And makes it slice for using another activity.
The image shows what i want to make.
Q1. What should i use c->d, d->e ?
Q2. There will be a lot of data, I want to know the way to simplify this sequence
******************** edited ********************
I have practiced by adding value to Arraylist.
But in String Array, there is no .get(), so i couldn't access to element's length.
public static ArrayList<String> randomValue = new ArrayList<>();
public static int iDistance=0, xIAngle=0, yIAngle=0, zIAngle=0;
public static String distance, xAngle, yAngle, zAngle;
randomValue.add("12345090080070");
randomValue.add("15640080085071");
randomValue.add("16542070084074");
randomValue.add("12645080087078");
randomValue.add("21345084081060");
randomValue.add("14785078075065");
randomValue.add("13155079077077");
randomValue.add("14623080078078");
randomValue.add("14918086080078");
randomValue.add("15684085082080");
for (int i=0; i<randomValue.size(); i++){
String a = randomValue.get(i);
String distance = a.substring(0,5);
String xAngle = a.substring(5,8);
String yAngle = a.substring(8,11);
String zAngle = a.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}
It seems like you are just stuck on finding the equivalent of get for a string array. To access an element in an array, the syntax is array[I], so if you were using a string array, this line:
String a = randomValue.get(i);
would have been:
String a = randomValue[i];
The code for your sequence of transformations can be shortened with Streams:
// this is the sequence of transformation starting with the sting builder "a"
List<String> randomValueWithLength14 =
Arrays.stream(a.toString().split(";")).filter(x -> x.length() == 14)
.collect(Collectors.toList());
// this is the for loop shown in your code
for (int i=0; i<randomValueWithLength14.size(); i++){
String s = randomValueWithLength14.get(i);
String distance = a.substring(0,5);
String xAngle = s.substring(5,8);
String yAngle = s.substring(8,11);
String zAngle = s.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}
I just have a simple enough question on an issue I'm having. I am trying to set a string value to "0" if a webelement isn't present else the string is the the webelement value (using getText). However I can't seem to use these values ouside the if and else statement. How do I do this?
Here is my code
String players_in_game = null;
public void join_game_user_increases_register() throws Exception {
WebDriverWait wait = new WebDriverWait(Drivers.getDriver(), 10);
wait.until(ExpectedConditions.visibilityOf(countdownLabel));
if (!num_of_players_in_game.isDisplayed()) {
String players_in_game = "0";
} else {
String players_in_game = num_of_players_in_game.getText();
}
System.out.println(players_in_game);
int first_num = Integer.parseInt(players_in_game);
Use code below:
WebDriverWait wait = new WebDriverWait(Drivers.getDriver(), 10);
wait.until(ExpectedConditions.visibilityOf(countdownLabel));
String players_in_game = "0";
if(num_of_players_in_game.isDisplayed()){
players_in_game = num_of_players_in_game.getText();
}
System.out.println(players_in_game);
int first_num = Integer.parseInt(players_in_game);
Or:
String players_in_game = num_of_players_in_game.isDisplayed() ? num_of_players_in_game.getText() : "0";
Or:
List<WebElements> num_of_players_in_game = driver.findElements(By....);
String players_in_game = num_of_players_in_game.size()==0 ? "0": num_of_players_in_game.get(0).getText();
Since your already declare that variable as a class member in the first line of your code, simple remove the String to not re-declare that name as a local variable but use the field instead:
if(!num_of_players_in_game.isDisplayed()){
players_in_game = "0";
} else {
players_in_game = num_of_players_in_game.getText();
}
Java allows variable shadowing at class level. So, you can actually declare a variable which has the same name as a class variable inside any method. In your case, the variable name is players_in_game.
You can define that variable once again in a method but scope of that new variable will be different. So, if you want to set that class level String inside a method, do not define a new variable and use the class level variable.
So just use the below code:
if (!num_of_players_in_game.isDisplayed()) {
players_in_game = "0";
} else {
players_in_game = num_of_players_in_game.getText();
}
Already others have answered with code. I just wanted to explain the reason.
You can try this :
String players_in_game = null;
public void join_game_user_increases_register() throws Exception {
WebDriverWait wait = new WebDriverWait(Drivers.getDriver(), 10);
wait.until(ExpectedConditions.visibilityOf(countdownLabel));
try {
if (num_of_players_in_game.isDisplayed()) {
String players_in_game = num_of_players_in_game.getText();
}
} catch (Exception e) {
String players_in_game = "0";
}
System.out.println(players_in_game);
int first_num = Integer.parseInt(players_in_game);
I am trying to only run nextLine() at the end of every run of the loop so that it starts the loop with the new line each iteration through, but at the end of the last run, i dont want it to run the nextLine() because it skips the data i need for the rest of my program. how do i fix this?
String hasInt = fileIn.nextLine();
while(Character.isDigit(hasInt.charAt(0)))
{
data = hasInt.split(",");
info = Integer.parseInt(data[0]);
def = data[1];
case = data[2];
free = data[3];
Case newCase = new Case(info, def, case, free);
miner.addCase(newCase);
hasInt = fileIn.nextLine();
}
Well combining it all into that for loop seemed to work, that got me all the way through the loop, and seemed to work, but now at the start of the method it got stuck in an infinite loop
while(fileIn.hasNextLine())
{
if(fileIn.hasNext("[A-Za-z]+"))
{
do {
String hasInt = fileIn.nextLine();
if (!Character.isDigit(hasInt.charAt(0)) {
break;
}
// rest of your code here
} while(true);
You could try merging the statements into a for loop:
for(
String hasInt = fileIn.nextLine();
Character.isDigit(hasInt.charAt(0));
hasInt = fileIn.nextLine()
) {
data = hasInt.split(",");
info = Integer.parseInt(data[0]);
def = data[1];
case = data[2];
free = data[3];
Case newCase = new Case(info, def, case, free);
miner.addCase(newCase);
}
I am not sure how clean it would be but; it seems that you could use hasInt after the while loop to get the value that you do not want to skip.
Hi you will not loss the data since the data you read last is in the hasInt variable. So use it after the while loop.
String hasInt = fileIn.nextLine();
while(Character.isDigit(hasInt.charAt(0)))
{
data = hasInt.split(",");
info = Integer.parseInt(data[0]);
def = data[1];
case = data[2];
free = data[3];
Case newCase = new Case(info, def, case, free);
miner.addCase(newCase);
hasInt = fileIn.nextLine();
}
//use the hasInt variable here to get the last read data...
I've researched can't find any relevant info. I have a result set that give me back distinct tagId's their can be multiple tagIds for same accountId's.
while(result_set.next()){
String tagId = result_set.getString("tagId");
String accountId = result_set.getString("accoundId");
// plenty of other fields being store locally
}
I need to store first accoundId(which is being done) & every subsequent iteration compare it with the previous Id to check for equality or not(if so same account).
I tried this and it failed horribly, after first iteration they'll continually be equal & I must be DUMB bc i though as long as I compare them before assignment global guy(previousId) should be holding the prior value.
String previousId = null;
while(result_set.next()){
String tagId = result_set.getString("tagId");
String accountId = result_set.getString("accoundId");
previousId = accountId;
}
Anyway I wanted my workflow to go something as follows:
while(result_set.next()){
if (previousId = null) {
// this would be the first iteration
}
else if (previousId.equals(accountId) {
// go here
} else {
// go here
}
}
If I've understood you well, this should work..
String previousId = null;
while(result_set.next()){
String tagId = result_set.getString("tagId");
String accountId = result_set.getString("accoundId");
if (previousId == null) {
// this would be the first iteration
} else if (previousId.equals(accountId) {
// go here
} else {
// go here
}
previousId = accountId;
}