日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

如何解决提示the operation % is undefined for the argument type string,int的错误

發布時間:2025/3/18 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何解决提示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的错误的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。