import java.util.Scanner;
import java.util.Arrays;
public class CarCareChoice{
public static void main(String[] args) {
String[] choices=new String[5];
int j ;
boolean validItem=false;
double price=0.0;
int p;
String str;
//When i'm entering services I'm getting 5.o for all services plz help
String[] services={"Am","Bm","Cm","Dm","Em"};
double prices[]={1.0,2.0,3.0,4.0,5.0};
//Scanner
Scanner input = new Scanner(System.in);
System.out.println("enter");
str= input.nextLine();
for(j = 0; j < choices.length;j++){
if(Arrays.asList(services).contains(str)){
validItem=true;
price=prices[j];
}
}
if (validItem)
System.out.println("service"+""+price);
else
System.out.println("Invalis enter");
}
}
输出
enter
Am
service5.0
输出
enter
Bm
service5.0
当我进入Am时我应该得到1.0“Bm 2.0等等但我只得到5.0
答案 0 :(得分:0)
您宁愿改进代码,如下所示:
System.out.println("enter");
List<String> choiceList = Arrays.asList(services);
str= input.nextLine();
int index = choiceList.indexOf(str);
if ( index!=-1 )
{
price = prices[i];
validItem = true;
}
if (validItem)
System.out.println("service"+""+price);
else
System.out.println("Invalis enter");
你不需要在for循环中执行此操作。因为当您将数组转换为列表时,只需找到索引。如果是-1,则它绝对不是有效项,否则返回该数组索引处的价格。 ArrayList在内部由数组支持。
答案 1 :(得分:0)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="widget" class="widget">
<h1>THE IMAGE</h1>
</div>
<input type="hidden" name="img_val" id="img_val" value="" />
<div id="showImage">
<img id="captured_img" src="" height="120" width="100" />
</div>
<input type="button" id="btnSave" value="Save PNG" />
如果可能,请使用import java.util.Arrays;
class Main {
public static final int INVALID_INDEX = -1;
public static void main(String[] args) {
String[] services={"Am","Bm","Cm","Dm","Em"};
double prices[]={1.0,2.0,3.0,4.0,5.0};
String input = "Em";
int index = Arrays.asList(services).indexOf(input);
System.out.println((index!=INVALID_INDEX)? prices[index]+"":"invalid input");
}
}
。