輸入一個(gè)字符串,如何比較是否和數(shù)組中的某個(gè)字符串相等?
String[] books={"高數(shù)","論語(yǔ)"};//創(chuàng)建了一個(gè)數(shù)組保存字符串;
Scanner input=new Scanner(System.in);
String stringc=input.next();//定義字符串類型的輸入
//通過(guò)遍歷比較
for(i=0;i<books.length;i++){ ? ? ? ? ? ? ? ? ? ? ??
if(stringc==books[i]){
System.out.println("book:"+stringc);
exsit=1;
}
}
if(exsit==0){
System.out.println("圖書(shū)不存在!");
}
這里的比較myeclipce里沒(méi)辦法用.equals ? 可以這么用么,但是實(shí)際跑起來(lái)的時(shí)候輸入高數(shù)或者論語(yǔ)都提示圖書(shū)不存在
2016-01-19
我擦,代碼里面錯(cuò)誤不少啊
2015-12-18
謝謝大家= =,這個(gè)是完整代碼:某一次的作業(yè),租書(shū)界面
package library;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Arrays;
public class Borrow {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] books={"高數(shù)","論語(yǔ)"};
//Borrow borrow=new Borrow();
Arrays.toString(books);
boolean flag=true;
while(flag){
try{
System.out.println("輸入命令:1-按照書(shū)名查找圖書(shū);2-按照序號(hào)查找圖書(shū)");
Scanner input=new Scanner(System.in);
int numc=input.nextInt();
//String stringc=input.next();
if(numc==1){
System.out.println("輸入圖書(shū)名稱:\n");
int exsit=0;
int i=0;
String stringc=input.next();
for(i=0;i<books.length;i++){
if(stringc.equals(books[i])){
System.out.println("book:"+stringc);
exsit=1;
}
}
if(exsit==0){
System.out.println("圖書(shū)不存在!");
}
}else if(numc==2){
System.out.println("輸入圖書(shū)序號(hào):\n");
int xuhao=input.nextInt();
if(xuhao>0&&xuhao<3){
System.out.println("book:"+books[xuhao-1]);
}else{
System.out.println("命令輸入錯(cuò)誤!請(qǐng)根據(jù)提示輸入數(shù)字命令");
}
}
}catch(InputMismatchException e){
System.out.println("命令輸入錯(cuò)誤!請(qǐng)根據(jù)提示輸入數(shù)字命令");
}
}
}
}
2015-12-18
臥槽。。這Myeclips簡(jiǎn)直有毒。。。我昨天跑了無(wú)數(shù)遍的equal都提示無(wú)法創(chuàng)建
2015-12-18
當(dāng)然會(huì)不存在啦,==判斷的是內(nèi)存地址是否一樣,equals才是比較字符串的內(nèi)容是否相同,myeclipce應(yīng)該是可以用equals的啊,是不是寫(xiě)的位置不對(duì)
2015-12-18
只能用equals? 你這里用的==比的是地址 達(dá)不到你要的效果? 應(yīng)該是別的地方有問(wèn)題
2015-12-18
當(dāng)然可以用equals,而且必須用equals,你把myeclipse不給你用的提示發(fā)出來(lái),是不是()沒(méi)有對(duì)應(yīng)