如何解决提示the operation % is undefined for the argument type string,int的错误
今天在做一個用三元運算符判斷奇偶的小練習時遇到“the operation % is undefined for the argument type string,int”錯誤的小插曲
開始的程序是這樣寫的
| 1 2 3 4 5 6 7 8 9 10 11 | package?com.lixiyu; import?java.util.Scanner; public?class?ParityCheck { public?static?void?main(String[] args){ ????Scanner sc=new?Scanner(System.in); ????System.out.println("請輸入一個整數:"); ????String line=sc.nextLine(); ???String flag=((line%2)==0)?"偶數":"奇數"; ????System.out.println("這個數字是:"+flag); } } |
這是我的寫法,但它會提示無法確定類型String,int無法正常使用%的問題,要用%得是整型嘛。所以后來google看到國外論壇有遇到類型問題,他給的解決方法是:Assuming what the user inputs is really a number, you can use Integer.parseInt(weight) and compare that.
意思也就是要讓line轉換為整型的數,即用到Integer.parseInt()即可解決故改一下下面為
String flag=(Integer.parseInt(line)%2==0)?"偶數":"奇數"; 可以正常運行編譯
自己寫的正常運行的代碼:
| 1 2 3 4 5 6 7 8 9 10 11 | package?com.lixiyu; import?java.util.Scanner; public?class?ParityCheck { public?static?void?main(String[] args){ ????Scanner sc=new?Scanner(System.in); ????System.out.println("請輸入一個整數:"); ????String line=sc.nextLine(); ???String flag=(Integer.parseInt(line)%2==0)?"偶數":"奇數"; ????System.out.println("這個數字是:"+flag); } } |
后來看了看書本上給出的參考答案:
| 1 2 3 4 5 6 7 8 9 10 | import?java.util.Scanner; public?class?ParityCheck { ????public?static?void?main(String[] args) { ????????Scanner scan =?new?Scanner(System.in);// 創建輸入流掃描器 ????????System.out.println("請輸入一個整數:"); ????????long?number = scan.nextLong();// 獲取用戶輸入的整數 ????????String check = (number %?2?==?0) ??"這個數字是:偶數"?:?"這個數字是:奇數"; ????????System.out.println(check); ????} } |
它書本上面用到的是long(長整型)從獲取用戶輸入數據上就已經控制了整數輸入。貌似會更方便點。
路還長,繼續學習。
本文轉自lixiyu 51CTO博客,原文鏈接:http://blog.51cto.com/lixiyu/1302769,如需轉載請自行聯系原作者
總結
以上是生活随笔為你收集整理的如何解决提示the operation % is undefined for the argument type string,int的错误的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [arm 驱动]Linux输入子系统分析
- 下一篇: tomcat日志切割-logrotate