輸入一個字符串,如何比較是否和數組中的某個字符串相等?
String[] books={"高數","論語"};//創建了一個數組保存字符串;
Scanner input=new Scanner(System.in);
String stringc=input.next();//定義字符串類型的輸入
//通過遍歷比較
for(i=0;i<books.length;i++){ ? ? ? ? ? ? ? ? ? ? ??
if(stringc==books[i]){
System.out.println("book:"+stringc);
exsit=1;
}
}
if(exsit==0){
System.out.println("圖書不存在!");
}
這里的比較myeclipce里沒辦法用.equals ? 可以這么用么,但是實際跑起來的時候輸入高數或者論語都提示圖書不存在
2016-01-19
我擦,代碼里面錯誤不少啊
2015-12-18
謝謝大家= =,這個是完整代碼:某一次的作業,租書界面
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={"高數","論語"};
//Borrow borrow=new Borrow();
Arrays.toString(books);
boolean flag=true;
while(flag){
try{
System.out.println("輸入命令:1-按照書名查找圖書;2-按照序號查找圖書");
Scanner input=new Scanner(System.in);
int numc=input.nextInt();
//String stringc=input.next();
if(numc==1){
System.out.println("輸入圖書名稱:\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("圖書不存在!");
}
}else if(numc==2){
System.out.println("輸入圖書序號:\n");
int xuhao=input.nextInt();
if(xuhao>0&&xuhao<3){
System.out.println("book:"+books[xuhao-1]);
}else{
System.out.println("命令輸入錯誤!請根據提示輸入數字命令");
}
}
}catch(InputMismatchException e){
System.out.println("命令輸入錯誤!請根據提示輸入數字命令");
}
}
}
}
2015-12-18
臥槽。。這Myeclips簡直有毒。。。我昨天跑了無數遍的equal都提示無法創建
2015-12-18
當然會不存在啦,==判斷的是內存地址是否一樣,equals才是比較字符串的內容是否相同,myeclipce應該是可以用equals的啊,是不是寫的位置不對
2015-12-18
只能用equals? 你這里用的==比的是地址 達不到你要的效果? 應該是別的地方有問題
2015-12-18
當然可以用equals,而且必須用equals,你把myeclipse不給你用的提示發出來,是不是()沒有對應