'How can i add a input to the "valor2" ? - java
I just started to learn java, someone knows, how can i ask like "Type your values", and add id to the double[] valor2 ?
class test { // body start
public static void main(String [] args) {
double[] valor2 = {15, 4864, 4, 21}; // here is my doubt
for (int a=0; a<valor2.length; a++){
System.out.format("%s %d: O valor deste item é %10.2f %s%n", "Item", a+1, valor2[a], "reais");
}
}
}
Solution 1:[1]
Use a Scanner for inputs.
public class TypeYours {
public static void main(String[] args) {
// Double array to contain the values
double[] values = new double[4];
// The scanner take System.in (console input stream) as input.
Scanner scanner = new Scanner(System.in); /
for (int a = 0; a < values.length; a++) {
System.out.print("Enter a price:");
// Store the scanned value
values[a] = scanner.nextDouble();
// Some %s is unnecessary so I removed them.
// Also, not %n but \n to start a new Line
System.out.format("Item %d: O valor deste item é %10.2f reais\n", a + 1, values[a]);
}
}
}
Note that this is a very simple example: 1) The size of the double[] is hardcoded in the source as 4. If you want to dynamically change the values's size, use ArrayList<Double> or some other instead. 2) Scanner can take int, float, String as well, try them in your coed. 3) System.out.format can be replaced by the combination of System.out.print() and String.format(format, ...args), which is more flexible.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
