package 实习2;import java.util.Scanner;public class No5m {
public int x,y,z;
public No5m() {
Scanner r = new Scanner(System.in);
System.out.println("输入整数值x:");
x = r.nextInt();
System.out.println("输入整数值y:");
y = r.nextInt();
System.out.println("输入整数值z:");
z = r.nextInt();
a sss = new a();
sss.a(x, y);
sss.a(x, z);
sss.a(y, z);
System.out.println(x + " " + y + " " + z);
}
public static void main(String args[]) {
No5m k = new No5m();}
}
class a {
public void a(int x, int y) {// 比较两个数x,y如果x>y则交换
int temp;
if (x > y) {
temp = x;
x = y;
y = temp;
}
}
}
问:为什么调用后不能在主方法上产生改变?怎么才可以?(我要的是一种方法.这只是一个例子~)
谢谢大家~
public int x,y,z;
public No5m() {
Scanner r = new Scanner(System.in);
System.out.println("输入整数值x:");
x = r.nextInt();
System.out.println("输入整数值y:");
y = r.nextInt();
System.out.println("输入整数值z:");
z = r.nextInt();
a sss = new a();
sss.a(x, y);
sss.a(x, z);
sss.a(y, z);
System.out.println(x + " " + y + " " + z);
}
public static void main(String args[]) {
No5m k = new No5m();}
}
class a {
public void a(int x, int y) {// 比较两个数x,y如果x>y则交换
int temp;
if (x > y) {
temp = x;
x = y;
y = temp;
}
}
}
问:为什么调用后不能在主方法上产生改变?怎么才可以?(我要的是一种方法.这只是一个例子~)
谢谢大家~
方法内部对改变参数的值,对方法外的变量不造成影响。
具体说明请参看
http://topic.csdn.net/u/20110608/09/cee50280-9cba-4803-b6c0-243aed7d5024.html
http://topic.csdn.net/u/20110605/21/d21c1b76-ba2b-49fa-89eb-1aea3dce1c8f.html
public void a(No5m n, int mode) {
int temp;
if (mode == 1) {
if (n.x<n.z) {
temp = n.x;
n.x = n.z;
n.z = temp;
}
} else if (mode == 2) {
if (n.y<n.z) {
temp = n.y;
n.y = n.z;
n.z = temp
}
} else {
if (n.x<n.y) {
temp = n.x;
n.x = n.y;
n.y = temp;
}
}
}调用
sss.a(this, 0);
sss.a(this, 1);
sss.a(this, 2);
int是基础类型
能把我的例子改一下帮帮忙.我想看看实际例子比较容易懂.我学的时候大多数都是看例子的
import java.util.Scanner;public class TestDemo01 {
public static void main(String[] args) {
No5m k = new No5m();
}
}
class No5m{
public int[]x = new int[3];
public No5m(){
Scanner in = new Scanner(System.in);
System.out.println("请输入X的值:");
x[0] = in.nextInt();
System.out.println("请输入Y的值:");
x[1] = in.nextInt();
System.out.println("请输入Z的值:");
x[2] = in.nextInt();
a ss = new a();
ss.as(x);
for(int a:x){
System.out.println(a);
}
}
}
class a{
public void as(int[] x){
int temp;
for(int i=0;i<x.length-1;i++){
for(int j=i+1;j<x.length;j++){
if(x[i]>x[j]){
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
}
}
public static void main(String[] args) {
No5m k = new No5m();
}
}
class Mon5{
public Integer x,y,z;
public Mon5(){
Scanner in = new Scanner(System.in);
System.out.println("请输入X的值:");
x = in.nextInt();
System.out.println("请输入Y的值:");
y = in.nextInt();
System.out.println("请输入Z的值:");
z = in.nextInt();
s ss = new s();
ss.as(x,y);
ss.as(x, z);
ss.as(y, z);
System.out.println(x+" "+y+" "+z);
}
}
class s{
public void as(Integer x,Integer y){
int temp;
if(x>y){
temp = x;
x = y;
y = temp;
}
}
}