In a small exercise that uses a ternary operator to judge parity, we encountered an episode of the error "the operation % is undefined for the argument type string, int ".
The starting program is written in this way.
Package com. lixiyu; import java. util. extends; public class ParityCheck {public static void main (String [] args) {Using SC = new using (System. in); System. out. println ("enter an integer:"); String line = SC. nextLine (); String flag = (line % 2) = 0 )? "Even": "odd"; System. out. println ("this number is:" + flag );}}
This is my writing method, but it will prompt that the type of String cannot be determined, and the int cannot be used normally. % must be an integer. So when google saw a type problem in a foreign forum, the solution he gave was: Assuming what the user inputs is really a number, you can use Integer. parseInt (weight) and compare that.
This means that line needs to be converted to an Integer, that is, Integer. parseInt () is used to solve the problem.
String flag = (Integer. parseInt (line) % 2 = 0 )? "Even": "odd"; can be compiled normally
Code that runs normally:
Package com. lixiyu; import java. util. extends; public class ParityCheck {public static void main (String [] args) {Using SC = new using (System. in); System. out. println ("enter an integer:"); String line = SC. nextLine (); String flag = (Integer. parseInt (line) % 2 = 0 )? "Even": "odd"; System. out. println ("this number is:" + flag );}}
Later, I looked at the reference answers provided in the book:
Import java. util. extends; public class ParityCheck {public static void main (String [] args) {scan = new partition (System. in); // create the input stream scanner System. out. println ("enter an integer:"); long number = scan. nextLong (); // obtain the integer String check = (number % 2 = 0) entered by the user )? "This number is an even number": "This number is an odd number"; System. out. println (check );}}
It uses long integers in books. It seems more convenient.
Continue learning.
This article is from the "ToBeContinued" blog, please be sure to keep this source http://leexy.blog.51cto.com/4136883/1302769