Java将2个整数与equals或==进行比较? [英] Java Compare 2 integers with equals or ==?

查看:187
本文介绍了Java将2个整数与equals或==进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java非常新,我想知道如何比较2个整数?我知道==完成工作......但是等于什么?这可以比较2个整数吗? (当我说整数时,我的意思是int而非整数)。
我的代码是:

i am very very new to Java and i would like to know how can i compare 2 integers? I know == gets the job done.. but what about equals? Can this compare 2 integers? (when i say integers i mean "int" not "Integer"). My code is:

import java.lang.*;
import java.util.Scanner;
//i read 2 integers the first_int and second_int
//Code above
if(first_int.equals(second_int)){
//do smth
}
//Other Code

但由于某些原因这不起作用..我的意思是Netbeans给我一个错误:int不能被解除引用为什么?

but for some reason this does not work.. i mean the Netbeans gives me an error: "int cannot be dereferenced" Why?

推荐答案

int 是一个原始的。您可以使用包装器 整数 喜欢

int is a primitive. You can use the wrapper Integer like

Integer first_int = 1;
Integer second_int = 1;
if(first_int.equals(second_int)){ // <-- Integer is a wrapper.

或者您可以按值进行比较(因为它是基本类型),如

or you can compare by value (since it is a primitive type) like

int first_int = 1;
int second_int = 1;
if(first_int == second_int){ // <-- int is a primitive.

JLS-4.1。类型和值的种类表示(部分)


Java编程语言中有两种类型:primitive类型(§4.2)和引用类型(§4.3)。相应地,有两种数据值可以存储在变量中,作为参数传递,由方法返回,并在以下操作:原始值(§4.2)和参考值(§4.3)。

There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).

这篇关于Java将2个整数与equals或==进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆