I am trying to implement the Dutch flag problem in Java. I wrote the following code for that:
import java.util.*;
public class DutchFlag{
static void swap(int a,int b)
{
int t;
t = a;
a = b;
b = t;
}
public static void main(String []args){
int n;
Scanner sc;
System.out.print("Enter the number of elements:");
sc = new Scanner(System.in);
n = sc.nextInt();
int arr[] = new int[n];
System.out.print("Now enter array elements.");
for(int i=0;i<n;i++)
{
System.out.print("Enter:");
sc = new Scanner(System.in);
arr[i] = sc.nextInt();
}
int l = 0, m = 0;
int h = n-1;
while(m <= h)
{
if(arr[m]==2)
{
swap(arr[m],arr[h]);
}
else if(arr[m]==0)
{
swap(arr[m],arr[l]);
l++;
m++;
}
else
{
m++;
}
}
for(int i=0;i<n;i++)
{
System.out.print(arr[i]);
}
}
}
I ran this code firstly on an online compiler, which gave the following exception:
Enter the number of elements:Now enter array elements.Enter:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at DutchFlag.main(DutchFlag.java:23)
Then I ran the same code by writing it on a text editor on my computer, and then compiling it on the command prompt. The code compiled fine, but nothing happens after it takes the input for n
.
After this, I tried using NetBeans to run this program. There, it works till taking the input for array, but after that nothing happens.
Neither am I able to understand the errors occuring in each of the platform, nor the reason why it is behaving differently for each of them is apparent to me. Can someone please point out the mistake that I am making?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…