Inserting a variable amidst another variable - java

I have three textboxes ct1,ct2,ct3. I have to use a for loop 1 to 3 and check whether the textboxes are empty. So, inside the for loop, how do I represent it? For example,
for(i=0;i<=3;i++)
{
if(ct+i.getText()) // I know I'm wrong
{
}
}

I have three textboxes ct1,ct2,ct3.
There's your problem to start with. Instead of using three separate variables, create an array or collection:
TextBox[] textBoxes = new TextBox[3];
// Populate the array...
Or:
List<TextBox> textBoxes = new ArrayList<TextBox>();
// Populate the list...
Then in your loop:
// Note the < here - not <=
for (int i = 0; i < 3; i++) {
// If you're using the array
String text = textBoxes[i].getText();
// or for the list...
String text = textBoxes.get(i).getText();
}
Or if you don't need the index:
for (TextBox textBox : textBoxes) {
String text = textBox.getText();
...
}

Use an array
TextBox[] boxes = new TextBox[]{ct1,ct2,ct3};
for(i=0;i<3;i++)
{
    boxes[i].getText(""); // I know I'm wrong
}

You can put your text boxes in a list and iterate over that list:
List<TextBox> ctList = new ArrayList<TextBox> ();
list.add(ct1);
list.add(ct2);
list.add(ct3);
for (TextBox ct : ctList) {
if(ct.getText().equals("expected text")) {
// do your stuff here
}
}

Related

Compress rows with same id

Hi i'm trying to loop through this structure:
id string1 string2 different_string
1 test test asd
1 test test dsa
2 data data qwe
3 info info ewq
3 info info zxc
3 info info qaz
I have rows with the exact same value but one of them is different so I'm trying to compress that data into a single row.
This is my code:
int actual_id = list.get(0).num(); //I pick the first id = 1
ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> items = new ArrayList<String>();
for(int i = 0; i < list.size(); i++){
if(list.get(i).id == actual_id){
String str = list.get(i).different_string;
items.add(str);
listOLists.add(items);
items.clear();
}else {
actual_id = list.get(i).id;
i--;
}
}
for(int j = 0; j < listOLists.size(); j++) {
System.out.println(listOLists);
}
First I check the id of each row and compare it with the actual value, I'm adding the string to an array and then append it to a list so I can store my data then reset the array to append new data to it and repeat the process, the problem is when I reset the array the loop doesn't seem to add more items to the list, what am I doing wrong?
this is I would like to get something like this:
{1, test, test, {asd, dsa}},{2, data, data, {asd}},{3, info, info, {ewq, zxc,qaz}}
Your code is a little difficult to follow but from what I can tell, your problem lies in this part of the code:
if(list.get(i).id == actual_id){
String str = list.get(i).different_string;
items.add(str);
listOLists.add(items);
items.clear();
}else {
You add items to listOList, but in the next line you clear it. items still refers to the List you just added to listOList so when you clear it, it clears the list in listOList as well. You may want to declare items within the if block so a new List will be created each pass through the loop like this:
if(list.get(i).id == actual_id){
ArrayList<String> items = new ArrayList<String>();
String str = list.get(i).different_string;
items.add(str);
listOLists.add(items);
}else {
This way, a new List is being created every iteration through the loop avoiding the issue. I can't tell if this will solve all you're problems but I hope this gets you headed in the right direction.

Android Studio - Array, ArrayList, List - JAVA

I am making a guessing game for as my School project, but I am quite new to Android Studio and Java.
At the moment my code looks like this:
public class MainActivity extends AppCompatActivity {
public int score = 0;
int random = random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button correct = (Button) findViewById(R.id.correct);
Button other = (Button) findViewById(R.id.other);
Button newGame = (Button) findViewById(R.id.newGame);
TextView words = (TextView) findViewById(R.id.words);
}
public Integer random (){
int random = (int )(Math.random() * 5);
return random;
}
private String list[] =
{"Dog", "Cat", "Mouse", "Elephant", "Rat", "Parrot"};
public void clickedButton(View view) {
TextView words = (TextView) findViewById(R.id.words);
if (view.getId()== R.id.newGame)
{
words.setText(list[random]);
score = 0;
Log.i("score", "score = " + score);
}
if (view.getId() == R.id.correct)
{
// set maybe new array so new textview does not give the same value
words.setText(list[random]);
score = score +1;
Log.i("score", "score = " + score);
}
if (view.getId() == R.id.other)
{
// set maybe new array so new textview does not give the same value
words.setText(list[random]);
Log.i("score", "score = " + score);
}
}
}
Idea is simple. I have my array with (at the moment) 6 words in it. So as I launch the game it gives me a random word on screen which I have to describe to others. If they guess it right I press correct, I get another word, if not I can pass and get another word... Well the problem I see is that there is chance that I get the same word over again. So I thought there should be a way how to fix this problem.
I thought about adding like if statements like if index 1 or 2 or 3 then give another word but if I had 100 words it would be monkey work to do it.
So I think there should be a chance how I can delete words from like temp. array, but there is no in-built method to do it.
I was reading that there are those arrayLists and lists but would not it be easier to use Array? and maybe some tips how to?
You can first Create an ArrayList (because it is more flexible):
List<String> list;
Then initialize the object in the constructor and shuffle the ArrayList like below:
list = new ArrayList<String>();
list.add("Dog");
list.add("Cat");
...
//or alternatively list.addAll(Arrays.asList(normalArray)); if you have your data in array
Collections.shuffle(list,new Random(System.nanoTime()); //randomly shuffles your list
Then you can keep track of the index of the last item you read:
int index = 0;
And every time you read an item just increase the index:
words.setText(list.get(index++));
This will do the trick
While there are a variety of ways solve your issue, personally I like mixing the array up (swapping places using random), then just keep an index on what word you are on in the array, so you don't have to keep track of the words in it.
I wrote a code for a similar program for doing a random shuffle on a deck of cards below, it goes through the int times amount, but you can remove it altogether and have a static loop value if you'd like:
// ...
// Random Shuffle
// Tip: Use this method to shuffle, may not be the fastest (not noticeable however), but it makes your array totally randomized.
public static void totalRandom(String[] array, int times)
{
// Random Initialize
Random randomGenerator = new Random();
// Variables
int first = 0;
int second = 0;
// Swap
for (int i = 0; i < times; i++)
{
// Generates number from 0 to array length
first = randomGenerator.nextInt(array.length);
second = randomGenerator.nextInt(array.length);
String word = array[second];
array[second] = array[first];
array[first] = word;
}
}
// ...
then after in your class you would want to write something along the lines of...
//...
int index = 0;
// ...
// Code for user input
// ...
if (userInput.equals(array[index]))
{
// do stuff
index++;
}
// ...
You can cache your last word. Add a String member variable.
...
public int score = 0;
public String cache; // new
Instead of using
words.setText(list[random]);
you can call a method to request a new word. You also save this word to the cache:
...
cache = getRandomWord();
words.setText(cache);
...
Your new method looks like this:
private String getRandomWord(){
int random = random();
String temp = list[random];
if(temp.equals(cache)){
temp = getRandomWord();
}
return temp;
}
Just put this method under your clickButton method. It takes a random word. Is the word equal to the previous word, the method will call itself again to pick another word. If not, it will return the new word.
There is no need to shuffle ArrayLists.
I think a more simple way is pop every shown text out from a copied list.
//when start a new game.
ArrayList<String> currentGameList = YourList.clone();
//when need next word.
String displayText = currentGameList.remove(randomIntInRestSize); //after called remove, you will get the object at list(index), and the object will be removed from the list.
Every game started, you just need to clone a new list from the original word list and play with the list.

checking if my array elements meet requirements

I need to create a method which checks each element in my array to see if it is true or false, each element holds several values such as mass, formula, area etc for one compound, and in total there are 30 compounds (so the array has 30 elements). I need an algorithm to ask if mass < 50 and area > 5 = true .
My properties class looks like:
public void addProperty (Properties pro )
{
if (listSize >=listlength)
{
listlength = 2 * listlength;
TheProperties [] newList = new TheProperties [listlength];
System.arraycopy (proList, 0, newList, 0, proList.length);
proList = newList;
}
//add new property object in the next position
proList[listSize] = pro;
listSize++;
}
public int getSize()
{
return listSize;
}
//returns properties at a paticular position in list numbered from 0
public TheProperties getProperties (int pos)
{
return proList[pos];
}
}
and after using my getters/setters from TheProperties I put all the information in the array using the following;
TheProperties tp = new properties();
string i = tp.getMass();
String y = tp.getArea();
//etc
theList.addProperty(tp);
I then used the following to save an output of the file;
StringBuilder builder = new StringBuilder();
for (int i=0; i<theList.getSize(); i++)
{
if(theList.getProperties(i).getFormatted() != null)
{
builder.append(theList.getProperties(i).getFormatted());
builder.append("\n");
}
}
SaveFile sf = new SaveFile(this, builder.toString());
I just cant work out how to interrogate each compound individually for whether they reach the value or not, reading a file in and having a value for each one which then gets saved has worked, and I can write an if statement for the requirements to check against, but how to actually check the elements for each compound match the requirements? I am trying to word this best I can, I am still working on my fairly poor java skills.
Not entirely sure what you are after, I found your description quite hard to understand, but if you want to see if the mass is less than 50 and the area is greater than 5, a simple if statement, like so, will do.
if (tp.getMass() < 50 && tp.getArea() > 5) {}
Although, you will again, have to instantiate tp and ensure it has been given its attributes through some sort of constructor.
Lots of ways to do this, which makes it hard to answer.
You could check at creation time, and just not even add the invalid ones to the list. That would mean you only have to loop once.
If you just want to save the output to the file, and not do anything else, I suggest you combine the reading and writing into one function.
Open up the read and the write file
while(read from file){
check value is ok
write to file
}
close both files
The advantage of doing it this way are:
You only loop through once, not three times, so it is faster
You never have to store the whole list in memory, so you can handle really large files, with thousands of elements.
In case the requirements changes, you can write method that uses Predicate<T>, which is a FunctionalInterface designed for such cases (functionalInterfaces was introduced in Java 8):
// check each element of the list by custom condition (predicate)
public static void checkProperties(TheList list, Predicate<TheProperties> criteria) {
for (int i=0; i < list.getSize(); i++) {
TheProperties tp = list.get(i);
if (!criteria.apply(tp)) {
throw new IllegalArgumentException(
"TheProperty at index " + i + " does not meet the specified criteria");
}
}
}
If you want to check if mass < 50 and area > 5, you would write:
checkProperties(theList, new Predicate<TheProperties> () {
#Override
public boolean apply(TheProperties tp) {
return tp.getMass() < 50 && tp.getArea() > 5;
}
}
This can be shortened by using lambda expression:
checkProperties(theList, (TheProperties tp) -> {
return tp.getMass() < 50 && tp.getArea() > 5;
});

Inserting a value into an array list, and remove any duplicates

I've got an array list of an object
Table[] tables = new Table[10];
this list stores information about 10 players and their position goes from top 1 which is tables[0] and top 10 that equals to tables[9]
however, sometimes I need to put a value in between the array, and let's say the player name i'm putting in must be top 5, that means, top 5 goes to top 4, and from top 4 to 3.. and 3 to 2.. and so on, but I also need to check if those values contain the player name that I just added so in that case I gotta remove it, and put all the list back up, pretty much add 1, does anyone have suggestions on the best way to do this, the way i'm thinking on doing it is probably not the best.
Here is what I made so far... however it's not complete..
private void addToBoard(Player damaged, Player killer) {
if(damaged.getName().equalsIgnoreCase(killer.getName())){
return;
}
for(Table table : tables){
if(table != null){
if(table.currentPlayer.equalsIgnoreCase("No One")){
table.currentPlayer = killer.getName();
break;
}else if(table.currentPlayer.equalsIgnoreCase(damaged.getName()) || table.currentPlayer.equalsIgnoreCase("Searching...")){
if(table.currentPlayer.equalsIgnoreCase(killer.getName())){
return;
}
if(table.currentPlayer.equalsIgnoreCase(killer.getName())){
return;
//update the list, and remove duplications
}
if(!table.currentPlayer.equalsIgnoreCase("Searching...")){
killer.chat("I killed "+damaged.getName()+" and now I am Top: "+table.topID+" gf :)");
}
table.currentPlayer = killer.getName();
if(table.topID != 10){
//make a list on a hashmap with the key from 1 to 10
HashMap<Integer, Table> addAll = new HashMap<Integer, Table>();
//add the top
for(int i = 0; i < tables.length; i++){
addAll.put(tables[i].topID, tables[i]);
}
HashMap<Integer, Table> updated = new HashMap<Integer, Table>();
String oldPlayer;
for(Entry<Integer, Table> top : addAll.entrySet()){
if(top.getValue().currentPlayer.equalsIgnoreCase(damaged.getName())){
//dont add
oldPlayer = top.getValue().currentPlayer;
top.getValue().currentPlayer = killer.getName();
Table next = updated.get((top.getValue().topID+1));
next.currentPlayer = oldPlayer;
updated.put(next.topID, next);
}else{
if(updated.containsKey(top.getValue().topID)){
updated.put((top.getValue().topID+1), top.getValue());
}else{
updated.put(top.getValue().topID, top.getValue());
}
}
}
for(int i = 0; i < tables.length; i++){
if(updated.get(i) != null){
tables[i] = updated.get(i);
}
}
}
break;
}
}
}
}
thanks!
Do not use an array. Use a List instead, which supports myList.add("New Guy", 4) -- that is, adding players in a given position and displacing all others one step up. You could then remove the 11th (old 10th) with myList.remove(10):
myList.add("New Guy", 4);
myList.remove(10);
You can do the same thing with arrays, but it is less readable:
// copies 4 elements from (old) pos. 4 to its new pos. 5
System.arraycopy(tables, 4, tables, 5, 4);
tables[4] = "New Guy";
Or use a loop, which is both hard to read (it has to go downwards to avoid losing information) and more verbose:
for (int i=9; i>=5; i--) tables[i] = tables[i-1];
tables[4] = "New Guy";

[Android]How to get item number(position) from a String[]

I have a String[] that contains number of strings, what I'm trying to do is set a ProgressBar's progress according to which string is used.
For example, I have already determined number of strings and set max progress of progress bar accordingly; here is the list:
"zero one two three four five six seven eight nine...."
..
String[] cpu0freqslist = cpu0freqs.split("\\s");
countcpu0 = cpu0freqslist.length;
..
ProgressBar cpu0progbar = (ProgressBar)findViewById(R.id.progressBar1);
cpu0progbar.setMax(countcpu0);
But now I need to set the progress of progressbar according to the item that is used, and I don't know how to get item position.
So if I want to set a progress bar to the position of item five (in this case it would be 6) how can I do that - how can I get the position of item five?
essentially what you're looking for is a indexOf(...) ...
since arrays don't have it, you'll have to search thru it to find the desired string. so something like this (feel free to optimize)
public int indexOfString(String searchString, String[] domain)
{
for(int i = 0; i < domain.length; i++)
if(searchString.equals(domain[i]))
return i;
return -1;
}
Then again, if you dynamically fetch your String[] data, it would be wiser to use an ArrayList and just invoke list.indexOf(myString);
You can use the Arrays utility class:
List<String> list = Arrays.asList(new String[] {"First", "Second", "Third"});
int index = list.indexOf("Second"); // 1
cpu0freqslist[5]
Does this help you?
Ok let me break your query into parts...
String[] arr = {"First","Second","Third"}; // String array with 3 elements
for(int i=0 ; i<arr.length ; i++){
int j = i ; // Position of the element
String s = a[i] ; // Element Itself
System.out.println("The "+i+" element is "+s);
}

Categories