我试图通过获取特定间隔的开始、结束间隔范围来打印特定间隔之间的数字,但我无法获得正确的输出。
我正在使用 Scanner 类来获取用户的输入。
我使用了start1、start2和end1、end2 2个间隔来显示它们的开始和结束范围。
import java.util.Scanner;
public class Smallest234Number
{
public static void smallest2NoInterval(int p[],int x[])
{
System.out.println("First interval");
for(int k=0;k<p.length;k++)
{
System.out.println(p[k++]);
}
System.out.println("Second Interval");
for(int k=0;k<x.length;k++)
{
System.out.println(x[k++]);
}
}
public static void main(String[] args)
{
int ar1[]=new int[10];
int ar2[]=new int[10];
int i=0;
int s=0;
// i have taken 2 intervals for a base
System.out.println("Enter the first Interval");
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first of starting interval");
int startno1=sc.nextInt();
//now take input from user startno
System.out.println("Enter the end of starting interval");
int endno1=sc.nextInt();
//now take input from user endno
System.out.println("Enter the second interval");
System.out.println("Enter the first of Second interval");
int startno2=sc.nextInt();
//now take input of 2Interval from user startno1
System.out.println("Enter the end of Second interval");
int endno2=sc.nextInt();
//now take input of 2Interval from user endno1
System.out.println("Enter the first interval nos only between start no and end no");
System.out.println("Enter the first interval nos only between start no and end no");
for(int a=startno1;a<=endno1;a++)
{
int inputNo=sc.nextInt();
if(inputNo<=endno1&&inputNo>=startno1)
{
ar1[s]=inputNo;
s++;
}
}
System.out.println("Enter the Second interval nos only between start no1 and end no1");
for(int a=startno2;a<=endno2;a++)
{
int inputNo=sc.nextInt();
if(inputNo<=endno1&&inputNo>=startno1)
{
ar2[i]=inputNo;
i++;
}
}
smallest2NoInterval(ar1,ar2);
}
}
**Output Shown:**
Enter the first Interval
Enter the first of starting interval
1
Enter the end of starting interval
3
Enter the second interval
Enter the first of Second interval
2
Enter the end of Second interval
4
Enter the first interval nos only between start no and end no
Enter the first interval nos only between start no and end no
1
2
3
Enter the Second interval nos only between start no1 and end no1
2
3
4
First interval
1
3
0
0
0
Second interval
2
0
0
0
0
最佳答案
您使用相同的变量i
在数组ar1
和ar2
中进行索引,这就是为什么您的程序将整数放在前两个位置ar1
和 ar2
中排名第三。您应在将值放入 ar2
之前使用不同的索引变量或重置 i=0
。
编辑 另一个问题在于您的打印逻辑
for(int k=0;k<p.length;k++)
{
System.out.println(p[k++]);
}
System.out.println("Second Interval");
for(int k=0;k<x.length;k++)
{
System.out.println(x[k++]);
}
您在循环中递增索引变量两次,请按如下方式更正:
for(int k=0;k<p.length;k++)
{
System.out.println(p[k]);
}
System.out.println("Second Interval");
for(int k=0;k<x.length;k++)
{
System.out.println(x[k]);
}
关于java - 为什么我在打印特定间隔的数字时得到此输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30636724/