Reputation: 1501
I have a fraction of code which is working. This is basically a scanner input so that it can save String with space. This is my code:
public class TestScannerString {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter strings: ");
String[] a = sc.nextLine().split(" ");
String name = "";
for (String a0 : a) {
name += a0 + " ";
}
System.out.println(name);
}
}
This is the output of that code:
Then i try to implement this code into mini-project. This is the block that contain previous code:
for (int i=0; i<jumlahData; i++) {
System.out.println("Masukkan Data Bayi ke " +(i+1));
System.out.println("Nama : ");
String[] a = sc.nextLine().split(" ");
String name = "";
for (String a0 : a) {
name += a0 + " ";
}
bayi[i].nama = name;
sc.nextLine();
System.out.print("Usia dalam Bulan : ");
bayi[i].usiaDalamBulan = sc.nextInt();
System.out.print("Berat (kg) : ");
bayi[i].beratDalamKg = sc.nextFloat();
System.out.print("Panjang (cm) : ");
bayi[i].panjangDalamCm = sc.nextInt();
System.out.println("Name :" +name);
System.out.println();
System.out.println("Nama bayi ke " + (i+1) + ": " +bayi[i].nama);
}
After i input "example of name" and print the name, it returns empty string like this:
Any suggestion why this happens and what should i do? Any help would be appreciated. Thanks before.
Upvotes: 0
Views: 1144
Reputation: 1501
Okay so the fix is by putting nextLine() in the beginning of loop before the scanner input. I think it is because of previous input that has newLine in it. So the final code is like this:
for (int i=0; i<jumlahData; i++) {
sc.nextLine();
System.out.println("Masukkan Data Bayi ke " +(i+1));
System.out.print("Nama : ");
String nameTest = sc.nextLine();
bayi[i].nama = nameTest;
System.out.print("Usia dalam Bulan : ");
bayi[i].usiaDalamBulan = sc.nextInt();
System.out.print("Berat (kg) : ");
bayi[i].beratDalamKg = sc.nextFloat();
System.out.print("Panjang (cm) : ");
bayi[i].panjangDalamCm = sc.nextInt();
System.out.println();
}
Upvotes: 1
Reputation: 964
I don't have the complete code to test this but it seems like you have two lines of code for taking a line of string as an input.
String[] a = sc.nextLine().split(" ");
and
sc.nextLine();
My guess is you are actually entering the name for the second one, which doesn't save the input to any reference. For the former line of code you probably are mistakenly responding with an empty string.
Upvotes: 0