英文:
What does this particular line in java using indexOf mean?
问题
numbers[index] = Double.parseDouble(value.replace("h", ""));
这行代码的含义是:将输入的值去除首尾的字符 "h",然后将剩余部分解析为一个双精度浮点数,并将其赋值给数组中指定索引位置的元素。
简单易懂的解释:
value
是从用户输入中获取的字符串。value.replace("h", "")
是将字符串中的所有 "h" 替换为空字符串,这样就去除了首尾可能存在的 "h"。Double.parseDouble(...)
将经过处理的字符串转换为双精度浮点数。numbers[index]
是一个数组,用于存储浮点数值。index
是一个计数器,表示当前存储位置的索引。- 所以,这行代码的作用是将经过处理的浮点数值存储到数组中的指定位置。
例如,如果用户输入了 "3.5h",经过处理后 "h" 被去除,剩下 "3.5" 被转换成浮点数,然后这个浮点数会被存储在 numbers
数组的特定位置,由 index
变量指示。
英文:
My Code:
// Import scanner class
import java.util.Scanner;
// Create class and method
class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.println("Press any key to start");
String key = inp.nextLine();
System.out.println("\nEnter the amount of each item");
System.out.println("Upto 5 inputs are allowed!\n");
int counter = 0;
int index = 0;
double[] numbers = new double[5];
boolean go = true;
while(go) {
String value = inp.nextLine();
int indexOfH = value.indexOf("h");
boolean containsH = indexOfH == 0 || indexOfH == (value.length()-1);
if(containsH){ //Validate h at beginning or end
numbers[index] = Double.parseDouble(value.replace("h", ""));
System.out.println("HST will be taken account for this value");
}
counter++;
if (counter == 5){
go = false;
}
}
System.out.println("Printing Valid values");
for(int i=0; i< numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
What does this line in my code mean?: `numbers[index] = Double.parseDouble(value.replace("h", ""));
I am new to java arrays, so can you explain it in a simple and easy way?
`
答案1
得分: 2
int indexOfH = value.indexOf("h");
boolean containsH = indexOfH == 0 || indexOfH == (value.length()-1);
`indexOfH` 是字符串中找到 `"h"` 的字符位置。
更清楚的表达可以是:
int indexOfH = value.indexOf("h");
boolean containsH = value.startsWith("h") || value.endsWith("h");
显然,`h` 是一个标记。
通过以下方式从 `value` 中去除标记:
String numValue = value.replace("h", "");
然后可以将其转换为双精度浮点数:
numbers[index] = Double.parseDouble(numValue);
(因此,`value` 可能包含 `"3.14h"` 或 `"h2.89"`。)
另一个注意:`value.indexOf('h')` 更加合乎逻辑,因为现在是在查找单个字符的位置,而不是整个字符串。
英文:
int indexOfH = value.indexOf("h");
boolean containsH = indexOfH == 0 || indexOfH == (value.length()-1);
indexOfH
is the char position in the string where "h"
is found.
More clear would have been:
int indexOfH = value.indexOf("h");
boolean containsH = value.startsWith("h") || value.endsWith("h");
Evidently "h" was a marker.
The value
is stripped by
String numValue = value.replace("h", "");
And can then be converted to a double:
numbers[index] = Double.parseDouble(numValue);
(So value
might have contained "3.14h"
or "h2.89"
.)
An other note: value.indexOf('h')
would have been more logical, as now the position of a char instead of an entire String is sought.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论