1

this is a program that given in input 5 names and 5 telephone numbers gives in output the names with their numbers in alphabetical order. the problem is that when I give in input the first name and the first number, then the program jumps to the second "telephone number input" without making me insert the second name. I hope this makes sense.

also I wouldn't mind any suggestion to make the sorting easier.

this is the code:

import java.util.Arrays;
import java.util.Scanner;

public class RubricaTelefonica {

public static void main(String[] args) {

    String names[] = new String[5];
    long phone_num[] = new long[5];
    Scanner sc = new Scanner(System.in);

    for(int i = 0; i < 5; i++) {
        System.out.println("Inserisci il nome:");
        names[i] = sc.nextLine();
        System.out.println("Inserisci il numero di telefono:");
        phone_num[i] = sc.nextLong();
    }
    sc.close();

    String names_unsorted[] = names;
    Arrays.sort(names);
    long sorted_num[] = new long[5];

    for(int a = 0; a < 5; a++) {
        //sorted cicle
        for(int b = 0; b < 5; b++) {
            //unsorted cicle
            if(names[a] == names_unsorted[b]) {
                sorted_num[a] = phone_num[b];
            }
        }
    }

}

}
Radiodef
  • 35,285
  • 14
  • 78
  • 114
BONANDRINI CARLO
  • 165
  • 1
  • 1
  • 7
  • If you have a different question, please ask a new question rather than editing this one. Also, see https://stackoverflow.com/questions/32806173/copying-arrays-the-right-way and https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java. – Radiodef May 31 '18 at 16:28

1 Answers1

0

You misinterpret nextLong(); it simply reads the long value and then the upcoming nextLine() is triggered by the new line entry from the console.

Put an sc.nextLine() after the nextLong() call, or even nicer is to read the phone number as String with nextLine() and then parse a long from it.

Adam Horvath
  • 1,132
  • 7
  • 25