In Java you can use a for each loop by saying:
for (elemento e : array)
Also in jQuery:
$.each(arr, function() {
In JavaScript I know I can do:
for (var i = 0; i > 10; i ++)
But is there a way to do a for each in pure JavaScript?
In Java you can use a for each loop by saying:
for (elemento e : array)
Also in jQuery:
$.each(arr, function() {
In JavaScript I know I can do:
for (var i = 0; i > 10; i ++)
But is there a way to do a for each in pure JavaScript?
Let's take this method:
public static void getDecimalPart(double n) {
int decimales = 0;
// convertimos el valor a string
String decimalPartString = String.valueOf(n);
// comprobamos si contiene punto de decimales
if (decimalPartString.contains(".")) {
// lo partimos y lo ponemos en un array
String[] doubleArray = decimalPartString.split(".");
// calculamos los decimales
decimales = (int) (Double.valueOf(doubleArray[1]) * (Math.pow(10, doubleArray[1].length()-2)));
}
// imprimimos
System.out.println("El numero " + n + " tiene " + decimales + " decimales");
}
It checks if the string contains(".")
and if so it does split(".")
... then... why when I run:
public static void main(String[] args) {
getDecimalPart(1.25698);
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at q1607.Q38239413.getDecimalPart(Q38239413.java:25) at q1607.Q38239413.main(Q38239413.java:14)
Debugging even confuses me even more since the array is totally empty, it does not matter IOOB
to ask for position 1 and that it does not exist, but rather:
doubleArray = []
What am I not seeing or what am I forgetting? , I'm sure it's something totally obvious but I don't see it....
Things I have tried:
Use the system decimal symbol:
DecimalFormat format=(DecimalFormat) DecimalFormat.getInstance();
DecimalFormatSymbols symbols=format.getDecimalFormatSymbols();
char sep=symbols.getDecimalSeparator();
In the end I have done the different method, but I am still intrigued as to what is happening.
I am mounting a new server, as always in an Eclipse Mars (4.5.2) Eclipse Java EE IDE for Web Developers , I had a problem with the installation of the server, I deleted it and I found this bug that is already solved, but now, when importing the project base tells me...
The import javax.servlet cannot be resolved
I know that I can import the library manually... but taking into account that I have the correct eclipse it does not have to be done, besides that would give me future problems....
I have finished a website and I am creating the necessary 301 redirects in the .htaccess
.
I have one of the old web sitemaps that has 100+ requests of the type:
?menu=nombre-del-plato
On the new web there are no similar requests and they should all be redirected to, say,http://mirestaurante.com/menu
Is there a way to avoid these 100+ same lines in the .httacces
?:
Instead of:
Redirect 301 /?menu=nombre-del-plato1 http://mirestaurante.com/menu
Redirect 301 /?menu=nombre-del-plato2 http://mirestaurante.com/menu
Redirect 301 /?menu=nombre-del-plato3 http://mirestaurante.com/menu
Redirect 301 /?menu=nombre-del-plato4 http://mirestaurante.com/menu
Make a line or function similar to:
Redirect 301 ?menu* http://mirestaurante.com/menu
EDIT: these requests are in two languages
Redirect 301 /?menu=nombre-del-plato3 http://mirestaurante.com/menu
Redirect 301 /ca/?menu=nombre-del-plato3 http://mirestaurante.com/ca/menu
I have a margin made like this ( Fiddle example ):
.menu--margen {
background: #f4f4f4;
border-right: 1px solid #bbbbbb;
border-left: 1px solid #bbbbbb;
border-top: 1px solid #bbbbbb;
border-bottom: none;
margin: 3px auto;
position: relative;
}
.menu--margen:before {
padding: 20px;
border-right: 1px solid #f0f0f0;
border-left: 1px solid #f0f0f0;
border-bottom: 1px solid #f0f0f0;
border-top: none;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
Is there a way to simplify the css of the border? I have tried:
border: 1px 1px 0px 1px solid #f0f0f0;
But it doesn't seem to work.
I have a wordpress with a theme in which I want to customize a title that I want to look like this :
But the source looks like this :
I have manually assigned the font it uses and other css effects:
.text--superior {
margin-bottom: 15px !important;
font-size: 59px;
font-family: "Herr Von Muellerhoff" !important;
}
I've also tried text-transform
but it doesn't work
How do I get rid of the excess italics that the font currently has?
I am analyzing a code and I have found the class Constantes
, which, as its name indicates, has this structure:
public final class Constantes {
public static final String PREFIJO = "prefijo_";
}
In another class I have seen this import
:
import static mi.paquete.Constantes.*;
So when using the constant class attributes you do so directly by name,
String nombreFichero = PREFIJO + nombre;
No need to reference the class as with normal imports:
String nombreFichero = Constantes.PREFIJO + nombre;
I did not know the technique of import static
and it seems quite interesting to me to clean code, as long as:
But:
I have a method that gets the index to use in my own markdown system.
Indices are passed to the method and it has to return the lowest greater than -1 (not found) until now we only had negrita
, cursiva
and normal
the method was relatively simple (although it seems ugly to me with desire):
private int getValidIndexToUse(int indexOfBold, int indexOfItalics) {
if (indexOfBold > -1 && indexOfItalics == -1)
return indexOfBold;
else if (indexOfItalics > -1 && indexOfBold == -1)
return indexOfItalics;
else
return indexOfBold > -1 && indexOfBold < indexOfItalics ? indexOfBold : indexOfItalics;
}
Now you have to add cursiva+negrita
and underline and with this system the method becomes crazy.
Does anyone have any better ideas than nesting infinite if's?
How do I create a regular expression that validates if a String is:
,
decimal pointAlso:
.
as a symbol for thousands.I have tried to create it:
[0-9,]+[^.]
But the results:
22,33 CORRECTO
33.44 INCORRECTO
22,33... CORRECTO // PERO DEBERIA SER INCORRECTO!!!
232.33dfdfd CORRECTO // PERO DEBERIA SER INCORRECTO!!!
Expected results:
22,33 CORRECTO
225,3432 CORRECTO
33.44 INCORRECTO
22,33... INCORRECTO
23, INCORRECTO
I know I can declare an array in JavaScript like this var miArray = [];
, I can also add elements with miArray.push(elemento);
.
But: How do I add or remove elements in a certain position?
I have seen that it exists splice()
and that it does both things (delete and add) but I don't quite understand how it works correctly with the examples I have found.
Why if I use BigDecimal
in this case, I don't get the expected result?
double value1 = 5.68;
double value2 = 2.45;
System.out.println(BigDecimal.valueOf(value1 + value2));
8.129999999999999
8.13
I'm passing an app Java6
to java-8 , there are cases where we have to count the occurrences of a String
in a list. For this we use:
Collections.frequency(lista, stringALocalizar);
I think this part should not be touched. If, instead, we have to count all String
and their occurrences across the entire list we have to iterate over the list and use a HashMap<String, Integer>
to store the results and not perform the extra iterations that would cause Collections.frequency
. Something like this:
for (String stringALocalizar : lista) {
if (mapaDeResultados.containsKey(stringALocalizar)) {
mapaDeResultados.put(stringALocalizar, mapaDeResultados.get(stringALocalizar)+1);
} else {
mapaDeResultados.put(stringALocalizar, 1);
}
}
How can I achieve the same result with java-8 streams ?
Is there a way to remove a character typed by console with System.out
or System.err
?
For example if I have a process that loads for a while, simulate an animation with the 3 ellipses ...
. Something similar to this demo on fiddle .
int puntos = 0;
final String PUNTO = ".";
System.out.print("Conectando, espera");
while (condicionQueSeCumplaAlAcabarElProceso) {
if (puntos < 3) { // comprobar cuantos puntos hay
System.out.print(PUNTO); // poner un punto
puntos ++; // indicarlo
try {
Thread.sleep(1000); // esperar 1 segundo
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
} else {
// aqui hay que borrar los 3 puntos ¿como se hace?
puntos = 0; // resetear
}
}
I have a list for validated mobile numbers that I have to display in the same way:
The desired format is:+34 666 111 222
String telefonos =
"666444555,
666-444-555,
666 44 45 55,
666-44-45-55,
+34666555444,
0034666555444";
Pattern pattern = Pattern.compile(""); // aqui es donde me clavo.
Matcher matcher = pattern.matcher(telefonos);
while (matcher.find())
System.out.println(matcher.group());
Expected output:
+34 666 444 555
+34 666 444 555
+34 666 444 555
+34 666 444 555
+34 666 555 444
+34 666 555 444
How do I create a regular expression that validates Spanish mobile phone numbers?
They must follow the following rules.
At the beginning:
+34
34
0034
From here you should have:
6
or7
Valid:
666444555
666-444-555
666 44 45 55
666-44-45-55
+34666555444
0034666555444
Not valid
935554488
+44777555444
800444666
635*554*488
635/554/488
NOTE: It's labeled java because that's how I'm going to parse
String
it and if you want to show code. Of course, it is not strictly necessary, with the regular expression I have enough.
In the code I see many times x++
in loops, but sometimes I find ++x
.
Is there a difference between these two expressions?
I have a series of labels
in my view JSP
. Each label
shows a unit of measure and in case you want to edit it, it is replaced via javascript by a input
via button.
NOTE: both the labels and the input are elements with class="CCC_UNIDAD" to iterate them later. The html
simplified result would look something like this:
<label class="CCC_UNIDAD">%</label>
<input class="CCC_UNIDAD">
<input class="CCC_UNIDAD" value="$">
<label class="CCC_UNIDAD">€</label>
$.each($(".CCC_UNIDAD"), function (index, value) {
var valor = value.textContent === undefined
? (value.value === undefined ? "" : value.value)
: value.textContent;
alert("VALOR = " + valor);
});
As you can see, in the snippet, I try to get the value of the label ( value.textContent
), if it does not have it, I look for the value of the input value.value
but it is not working correctly.
How can I differentiate what type of element the variable is value
in order to get the attribute corresponding to each type?
This question is to share a very simple trick I learned on StackOverflow that has helped me clean thousands of cases in my code.
NOTE: it is not a translation, it is simply a transmission of knowledge that I think is necessary and interesting and originally created by me for SO in Spanish.
We have all assembled a text string by hand by inserting the separators, for example:
Characteristics of an element (car) separated by commas,
ABS, ESP, EE, CC
Printable list with line breaks\n
producto1 2,23\n
producto2 3,23\n
producto33 5,31\n
And we have encountered one of the following problems:
insert a comparison to each iteration:
JAVA
// bucle que inserta valor v en variable x
if ("".equals(x)) x = v;
else x = "," + v;
JAVA SCRIPT
// bucle que inserta valor v en variable x
if (x == "") x = v;
else x = "," + v;
if we do not insert that comparison to optimize, we still have to do it later to avoid
last empty element:
1,1,1,1,1,
// ↑ aquí!
first empty element
,1,1,1,1,1
//↑ aquí!
Is there a pattern to avoid this usual and annoying case and that meets the following characteristics?
I have always seen that JavaScript
there is:
=
==
and===
I understand that it ==
does something similar to compare the value of the variable and ===
it also compares the type (like a java equals).
Could someone confirm this point for me and extend it? . I'm a Javanese and sometimes I love javascript untyping and sometimes I hate it.
What is the correct way in javascript to compare undefined
, null
and other default values?
variable == null
variable === null
Is undefined
it used as a text string or as a keyword? Which of the following comparisons is correct for an element html
without value
? (for example a label without content)
variable == "undefined"
variable === "undefined"
variable == undefined
variable === undefined
I am creating a mini game where the user tries to guess a name. But when I want to compare two text strings to see if they are the same it doesn't seem to work.
final String miNombre = "Jordi";
Scanner input = new Scanner(System.in);
System.out.println("Adivina mi nombre: ");
while (true) {
String intento = input.next();
if(intento == miNombre) {
System.out.println("Acertaste!");
break;
} else {
System.out.println("Intentalo de nuevo!");
}
}
EXIT:
Adivina mi nombre:
manuel
Intentalo de nuevo!
jordi
Intentalo de nuevo!
Jordi
Intentalo de nuevo!