Hello guys I'am beginner of the Java and i've got some problems with array&arraylist. My main problem is how to write computing, dynamic data into the array and later how to read it? Here's my weird code:
public static void main(String[] args) {
int yil, bolum = 0, kalan;
Scanner klavye = new Scanner(System.in);
ArrayList liste = new ArrayList();
//or shall i use this? >> int[] liste = new int[10];
System.out.println("Yıl Girin: "); // enter the 1453
yil = klavye.nextInt();
do{ // process makes 1453 separate then write in the array or arraylist. [1, 4, 5, 3]
kalan = yil % 10;
liste.add(kalan); //my problem starts in here. How can i add "kalan" into the "liste".
bolum = yil / 10;
yil = bolum;
}while( bolum == 0 );
System.out.println("Sayının Basamak Sayısı: " + liste.size()); //in here read the number of elements of the "liste"
klavye.close();
}
Edit:
//needs to be like that
while( bolum != 0 );
System.out.println("Sayının Basamak Sayısı: " + liste);
I think that you most likely want your loop stopping condition to be:
while( bolum != 0)
because bolum will only be 0 when there are no more digits left in your number to process. Also, as amit mentions above it could be the case that the user entered 0 when prompted for a number, so you should take that into account.
To obtain a string representation of your ArrayList (showing the elements it contains through their string representations), you can just use
System.out.println("Sayının Basamak Sayısı: " + liste);
No need to convert to an array. This works because it causes liste's toString method to be called (which is why we don't need to call it explicitly).
You must change this line:
}while( bolum == 0 );
To this:
}while( bolum > 0 );
If you want to print your elements in the ArrayList, update your last statement to print as below:
System.out.println("Sayının Basamak Sayısı: " + liste);
Or you can iterate your list and print as :
for(Object i: liste){
System.out.println(i);
}
This will print your individual list items in separate lines.
Also please fix your while condition as while(bolum != 0); as it may terminate after the very first iteration as bolum will be non zero i.e. 1, 2...(!= 0).
Related
I am having trouble in printing number in series like 1,2,3,4,5 through for loop. I have code a mark sheet where we take numbers as input from user and then print them through for loop like Subject 1 is = 33
val x = arrayListOf<String>()
for (i in 0..4) {
println("Enter Marks of Subject ${i+1}")
x.add(readLine()!!)
}
for(Marks in x) {
for(f in 0..0) {
println("Subject ${f + 1} is $Marks")
}
}
If I understood your question:
for (f in 0..x.size - 1)
println("Subject ${f+1} is ${x[f]}")
you don't need the outer loop
Your inner loop never updates the value of f so you are always getting the same value of f = 0 + 1. Anyway, you can do the same operation with a single loop, like so:
for(i in 0 until x.size) {
println("Subject ${i+1} is ${x[i]}")
}
I know that if you have two HashSet the you can create a third one adding the two.However, for my purpose I need to change my previous HashSet, look for certain condition , and then if not met then change the set again.My purpose is that that I will give an input, say number 456, and look for digits(1 through 9, including 0).If I'm unable to find size 10 for the HashSet then I will multiply the number with 2 , and do the same.So I'll get 912; the size is 6 now(and I need to get all digits 1-9 & 0, i.e., size 10).Now I will multiply it by 3 and I get 2736 , the size is now 7.I keep doing so until I get size 10.At the time I get size 10, I will complete the loop and return the last number that concluded the loop, following the incremental multiplication rule.My approach is as follows.It has errors so won't run but it represents my understanding as of now.
public long digitProcessSystem(long N) {
// changing the passed in number into String
String number = Long.toString(N);
//splitting the String so that I can investigate each digit
String[] arr = number.split("");
// Storing the digits(which are Strings now) into HashSet
Set<String> input = new HashSet<>(Arrays.asList(arr));
// Count starts for incremental purpose later.
count =1;
//When I get all digits; 1-9, & 0, I need to return the last number that concluded the condition
while (input.size() == 10) {
return N;
}
// The compiler telling me to delete the else but as a new Java user so far my understanding is that I can use `else` with `while`loops.Correct me if I'm missing something.
else {
// Increment starts following the rule; N*1, N*2,N*3,...till size is 10
N = N*count;
// doing everything over
String numberN = Long.toString(N);
String[] arr1 = number.split("");
// need to change the previous `input`so that the new updated `HashSet` gets passed in the while loop to look for size 10.This is error because I'm using same name `input`. But I don't want to create a new `set` , I need to update the previous `set` which I don't know how.
Set<String> input = new HashSet<>(Arrays.asList(arr1));
// increments count
count++;
}
clear() input and add the new values. Something like
// Set<String> input = new HashSet<>(Arrays.asList(arr1));
input.clear();
input.addAll(Arrays.asList(arr1));
and
while (input.size() == 10) {
should be
if (input.size() == 10) {
Or your else isn't tied to an if.
Alright, I'm making a method that should be able to remove objects from an array list through the use of a string input.
Say I want to remove the following numbers: {1,2,4,3,3,1} from an arraylist. How can I ensure that it only removes 1 & 3 twice and 4 & 2 once?
What I have is:
mv.displayMessages("choosedicestokeep");
String in = mv.getInput();
for (char c : in.toCharArray()) {
int x = Character.getNumericValue(c);
for (Iterator<Integer> it = rollingHand.iterator(); it.hasNext(); ){
int i = it.next();
if (x == i) {
finalHand[finalArrIndex] = i;
it.remove();
finalArrIndex++;
}
}
}
But this checks the arraylist "RollingHand" and removes ALL instances of a number and not the number of times I write a number which is what I want.
So if i enter {1,1,1,2,2,4} it should remove three 1s, two 2s and one 4.
https://stackoverflow.com/users/4584292/mike Solved the obvious answer.
Breaking to a statement outside the inner loop solved the problem.
The method doesn't return anything because it sets a private int[] finalHand in the class which is later accessed by other methods.
All cred to Mike!
New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;
cantmano is the index, it starts on 0. Another method increases with cant++.
I recheck that 0 <= cantmano <= 10
public void dibujar(){
//actualiza la pantalla
if (cantmano >= 0 && cantmano < 10 && cantcroupier >= 0 && cantcroupier < 10){
TextView textomano = (TextView)findViewById(R.id.textView3);
TextView textocroupier = (TextView)findViewById(R.id.textView5);
CharSequence buffer = textomano.getText();
textomano.setText( buffer + " " +
String.valueOf(manojugador[cantmano].getPalo())+ " de " +
String.valueOf(manojugador[cantmano].getNumero()) ); // <-- ERROR
textocroupier.setText( String.valueOf(cantmano) );
}
}
I get a nice
Caused by: java.lang.NullPointerException
at com.pruebas.blackjack.blackjack.dibujar(blackjack.java:58)
at com.pruebas.blackjack.blackjack.onCreate(blackjack.java:23)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2717)
EDITS:
.getNumero() returns the int with the value of a requested CARD. (playing card type)
.getPalo() returns an int where 1= diamonds, etc.
initialization of manojugador:
Carta manojugador[]= new Carta[10];
constructor of Carta:
public Carta(){
int palo=0;
int numero=0;
}
MIDNIGHT UPDATE:
With some improvements i managed it to get over the error. BUT now the array has all 0 values when written. This has to be an easy to solve but that's the final step before accepting the best answer.
Here's the method that adds cards:
public void hit(View v){
//sacan cartas
if (cantmano < manojugador.length){
manojugador[cantmano]=mazo.darcarta(); //adds a random Card to the manojugador. mazo means deck.
manocroupier[cantcroupier]=mazo.darcarta(); //adds a random Card to the manojugador. mazo means deck.
cantmano++;
cantcroupier++;
}
dibujar();
}
You must initialize the array and it's elements. If you simply have this:
Carta manojugador[]= new Carta[10];
then all 10 elements of the array will be null. You must also initialize each element. Something like this:
for(int i=0, length=manojugador.length; i<length; i++) {
manojugador[i] = new Carta();
}
Update:
I see that in your hit() method, I see you have:
if (cantmano <= 8) {
Shouldn't that be:
if (cantmano < 10) {
Or even better:
if (cantmano < manojugador.length) {
I think that what is happening in your code to cause the NullPointerException is that manojugador[9] can never be initialized.
Your manojugador array null elements and your cantmano is somehow pointing to one of those null elements.
For instance, let's say you have:
ManoJugador [] cantmano = new ManoJugador[10];
cantmano[0] = new ManoJugador();
cantmano[1] = new ManoJugador();
cantmano[2] = new ManoJugador();
You array beyond index 3 you have nulls. That's why when your try to get the numero of null you get NullPointerException.
EDIT
As per your edit:
Yeap, definitely, you have a null value there. Debug that part and you'll see some null values
hint: System.out.println( java.util.Arrays.toString( someArray ));
Suerte!