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

今天在做一个用三元运算符判断奇偶的小练习时遇到“the operation % is undefined for the argument type string,int”错误的小插曲

开始的程序是这样写的

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)?"偶数":"奇数"; 可以正常运行编译

自己写的正常运行的代码:

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);
}
}

后来看了看书本上给出的参考答案:

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(长整型)从获取用户输入数据上就已经控制了整数输入。貌似会更方便点。

路还长,继续学习。

你可能感兴趣的:(Google,undefined,import,public,operation)