如何使用Scanner在Main中输入两个数字,并使其与方法(升序java)一起工作



我正在尝试制作这个程序,它将在两个输入数字之间按升序打印数字。我把它作为一个方法来工作,我可以在Main中调用这个方法,但我真正想做的是在Main中输入两个数字,而不是在方法中。

这样的东西:

System.out.println("按升序排列的两个数字"(;

(在控制台中输入两个数字(

然后,调用将在所选Main数字之间按升序打印的方法。

我是新手,我试过好几件事,但似乎不知道该怎么办。希望你能帮我。

这就是代码现在的样子。

import java.util.Scanner;
public class AscendingOrder {
public static void main(String[] args) {
// calling method
int ascending1 = ascending();
}
public static int ascending() {
int min;
int max;
int total = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
min = sc.nextInt();
max = sc.nextInt();
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}

将两个输入作为参数传递给您的方法,类似于:

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
int min = sc.nextInt();
int max = sc.nextInt();
int ascending1 = ascending(min, max);
System.out.println(ascending1);
}

现在:

public static int ascending(int min, int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}

请注意,现在ascending()的定义包含两个类型为int参数。这些值是从主方法传递到方法的。

您可以在main方法中输入数字,然后将其传递给另一种方法:

public class AscendingOrder {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
int min = sc.nextInt();
int max = sc.nextInt();
int ascending1 = ascending(min, max);
}
public static int ascending(int min, int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}

您可以读取命令行参数,或者将扫描程序放在主函数中,并将参数

import java.util.Scanner;
public class AscendingOrder {
public static void main(String[] args) {
System.out.println("Entered first number is: "+args[0]);  
System.out.println("Entered Secomd number is: "+args[1]);  
int ascending1 = ascending(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}
public static int ascending(int min,int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}

您可以在main方法中获取数字,并在main方法本身中对其进行排序。Java 8使流处理变得如此简单。

public static void main( String[] args ) throws Exception {
Framework.startup( );
Scanner sc = new Scanner( System.in );
System.out.println( "Two numbers in ascending order" );
int num1= sc.nextInt( );
int num2= sc.nextInt( );
Arrays.asList( num1, num2).stream( ).sorted( ).forEach( System.out::println );
}

最新更新