Prime-Factoring Program Can Only Factor 4 - java

So I have a class that is supposed to take in a number and get the Prime factors. Those factors are then stored in an ArrayList, Factors, and printed out at the end. Problem is it only works for 4 and when I do 16 it freezes. Any help would be great!
My java class:
package com.frostbytedev.addsub;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Steven on 7/4/13.
*/
public class Factor extends Activity implements View.OnClickListener{
ArrayList<Integer> Factors = new ArrayList<Integer>();
ArrayList<Integer> toAdd = new ArrayList<Integer>();
ArrayList<Integer> toRemove = new ArrayList<Integer>();
int numToFactor;
TextView FactorResults;
EditText NumberInput;
Button bFactor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.factor);
initialize();
}
private void initialize() {
FactorResults = (TextView)findViewById(R.id.tvFactors);
NumberInput = (EditText)findViewById(R.id.etNumber);
bFactor = (Button)findViewById(R.id.bFactor);
bFactor.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.bFactor:
numToFactor = Integer.parseInt(NumberInput.getText().toString());
FactorNumber(numToFactor);
FindFactors(Factors);
PrintFactors(Factors);
}
}
private void PrintFactors(ArrayList<Integer> factors) {
//String joined = Factors.get(0)+", "+Factors.get(1);
String joined = TextUtils.join(", ", Factors);
FactorResults.setText(joined);
}
private void FactorNumber(int number) {
int multipliedFactors=1;
int i;
double middle = Math.ceil(number/2);
FactorResults.setText(String.valueOf(middle));
for(i=(int)middle;i>1;i--){
if(number%i==0){
Factors.add(i);
}
else
return;
}
for(i=0;i<Factors.size();i++){
multipliedFactors*=Factors.get(i);
}
if(multipliedFactors<number){
FactorNumber(number);
}
if(Factors.size()==0){
FactorResults.setText(number+" has no factors!");
}
}
public void FindFactors(ArrayList<Integer> factors){
int i;
for(i=0;i<factors.size();i++){
int y;
double middle;
middle = Math.ceil(factors.get(i)/2);
for(y=(int)middle;y>1;y--){
if(i%y==0){
toAdd.add(y);
toAdd.add(factors.get(i)/y);
toRemove.add(i);
RemoveExtras(toRemove);
AddNewFactors(toAdd);
FindFactors(Factors);
}
else
return;
}
}
}
private void AddNewFactors(ArrayList<Integer> toAdd) {
int i;
for(i=0;i<toAdd.size();i++){
Factors.add(toAdd.get(i));
}
}
private void RemoveExtras(ArrayList<Integer> toRemove) {
int i;
for(i=0;i<toRemove.size();i++){
Factors.remove(toRemove.get(i));
}
}
}

Try this algorithm
private void factorNumber(int n) {
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
if (n > 1) {
factors.add(n);
}
}

Related

App Crash on Arrayupdate within Ticklistener

im working through my first app right now and i have a problem concerning an update of an Arraylist object.
This is the code:
package com.example.stopwatchmulti;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class Main2Activity extends AppCompatActivity {
//Define Variables and Arrays
String ergebnis;
String stopTime;
int anzahl;
int hours;
int minutes;
int seconds;
Chronometer chronometer;
long pauseOffset;
boolean running;
int arrayelements = anzahl - 1;
long timeElapsed;
ListView customListview;
ArrayList<UserIDs> userList;
ArrayList<String> stoppedTime;
CustomListview adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ergebnis = getIntent().getExtras().getString("Ergebnis");
anzahl = Integer.parseInt(ergebnis);
chronometer = findViewById(R.id.chronometer);
customListview = (ListView) findViewById(R.id.customListview);
userList = new ArrayList<>();
// Add Lines in favour of UserChoice in First activity
for (int i = 1; i <= anzahl; i++) {
UserIDs user = new UserIDs(String.valueOf(i), "Chronometer" + String.valueOf(i), stopTime);
userList.add(user);
}
stopTime = String.valueOf(hours)+":"+String.valueOf(minutes)+":"+String.valueOf(seconds);
// Run Custom ArrayAdapter
adapter = new CustomListview(this, R.layout.usertableobjects, userList);
customListview.setAdapter(adapter);
}
public void startChronometer(View v) {
if (!running) {
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
running = true;
new Thread(new updateStoptime()).start();
}
}
public void pauseChronometer(View v) {
if (running) {
chronometer.stop();
running = false;
}
}
public void resetChronometer(View v) {
chronometer.setBase(SystemClock.elapsedRealtime());
}
class updateStoptime implements Runnable {
#Override
public void run() {
chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
timeElapsed = SystemClock.elapsedRealtime() - chronometer.getBase();
hours = (int) (timeElapsed / 3600000);
minutes = (int) (timeElapsed - hours * 3600000 / 6000);
seconds = (int) (timeElapsed - hours * 3600000 - minutes * 60000) / 1000;
stopTime = String.valueOf(hours)+":"+String.valueOf(minutes)+":"+String.valueOf(seconds);
Log.i("Zeit:", String.valueOf(stopTime));
}
});
while(running == true){
for (int i = 1; i <= anzahl; i++) {
userList.get(arrayelements).setUserTime(stopTime);
Log.i("LoopNr:", String.valueOf(i));
}
}
}
}
}
The update of the arraylist in the while loop is the reason why the app is crashing when the user clicks the button. If I just loop through and print the number of the loop in the logs, everything is ok.
Is it too much dada? How can I fix it?
PS. Basically I just need the actual countdowntime, when the user clicks the button and then update the listview with the updated array. So if there's a better and smarter way to achieve this instead of using a while loop, i would appreciate a hint.
Thx in advance
Quick correction:
// Here anzahl is not initialized and is being referred to in the next line.
// Please initialize anzahl first;
int anzahl;
int arrayelements = anzahl - 1;
Then, change your while loop to something like this.
while(running == true){
for (int i = 1; i <= anzahl; i++) {
/* here, just call "i -1". this is basically equal to "arrayelements"
which is not properly referenced up in your code.*/
userList.get(i - 1).setUserTime(stopTime);
Log.i("LoopNr:", String.valueOf(i));
}
}

How to solve stack memory problems?

iam trying to build an android app which makes users to do some calculation in a time limit. The code worked well until i divided the code into two parts and created another class for doing other task .
I have imported all the corressponding packages and class files to the new class .There were no errors in the code but when i run the app it crashes .I tried changing the code many times but no use. Code works well when i combine all the code into a single class.
the error i get is "java.lang.StackOverflowError: stack size 8MB on line number "
**MainActivity.java**
package e.nani.firstattempt;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public int a1;//random num 1
public int a2;//random num 2;
public TextView textview;
public Button b1;
public Button b2;
public Button b3;
public Button b4;
public int option1;
public int option2;
public int option3;
public int option4;
public int score=0;
TextView scoreid;
int numberofquestions=10;
TextView time;
public int answers[]=new int[4];
Logic c=new Logic();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview=(TextView)findViewById(R.id.sum);
b1=(Button)findViewById(R.id.option1);
b2=(Button)findViewById(R.id.option2);
b3=(Button)findViewById(R.id.option3);
b4=(Button)findViewById(R.id.option4);
time=(TextView)findViewById(R.id.timer);
scoreid=(TextView)findViewById(R.id.scoreid) ;
scoreid.setText((0+"/"+numberofquestions));
c.operatio();
timer.start();
}
public void operation(View V)
{
try{
switch(V.getId()) {
case R.id.option1:
if (b1.getText().equals(Integer.toString(option4))) {
score = score + 1;
c.operatio();
scoreid.setText((score +"/"+ numberofquestions));
} else {
Toast.makeText(this, "wrong answer", Toast.LENGTH_SHORT).show();
Vibrator vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
c.operatio();
}
break;
case R.id.option2:
if (b2.getText().equals(Integer.toString(option4))) {
score = score + 1;
c.operatio();
scoreid.setText(score+"/"+ numberofquestions);
} else
{
Toast.makeText(this, "wrong answer", Toast.LENGTH_SHORT).show();
Vibrator vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
c.operatio();
}
break;
case R.id.option3:
if (b3.getText().equals(Integer.toString(option4))) {
score = score + 1;
c.operatio();
scoreid.setText((score+"/"+ numberofquestions));
} else
{
Toast.makeText(this, "wrong answer", Toast.LENGTH_SHORT).show();
Vibrator vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
c.operatio();
}
break;
case R.id.option4:
if (b4.getText().equals(Integer.toString(option4))) {
score = score + 1;
c.operatio();
scoreid.setText(score+"/"+ numberofquestions);
} else
{
Toast.makeText(this, "wrong answer", Toast.LENGTH_SHORT).show();
Vibrator vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
c.operatio();
}
break;
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
CountDownTimer timer=new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
time.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
time.setText("done!");
}
};
}
Logic.java
package e.nani.firstattempt;
import java.util.Random;
class Logic {
MainActivity s=new MainActivity();
public void operatio() {
try {
Random n = new Random();
int n1 = n.nextInt(4);
int n2 = n.nextInt(4);
int n3 = n.nextInt(4);
int n4 = n.nextInt(4);
s.a1 = n.nextInt(51);
s.a2 = n.nextInt(35);
s.option1 = n.nextInt((s.a1 + s.a2) + 1);
s.option2 = n.nextInt((s.a1 + s.a2) + 1);
s.option3 = n.nextInt((s.a1 + s.a2) + 1);
s.option4 = s.a1 + s.a2;
s.answers[n1] = s.option1;
while (n2 == n1) {
n2 = n.nextInt(4);
}
while (s.option2 == s.option1 || s.option2 == s.option4) {
s.option2 = n.nextInt((s.a1 + s.a2) + 1);
}
s.answers[n2] = s.option2;
while (s.option3 == s.option2 || s.option3 == s.option1 || s.option3 == s.option4)
{
s.option3 = n.nextInt((s.a1 + s.a2) + 1);
}
while (n3 == n2 || n3 == n1)
{
n3 = n.nextInt(4);
}
s.answers[n3] = s.option3;
while (n4 == n2 || n4 == n1 || n4 == n3) {
n4 = n.nextInt(4);
}
s.answers[n4] = s.option4;
s.b1.setText(Integer.toString(s.answers[0]));
s.b2.setText(Integer.toString(s.answers[1]));
s.b3.setText(Integer.toString(s.answers[2]));
s.b4.setText(Integer.toString(s.answers[3]));
s.textview.setText(s.a1 + "+" + s.a2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The main question here is ,why is the app working fine when the code is only in main class but not working when some code is written in other class ?
ThankYou.
In your MainActivity you have a variable c with type Logic which is instantiated.
But in your Logic class has MainActivity type variable which try to instantiate MainActivity class. In a nutshell in a class A you instantiate class B which instatieates class A and so on...
By the way you cannot instantiate AppCompatActivity classes directly.
So remove MainActivity s=new MainActivity(); in your Logic.class.
Hope I could help you.

Why the arraylist empties itself when it is called optionPressed method?

Making a simple BrainTrain app, the updateAnswer method gives out random answers to the question but the issue comes up whenever i call the optionsPressed method and try getting any of the object, the arrayList gives out IndexOutOfBoundsException.
package com.example.nishantsaini.braintrain;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
import static android.R.color.black;
import static android.R.color.holo_blue_bright;
import static android.R.color.holo_blue_dark;
import static android.R.color.holo_blue_light;
import static android.R.color.holo_green_light;
public class MainActivity extends AppCompatActivity {
Random rnd = new Random();
boolean gameisActive = false;
int count = 0;
CountDownTimer cd;
int var1,var2;
ArrayList<Button> options;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cd = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long l) {
Log.i("Time Left:", Long.toString(l / 1000));
TextView timer = (TextView) findViewById(R.id.timer);
timer.setText("0:" + String.format("%02d", (l / 1000)));
}
#Override
public void onFinish() {
TextView score = (TextView) findViewById(R.id.Score);
LinearLayout onFinishLayout = (LinearLayout) findViewById(R.id.onFinishLayout);
/*score.setText( "You got " + getScore() + "right!");
*/
}
};
options = new ArrayList<>();
options.add((Button) findViewById(R.id.option2));
options.add((Button) findViewById(R.id.option1));
options.add((Button) findViewById(R.id.option3));
options.add((Button) findViewById(R.id.option4));
}
public void start(View view) {
cd.start();
Button start = (Button) findViewById(R.id.start);
updateQuestion();
updateAnswers(options);
start.setText("Replay");
}
public void optionPressed(View view){
ColorDrawable blue_d = new ColorDrawable(getResources().getColor(R.color.blue_b));
ColorDrawable blue_l = new ColorDrawable(getResources().getColor(R.color.blue_l));
ColorDrawable blue_b = new ColorDrawable(getResources().getColor(R.color.blue_b));
ColorDrawable green = new ColorDrawable(getResources().getColor(R.color.green));
Drawable color = blue_b;
while(options.size() > 0) {
int index = rnd.nextInt(options.size());
Button b = options.get(index);
if (color == blue_b){
color = blue_d;
b.setBackground(color);
}
else if (color == blue_d){
color = green;
b.setBackground(color);
}
else if (color == green){
color = blue_l;
b.setBackground(color);
}
else if (color == blue_l)
{
color = blue_b;
b.setBackground(color);
}
options.remove(index);
}
updateQuestion();
updateScore();
updateAnswers(options);
}
public void updateQuestion(){
var1 = 5 + (int)(Math.random()*20);
var2 = 5 + (int)(Math.random()*20);
TextView question = (TextView) findViewById(R.id.question);
question.setText(Integer.toString(var1) +" + " + Integer.toString(var2) + " = ");
question.setPadding(0,50,0,0);
}
public void updateScore(){
count++;
int correct = 0;
TextView score = (TextView) findViewById(R.id.points);
score.setText(Integer.toString(correct) + "/" + Integer.toString(count));
}
public void updateAnswers(ArrayList<Button> arrayList ){
Button b;
int answer = var1 + var2;
int indexAtWhichRealAnswerGoes = 1+ (int) (Math.random()*3);
int id ;
Log.i("arraylist size",Integer.toString(options.size()));
b = arrayList.get(indexAtWhichRealAnswerGoes);
b.setText(Integer.toString(answer));
id = b.getId();
arrayList.remove(indexAtWhichRealAnswerGoes);
for (int i = 0; i < arrayList.size(); i++) {
int randomanswer = (answer-7) + (int)(Math.random()*(answer+7));
b = arrayList.get(i);
b.setText(Integer.toString(randomanswer));
}
arrayList.add((Button) findViewById(id));
Log.i("arraylist size",Integer.toString(arrayList.size()));
}
}
So, you call updateAnswers(options); using the list that you previously emptied
while(options.size() > 0) {
int index = rnd.nextInt(options.size());
...
options.remove(index);
}
...
updateAnswers(options);
At that point, the list is empty.
In the method, you safely used for (int i = 0; i < arrayList.size(); i++) { to prevent any error but before that we see
int indexAtWhichRealAnswerGoes = 1+ (int) (Math.random()*3);
...
b = arrayList.get(indexAtWhichRealAnswerGoes);
You get that random index without checking the size of the list. (List that is empty at that point).
If you want to keep the list with its value, but the logic can't be change so the remove is necessary, you need to do a copy of the list to work on that one, and pass the original to the method updateAnswers.
List<Button> copyOptions = new ArrayList<>(options);
It will share the same instance, but you can update the list copyOptions without having any impact on options

How to make Android Guessing Game to restrict the number of guesses to 3 attempts after which a message will be displayed

I need to make the android guessing game I have so far to have a limit of 3 attempts after which the message like game over will be displayed, however I have no idea how to do it as I'm still new to programming so I would appreciate your help
Android Code I have so far:
import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Task1Activity extends Activity {
private TextView tvPlayer;
private EditText eName;
private Button butSubmit;
private TextView nameOutput;
private TextView tvNumber;
private EditText eNumber;
private TextView numOutput;
private Button butGuess;
private Button butStart;
private String name_output;
private String number_output;
private TextView tvTries;
private TextView tvTries2;
public static int N;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task1_layout);
//Reference the input and output views on the interface
tvPlayer = (TextView) findViewById(R.id.tvPlayer);
eName = (EditText) findViewById(R.id.eName);
butSubmit = (Button) findViewById(R.id.butSubmit);
tvNumber = (TextView) findViewById(R.id.tvNumber);
eNumber = (EditText) findViewById(R.id.eNumber);
butGuess = (Button) findViewById(R.id.butGuess);
butStart = (Button) findViewById(R.id.butStart);
nameOutput = (TextView) findViewById(R.id.nameOutput);
numOutput = (TextView) findViewById(R.id.numOutput);
tvTries = (TextView) findViewById(R.id.tvTries);
tvTries2 = (TextView) findViewById(R.id.tvTries2);
}
public void addClick1(View Button){
name_output = eName.getText().toString(); //get the existing comments
nameOutput.setText(name_output);//Display the new comments
} public void addClick2(View Button){
Random r = new Random();
int Low = 0;
int High = 20;
N = r.nextInt(High-Low) + Low;
}
public void addClick3(View Button){
number_output = eNumber.getText().toString(); //get the existing comments
try {
int compareNum = Integer.parseInt(number_output);
if(compareNum == N){
numOutput.setText(number_output + " Good Guess!");//Display the new comments
numOutput.setBackgroundColor(Color.GREEN);
}else if(compareNum > N){
numOutput.setText(number_output + " is too HIGH!");//Display the new comments
numOutput.setBackgroundColor(Color.RED);
}else if(compareNum < N){
numOutput.setText(number_output + " is too LOW!");//Display the new comments
numOutput.setBackgroundColor(Color.RED);
}
}
catch (NumberFormatException e) {
}
}
}
You have to get a count on the clicks something like:
public void addClick2(View Button){
Random r = new Random();
int Low = 0;
int High = 20;
int count = 0;
N = r.nextInt(High-Low) + Low;
}
public void addClick3(View Button){
count++;
number_output = eNumber.getText().toString(); //get the existing comments
try {
int compareNum = Integer.parseInt(number_output);
if(compareNum == N){
numOutput.setText(number_output + " Good Guess!");//Display the new comments
numOutput.setBackgroundColor(Color.GREEN);
}else if(compareNum > N){
numOutput.setText(number_output + " is too HIGH!");//Display the new comments
numOutput.setBackgroundColor(Color.RED);
}else if(compareNum < N){
numOutput.setText(number_output + " is too LOW!");//Display the new comments
numOutput.setBackgroundColor(Color.RED);
}
}
catch (NumberFormatException e) {
}
if(count == 3){
//set your game over message
}
}
}

How to count duplicates in ArrayList<Integer> in Java and return them as string

How can I count duplicates in ArrayList and return them as string?
For example I have ArrayList [1,3,4,4,5,6,3,4,6] and I want to have method which will count occurrence of Array items and show them when they will occur more than one time in output format like this:
3 - 2; 4 - 3; 6 - 2;
I've tried with something like that
`
import java.util.ArrayList;
import java.util.Random;
import java.util.HashSet;
import java.util.Set;
import java.util.Collections;
public class GeneratorKostek {
public int ileKostek;
Random rand = new Random();
String wynik;
private ArrayList<Integer> rzuty;
private ArrayList<String> dublety;
private int rzut = 0;
private int ileScian;
private int suma;
public GeneratorKostek() {
rzuty = new ArrayList<Integer>();
}
public GeneratorKostek(int IleKostek, int IleScian) {
ileKostek = IleKostek;
ileScian = IleScian;
rzuty = new ArrayList<Integer>();
}
public void Rzucaj(int IleKostek, int IleScian) {
ileKostek = IleKostek;
ileScian = IleScian;
for (int i = 0; i < ileKostek; i++) {
rzut = rand.nextInt(ileScian) + 1;
rzuty.add(rzut);
}
}
public String PrezentujRzuty() {
wynik = "";
for (int i : rzuty) {
wynik = wynik + i;
}
return wynik;
}
public void CzyscRzuty() {
rzuty.clear();
}
public int SumaWartosciRzutow() {
suma = 0;
for (int i : rzuty) {
suma += i;
}
return suma;
}
public String PrezentacjaDubletow() {
Set<Integer> noDupes = new HashSet<Integer>();
noDupes.addAll(rzuty); // Remove duplicates
for (Integer i : noDupes) {
int wystapienia = Collections.frequency(rzuty, i);
if (wystapienia > 1) {
dublety.add(i + " - " + wystapienia + ";" );
}
}
for (int i =0 ; i < dublety.size(); i++) {
wynik = wynik + dublety.get(i);
}
return wynik;
}
}
`
I'm just starting my adventure with programming...
I'm calling it in other class
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends ActionBarActivity {
GeneratorKostek Kostki = new GeneratorKostek();
ArrayList<Integer> wyniki = new ArrayList<Integer>();
String wynik;
Button btnk6, btn2k6, btn3k6, btn4k6, btn5k6, btn6k6;
TextView tvWynik;
EditText etInfo;
Random rand = new Random();
int kostka1, kostka2, kostka3, kostka4, kostka5, kostka6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnk6 = (Button) findViewById(R.id.btnk6);
btn2k6 = (Button) findViewById(R.id.btn2k6);
btn3k6 = (Button) findViewById(R.id.btn3k6);
btn4k6 = (Button) findViewById(R.id.btn4k6);
btn5k6 = (Button) findViewById(R.id.btn5k6);
btn6k6 = (Button) findViewById(R.id.btn6k6);
tvWynik = (TextView) findViewById(R.id.tvWynik);
etInfo = (EditText) findViewById(R.id.etInfo);
btnk6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Kostki.CzyscRzuty();
Kostki.Rzucaj(1, 6);
tvWynik.setText(Kostki.PrezentujRzuty());
}
});
btn2k6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Kostki.CzyscRzuty();
Kostki.Rzucaj(2, 6);
tvWynik.setText(Kostki.PrezentujRzuty());
}
});
btn3k6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Kostki.CzyscRzuty();
Kostki.Rzucaj(3, 6);
tvWynik.setText(Kostki.PrezentujRzuty());
}
});
btn4k6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Kostki.CzyscRzuty();
Kostki.Rzucaj(4, 6);
tvWynik.setText(Kostki.PrezentujRzuty());
}
});
btn5k6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Kostki.CzyscRzuty();
Kostki.Rzucaj(5, 6);
tvWynik.setText(Kostki.PrezentujRzuty());
}
});
btn6k6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Kostki.CzyscRzuty();
Kostki.Rzucaj(6, 6);
tvWynik.setText(Kostki.PrezentujRzuty());
etInfo.setText(Kostki.PrezentacjaDubletow());
}
});
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.container, new PlaceholderFragment())
// .commit();
// }
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}`
Sort the list, then it's easy to count the items.
Create a Map object with keys of each unique item in the ArrayList.
Iterate through your List, querying the Map to see if there's an entry for that item. If there is, increment the value stored, otherwise initialize it with 1.
Edit*: Here's an example
package com.count.list.items;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ListItemCounter
{
public void start()
{
List<Integer> list = getList(1, 1, 5, 3, 7, 3, 11, 2, 3, 1);
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer i : list)
{
Integer retrievedValue = map.get(i);
if (null == retrievedValue)
{
map.put(i, 1);
}
else
{
map.put(i, retrievedValue + 1);
}
}
System.out.println("list: " + list);
printCount(map);
}
private List<Integer> getList(int... numbers)
{
List<Integer> list = new ArrayList<Integer>();
for (int i : numbers)
{
list.add(i);
}
return list;
}
private void printCount(Map<Integer, Integer> map)
{
for (Integer key : map.keySet())
{
System.out.println("number: " + key + ", count: " + map.get(key));
}
}
}
Try this code:
public static void main(String[] args) {
String input = "I am am akash pal pal pal";
System.out.println("Before removing duplicate: "+input);
String[] arr = input.split(" ");
int count=0;
System.out.println(arr.length);
for (int i = 0; i < arr.length; i++) {
if (arr[i] != null) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i].equalsIgnoreCase(arr[j])) {
//System.out.println("Duplicates are \n"+arr[i]);
arr[j] = null;count++;
}
}
}
}
System.out.println("After");
for (int k = 0; k < arr.length; k++) {
if (arr[k] != null)
System.out.print(arr[k] + " ");
}
System.out.println("");
System.out.println("Duplicates \t"+count);

Categories

Resources