This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
This is a basic name sorting program. Everything works except for the fact that the user cannot input the first name. This is the code:
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to sort");
int num = sc.nextInt();
String[] names = new String[num];
for (int x = 0; x < names.length; x++){
int pos = x+1;
System.out.println("Enter name " + pos);
//String temp = sc.nextLine();
names[x] = sc.nextLine();
}
String sortedArray[] = sort(names);
for (int i = 0; i < sortedArray.length; i++){
System.out.print(sortedArray[i] + " ");
}
}
Update: I changed the code so if it is the first time, it calls sc.nextLine() and then sets the input equal to names[0]
One problem with .next() is that if a person's first name is 2 words to treats it as two names. This is the updated code that works:
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to sort");
int num = sc.nextInt();
String[] names = new String[num];
//String[] temp = new String[names.length];
for (int x = 0; x < names.length; x++) {
int pos = x + 1;
if (x == 0) {
System.out.println("Enter name 1");
sc.nextLine();
names[0] = sc.nextLine();
} else {
System.out.println("Enter name " + pos);
//String temp = sc.nextLine();
names[x] = sc.nextLine();
}
}
String sortedArray[] = sort(names);
for (int i = 0; i < sortedArray.length; i++) {
System.out.print(sortedArray[i] + " ");
}
}
Use sc.next(); instead of sc.nextLine();
next() will find and return the next complete token from the input stream.
nextLine() will advance the scanner past the current line and will return the input that was skipped
Also, check below description from Scanner#nextLine().
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to sort");
int num = sc.nextInt();
String[] names = new String[num];
for (int x = 0; x < names.length; x++){
int pos = x+1;
System.out.println("Enter name " + pos);
//String temp = sc.nextLine();
names[x] = sc.next();
}
/*String sortedArray[] = sort(names);
for (int i = 0; i < sortedArray.length; i++){
System.out.print(sortedArray[i] + " ");
}*/
Related
I am writing some pretty basic java code. The idea is to use a loop to write up to 20 numbers into an array. I want to exit the loop when there are no values left. Right now, my code will write to the array, but I cannot get it to exit the loop without entering a non-integer value. I have read some other posts, but they tend to use string methods, which would make my code kind of bulky. I feel like there is a simple solution to this, but I can't seem to figure it out....
import java.util.Scanner;
public class getArray{
public static void main (String[] args){
Scanner scnr = new Scanner(System.in);
int[]newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt()){
newArray[newArraySize] = scnr.nextInt();
newArraySize += 1;
continue;
}
for (int i = 0; i < newArraySize; i++){
System.out.println("The " + i + " input is " + newArray[i]);
}
}
}
And yet another alternative. Allows for single numerical entry or white-space delimited multiple numerical entry, for example:
--> 1
--> 2
--> 10 11 12 13 14 15 16
--> 20
--> 21
Enter nothing to end data entry and view array contents:
Scanner scnr = new Scanner(System.in);
List<Integer> valuesList = new ArrayList<>();
System.out.println("Enter all the Integer values you would like");
System.out.println("stored into your int[] array. You can enter");
System.out.println("them either singular or multiple values on a");
System.out.println("single line spaced apart with a single white");
System.out.println("space. To stop numerical entry and view your");
System.out.println("array contents just enter nothing.");
System.out.println("============================================");
System.out.println();
String inputLine = "";
while (inputLine.isEmpty()) {
System.out.print("Enter a numerical value: --> ");
inputLine = scnr.nextLine().trim();
// If nothing is supplied then end the 'data entry' loop.
if (inputLine.isEmpty()) {
break;
}
//Is it a string line with multiple numerical values?
if (inputLine.contains(" ") && inputLine.replace(" ", "").matches("\\d+")) {
String[] values = inputLine.split("\\s+");
for (String vals : values) {
valuesList.add(Integer.valueOf(vals));
}
}
//Is it a string line with a single numerical value?
else if (inputLine.matches("\\d+")) {
valuesList.add(Integer.valueOf(inputLine));
}
// If entry is none of the above...
else {
System.err.println("Invalid numerical data supplied (" + inputLine + ")! Try again...");
}
inputLine = "";
}
System.out.println("============================================");
System.out.println();
// Convert List<Integer> to int[]...
int[] newArray = new int[valuesList.size()];
for (int i=0; i < valuesList.size(); i++) {
newArray[i] = valuesList.get(i);
}
// Display the int[] Array
for (int i = 0; i < newArray.length; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
If I understand correctly, then you want the input of numbers to be limited to the size of the array?
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length && scnr.hasNextInt()) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
}
Your while loop condition should be as long as newArraySize is less than the actual size. Here is a fix with some modifications:
Scanner scnr = new Scanner(System.in);
int[]newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length){
try {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}catch(Exception e){
scnr.nextLine();
}
}
for (int i = 0; i < newArraySize; i++){
System.out.println("The " + i + " input is " + newArray[i]);
}
A solution using Java Stream API:
Scanner sc = new Scanner(System.in);
System.out.println("Input 20 numbers: ");
int[] arr = IntStream.generate(sc::nextInt) // create infinite stream generating values supplied by method `nextInt` of the scanner instance
.limit(20) // take only 20 values from stream
.toArray(); // put them into array
System.out.println(Arrays.toString(arr)); // print array contents at once
Also, there's a utility method Arrays.setAll allowing to set array values via IntUnaryOperator:
int[] arr = new int[20];
Arrays.setAll(arr, (x) -> sc.nextInt());
While loop should have condition for Array Length, kindly try below code which will stop taking inputs after 21st input and array elements will be displayed.
import java.util.Scanner;
public class AarrayScanner {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt() && newArraySize < newArray.length) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
}
}
I keep getting an error with my code specifically at
ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];
the error tells me "; expected" what am I doing wrong here?
Scanner scnr = new Scanner(System.in);
System.out.println("how many lines of text do you want to enter");
int numLines = 0;
numLines = scnr.nextInt();
System.out.println();
ArrayList lines = new ArrayList();
scnr.nextLine();
int i = 0;
do{
System.out.println("Enter your text: ");
String text = scnr.nextLine();
ArrayList<String> input = new ArrayList<String>();
i++;
for (i = 0; i < numLines; i++)
{
ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];
}
for (String element: ArrayList<String> Lines)
{
System.out.println(element);
}
} while(i != 0);
As you have
ArrayList<String> input = new ArrayList<String>();
within your loop, it means that it will get re-declared and initialised for every iteration of that loop, so move this declaration to before your do
Next, to add to this loop, use add method
String text = scnr.nextLine();
input.add (text);
To simplify, you do not need a do as you have a number of times that you want to loop
Scanner scnr = new Scanner(System.in);
System.out.println("how many lines of text do you want to enter");
int numLines = scnr.nextInt();
System.out.println();
scnr.nextLine();
ArrayList <String> lines = new ArrayList <> ();
for (int i = 0; i < numLines; i++) {
System.out.println("Enter word...");
String text = scnr.nextLine();
lines.add(text);
}
To print your list, you can then do
for (int x = 0; x < lines.size(); x++) {
System.out.println (lines.get(x));
}
output
how many lines of text do you want to enter
5
Enter word...
one
Enter word...
two
Enter word...
three
Enter word...
four
Enter word...
five
one
two
three
four
five
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]);
}
}
}
I have a problem with Scanner class. I have a few methods which read certain input from the user, however after invoking first method others crash (cannot read input). I searched for the solution and it looked like adding "scanner.nextLine()" will solve the problem but it didn't.
public class GameController {
private int numberOfPlayers = 2;
private Board board = new Board('.');
String players[] = new String[numberOfPlayers];
char playersMarkers[] = new char[numberOfPlayers];
public void getPlayersNames() {
Scanner input = new Scanner(System.in);
for (int i = 0; i < players.length; i++) {
System.out.print("Insert player " + (i + 1) + "'s name: ");
players[i] = input.nextLine();
}
input.nextLine(); // <- this one was suppose to solve the problem
input.close();
}
public static void main(String[] args) {
GameController gc = new GameController();
gc.getPlayersNames();
Scanner scanner = new Scanner(System.in);
int array[] = new int[5];
for (int i = 0; i < array.length; i++) {
if (scanner.hasNext()) {
array[i] = scanner.nextInt();
}
}
scanner.close();
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Output:
Insert player 1's name: John
Insert player 2's name: George
1
0
0
0
0
0
You are not getting anything from scanner (in the main method) because you already closed System.in (when closing input, at the end of the getPlayersNames method).
You should not close System.in yourself, as it prevent any future attempt to read from this stream.
I was trying to take string input in java. My input should be like this
3
1,1,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
1,2,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
1,3,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
So, I tried this
Scanner in = new Scanner(System.in);
int TotalNumber = in.nextInt();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.next();
}
in.close();
for (int counter = 0; counter < Data.length; counter++) {
System.out.println(Data[counter]);
}
My output is showing this
1,1,bugs#bunny.com,123
Sesame
St.,New
What is my problem ? How take input string line properly ?
Update
I found my solution at here Scanner issue when using nextLine after nextXXX
next() breaks at a whitespace. Instead, you should use nextLine() to input the entire line to your string:
int TotalNumber = in.nextInt();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
Try with Data[Counter] = in.nextLine();
What about:
import java.util.Scanner;
import java.lang.String;
public class Test
{
public static void main(String[] args)
{
char[] sArray;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a Palindrome : ");
String s = scan.nextLine();
s = s.replaceAll("\\s+", "");
sArray = new char[s.length()];
for(int i = 0; i < s.length(); i++)
{
sArray[i] = s.charAt(i);
System.out.print(sArray[i]);
}
}
}
Try this (Mureinik modified code)..
int TotalNumber = in.nextInt();
in.nextLine();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
You need a nextLine() after taking the int because you will press enter after taking int and that enter is read by nextLine() in the Data[0].