This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 7 years ago.
My code below has a exception error for:
YN = input.nextLine().charAt(0); //line 13
when it is run. The assignment is to make an array that is assigned 10 numbers from console, when I put in 10 numbers the run completes automatically and gives an error for line 13. Is there something wrong with line 13 or is the issue with something else?
(The array must be a normal array and not an arrayList)
import java.util.*;
import java.util.Arrays;
public class CountOccurrences {
static Scanner input = new Scanner(System.in);
static int[][] temp = new int[10][1];
public static void main(String[] args) {
char YN = 'y';
while (YN == 'y') {
run();
System.out.print("Continue? (y or n)\t");
YN = input.nextLine().charAt(0); // Line 13
}
}
public static void run() {
System.out.print("Enter the integers between 1 and 100: ");
int[] numbersArray = new int[10];
for (int i = 0; i < numbersArray.length; i++) {
numbersArray[i] = input.nextInt();
}
for (int i = 0; i < numbersArray.length; i++) {
Arrays.sort(numbersArray);
System.out.println(numbersArray[i]);
}
}
}
input.nextLine() could be an empty String, in which case input.nextLine().charAt(0) will give you that exception. You should check the length() of the String before calling charAt.
Now that I see you are using input.nextInt() to read the inputs in your run() method, what you have to do is add a input.nextLine() at the end of the run() method, to consume the end of the line that contains the final int.
You still have to check the length of the String you get in input.nextLine(), though, since the user may hit enter instead of hitting Y or N, which will result in the same exception.
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
import java.util.Scanner;
public class EngineStorage {
Engine[] engines = new Engine[3];
Scanner scanner = new Scanner(System.in);
public void fillArray(Engine[] engines) {
String name;
double vol;
for (int i = 0; i < engines.length; i++) {
System.out.println("name");
name = scanner.nextLine();
System.out.println("volume");
vol = scanner.nextDouble();
}
}
}
when "i" is 0 it works fine but then loop is avoiding "name" variable when "i" is 1 and 2. The result is:
name
e32
volume
2,5
name
volume
3
name
volume
3
Process finished with exit code 0
nextDouble() does not skip to the next line, so the next time nextLine() is ran, it will read what is left on that line, which is nothing. You can consume the rest of this line with a blank newline like
for (int i = 0; i < engines.length; i++) {
System.out.println("name");
name = scanner.nextLine();
System.out.println("volume");
vol = scanner.nextDouble();
scanner.nextLine(); //skip to next line
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I have a Java program below. At first, I tried to get input n as this
int n = sc.nextInt();
But the output was different than expected. It runs the first iteration without taking the userName. After changing to
int n = Integer.parseInt(sc.nextLine());
It's working fine. What was wrong with "int n = sc.nextInt();"?
public class StringUserNameChecker {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Number of usernames you want to enter
int n = Integer.parseInt(sc.nextLine());
while (n-- != 0) {
String userName = sc.nextLine();
System.out.println("Your username is " + userName);
}
}
}
When sc.nextLine() is used after sc.nextInt(), it will read a newline character after the integer input.
So, to run your code correctly, you'll have to use sc.nextLine() after sc.nextInt(), like this:
int n = sc.nextInt();
sc.nextLine();
while(n-- > 0) {
String username = sc.nextLine();
}
First of all, i just started programming with Java so i'm really a noob :P
Ok so my instructor gave me an assignment which is to take an int input from the user and put each digit in a new line.
for example, if the user gave 12345, the program will give:
1
2
3
4
5
each number in a new line.
The statements i will be using is IF statement and the loops and operators ofcourse.
I thought about using the % operator inside the IF/WHILE but i have two issues. One is that i don't know the number of digits the user is inputting and since i can't use the .length statement i reached a dead end. second of all the console output will be 5 4 3 2 1 inversed.
So can anyone help me or give me any ideas?
import java.util.Scanner;
public class NewLineForDigit {
public static void main(String[] args) {
System.out.print("Please, enter any integer: ");
Scanner sc = new Scanner(System.in);
String intString = sc.next();
for (char digit : intString.toCharArray()) {
System.out.println(digit);
}
}
}
Given the assignment your instructor gave you, can you convert the int into a String? With the input as a String, you can use the length() String function as you had mentioned to iterate the number of characters in the input and use the built-in String function charAt() to get the index of character you want to print. Something like this:
String input = 12345 + "";
for(int i = 0; i < input.length(); i++)
System.out.println( input.charAt(i) );
How about using a Scanner to get the users input as an int and converting that int to a String using valueOf. Lastly loop over the String to get the individual digits converting them back to int's from char's :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a Integer:");
int input = sc.nextInt();
String stringInput = String.valueOf(input);
for(int i = 0; i < stringInput.length(); i++) {
int j = Character.digit(stringInput.charAt(i), 10);
System.out.println(j);
}
}
}
Try it here!
This question already has answers here:
Get specific ArrayList item
(8 answers)
Closed 7 years ago.
The code is trying to take String entries, add them to an array and then stop when no text is written (user just presses enter). Then it is meant to display all of the String items in the array thus far on new lines.
The error in my title is coming up on my if query, and I'm additionally getting error's reading the value 'x' in the for loop as a variable (cannot find symbol).
Can anyone help me out
import java.util.Scanner;
import java.util.ArrayList;
public class FirstPart {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> tillEmpty = new ArrayList<String>();
int i = 0;
while (true) {
System.out.print("Type a word: ");
tillEmpty.add(reader.nextLine());
if (tillEmpty[i].isEmpty()) {
break;
} else {
i++;
}
}
System.out.println("You typed the following words: ");
for (x = 0; x < tillEmpty.size; x++){
System.out.println(tillEmpty.get(x));
}
}
}
The error message is telling you exactly what is wrong. You've got an ArrayList and are trying to treat it as if it were an array. It isn't, and you can't use array indices, [i] on it. Instead use the get(...) method as any tutorial will tell you (and which I strongly recommend that you read -- Google can help you find one).
Your tillEmpty is not an array but an arraylist...you have to use tillEmpty.get(i).isEmpty instead of tillEmpty[i]
You missed int in your for loop:
for (int x = 0; x < tillEmpty.size; x++){
System.out.println(tillEmpty.get(x));
}
You are accessing list as Array, use below code, this should work:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> tillEmpty = new ArrayList<String>();
int i = 0;
while (true) {
System.out.print("Type a word: ");
tillEmpty.add(reader.nextLine());
if (tillEmpty.isEmpty()) {
break;
} else {
i++;
}
}
System.out.println("You typed the following words: ");
for (int x = 0; x < tillEmpty.size(); x++){
System.out.println(tillEmpty.get(x));
}
}
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
Why is my while loop making two passes before allowing user input? Tried the same with for loop and can't figure out why it's asks for input twice before allowing user to enter input. I know it's a stupid, simple logic mistake I'm making but I'm a noob. Thanks in advance.
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
System.out.println("How large would you like the array to be? (number)");
int arraySize = scan.nextInt();
String [] myArray = new String [arraySize];
int i = 0;
if (arraySize <= 0 ) {
System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
} else {
while (i < myArray.length) {
System.out.println("Please type a string to be entered in the array");
myArray[i] = scan.nextLine();
i++;
}
}
}
Output looks like
How large would you like the array to be? (number)
5
Please type a string to be entered in the array
Please type a string to be entered in the array
Add scan.nextLine(); right after your nextInt:
int arraySize = scan.nextInt();
scan.nextLine();
The first iteration of the while loop is not blocking on the nextLine() because it is picking the new line after the first integer that you input.
Try this:
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
System.out.println("How large would you like the array to be? (number)");
int arraySize = scan.nextInt();
scan.nextLine(); // This advances the Scanner to the next line.
String [] myArray = new String [arraySize];
int i = 0;
if (arraySize <= 0 ) {
System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
} else {
while (i < myArray.length) {
System.out.println("Please type a string to be entered in the array");
myArray[i] = scan.nextLine();
i++;
}
}
}