for loop jumping an input in java [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
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];
}
}
}
}
}

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.

Related

Can't enter all of the strings I want into the string array [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed last year.
So, I know this is probably a really stupid question, I am a beginner trying to learn Java basics and I have a problem with string array that I can't quite figure out. When I try to enter words into string array and the number of words is set by user (for example 5) I always can enter one less word (for example 4 instead of 5). My code is down below.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of words");
int n = scan.nextInt();
String arr[] = new String[n];
System.out.println("Please enter the words");
for (int i = 0; i < arr.length; i++) {
arr[i] = scan.nextLine();
}
for (int i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}
}
It is because when you use nextInt(), it is not reading the newline character. You can avoid this using 2 approaches.
Use nextLine i.e. use Integer.parseInt(scanner.nextLine()) instead of nextInt().
int n = Integer.parseInt(scan.nextLine());
String arr[] = new String[n];
Call nextLine before for loop so that the redundant newline is consumed before your for loop.
int n = scan.nextInt();
String arr[] = new String[n];
scan.nextLine();
System.out.println("Please enter the words");

I'm trying to create an array with a certain number of elements, but when use a variable it doesnt work [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
Here I put a 4 value in the variable length. I'm supposed to get an array with 4 elements, but I can only input 3 elements.
public static void main(String[] args) {
int length;
Scanner input = new Scanner(System.in);
System.out.print("Length: ");
length = input.nextInt();
String[] my_friend_names = new String[length];
for (int i = 0; i < length; i++) {
my_friend_names[i] = input.nextLine();
}
for (int i = 0; i < length; i++) {
System.out.println("Name: " + my_friend_names[i]);
}
}
OUTPUT:
Length: 4
1
2
3
Name:
Name: 1
Name: 2
Name: 3
Now if I change the length variable for a number 4, it works!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] my_friend_names = new String[4];
for (int i = 0; i < 4; i++) {
my_friend_names[i] = input.nextLine();
}
for (int i = 0; i < 4; i++) {
System.out.println("Name: " + my_friend_names[i]);
}
}
OUTPUT:
1
2
3
4
Name: 1
Name: 2
Name: 3
Name: 4
Do you know why that is?
This is because of incorrect use of the scanner api.
In the first example, when you used input.nextInt(); it only read the integer part of that line, the new line char is still not used by the scanner.
Later when you call scanner.nextLine() it returns the chars after 4 which was your input and the new line which is an empty string.
This question has been answered before
Scanner is skipping nextLine() after using next() or nextFoo()?
Can't use Scanner.nextInt() and Scanner.nextLine() together
Java arrays are fixed. Try using a List instead.

For loop: populate array from user input [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I was setting up a small app that asks a user to determine the array size and then populate it. The used "for" loop skips the index 0; but I'm uncertain why.
If you run this code with 1 as the array size it skips over the user inputting the first word.
The issue is certainly on the for-loop but it is so simple that I don't see it.
Thanks!
import java.util.Scanner;
public class WordRandomizerAdvanced {
public static void main(String[] args) {
int arrayDimesion;
Scanner sc = new Scanner(System.in);
System.out.println("****************************************************");
System.out.println("******** Welcome to Word Randomizer ADVANCED********");
System.out.println("****************************************************");
//Get array size
System.out.println("How many words would you like to enter?");
arrayDimesion = sc.nextInt();
String[] wordArray = new String[arrayDimesion];
//Populate with user input
for (int i=0; i<arrayDimesion; i++) {
System.out.println("Please enter a word");
wordArray[i] = sc.nextLine();
}
//Print all entered Strings
System.out.println("This are the words you entered: ");
for(int i = 0; i < wordArray.length; i++) {
System.out.println(wordArray[i]);
}
//Print random string from array
int r = (int)(Math.random() * wordArray.length);
System.out.println("The random word is: " + wordArray[r]);
}
}
Change your
arrayDimesion = sc.nextInt();
to
arrayDimesion = Integer.parseInt(sc.nextLine());
Reason: sc.nextInt() doesn't consume the newline character that you give after taking arrayDimesion input. This later on gets consumed in the next sc.nextLine() call.
PS: It might throw NumberFormatException. So you can handle it like :
try {
arrayDimesion = Integer.parseInt(sc.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
The below code is clean, easy to read and handles the edge cases.
import java.util.Scanner;
public class WordRandomizerAdvanced {
public static void main(String[] args) {
int numOfWords;
Scanner scanner = new Scanner(System.in);
System.out.println("****************************************************");
System.out.println("******** Welcome to Word Randomizer ADVANCED********");
System.out.println("****************************************************");
//Get array size
System.out.println("How many words would you like to enter?");
numOfWords = Integer.parseInt(scanner.nextLine());
String[] wordArray = new String[numOfWords];
//Populate with user input
System.out.println("Please enter the word(s)");
for (int i = 0; i < numOfWords; i++) {
wordArray[i] = scanner.nextLine();
}
//Print all entered Strings
System.out.println("These are the words you entered: ");
for (int i = 0; i < numOfWords; i++) {
System.out.println(wordArray[i]);
}
//Print random string from array
if (numOfWords == 0) {
System.out.println("You didn't enter a word");
} else {
int r = (int) (Math.random() * numOfWords);
System.out.println("The random word is: " + wordArray[r]);
}
}
}

How do i use a for loop to do this output? [duplicate]

This question already has answers here:
Make a upside down triangle in java
(3 answers)
Closed 4 years ago.
I'm a beginner in java and I need help with this code. I have to let the user enter a word and the output as follows,(I used Canada as an example)
Canada
anada
nada
ada
da
a
However, I'm not sure what to do. This is what I have so far
import java.util.*;
public class javapdf2413_17 {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter in a single word");
String wordEntered = in.next();
for (int i = wordEntered.length(); i>=0; i--) {
System.out.println(wordEntered.substring (0, i));
}
}
}
This should do it
for (int i = 0; i < wordEntered.length(); i++) {
System.out.println(wordEntered.substring(i));
}
The above substring method takes the beginning index of the string and returns a substring from that index (inclusive) till the end of the string.
You're close. String.substring(1) will return everything from the second character to the end. And I would use that in a loop with test against the empty string. Like,
while (!wordEntered.isEmpty()) {
System.out.println(wordEntered);
wordEntered = wordEntered.substring(1);
}

How to give user input for array of arraylist? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 6 years ago.
I would like to use input an array of arraylist, where the first input is the number of arrays of arraylist and the next line represents the input for each array. Please let me know where am going wrong. Please find below the code for the same:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
ArrayList[] al = new ArrayList[a];
for( int i =0; i<a; i++){
while(input.hasNextLine())
{
al[i].add(input.nextInt());
}
}
System.out.print("result is"+al[0]);
}
Try this out.
for( int i =0; i<a; i++){
ArrayList<int> temp = new ArrayList<int>();
while(input.hasNextLine())
{
temp.add(input.nextInt());
}
al[i] = temp;
}

Categories