Lorsque j'utilise Scanner en Java seconde fois, l'objet Scanner sc2 n'est pas converti en nombre entier dans cette chaîne "int typeOfSort = sc2.nextInt();
". Eclipse ne montre pas d'erreur avant de démarrer le programme, mais après le démarrage, affiche cette erreur. Le programme peut s'exécuter mais quand vient la chaîne où sc2 doit convertir en int, erreur de programmation. Comment le réparer?Java Scanner ne fonctionne pas lorsque je l'utilise une seconde fois
"
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Buble.main(Buble.java:39)
"
du code Java
import java.util.Scanner;
public class Buble {
public static void main(String[] args) {
int size; // size of Array
int array[]; // Array
System.out.print("Enter size of arrays: ");
// Scanner is tool for input text to console
Scanner sc = new Scanner(System.in);
size = sc.nextInt();
array = new int [size];
sc.close();
for(int i = 0; i < array.length; i++){
double randnum = Math.floor(Math.random() * 1000);
array[i] = (int) randnum;
System.out.println("Element " + i + " = " + (int) randnum);
}
for(int b = 0; b < array.length; b++){
for(int i = 1; i < array.length; i++) {
if(array[i] < array[i-1]){
int a = array[i];
array[i] = array[i-1];
array[i-1] = a;
}
}
}
System.out.println("If you want to sort from smallest to largest
press 1 or 2 if Conversely: ");
Scanner sc2 = new Scanner(System.in);
int typeOfSort = sc2.nextInt(); // String with error
sc2.close();
if(typeOfSort == 1){
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
}
else{
for(int i = array.length; i < array.length; i++){
System.out.println(array[i]);
}
}
}
}