Java - read String and int: java.util.NoSuchElementException - java

I try to read an int and after it a string, in this way:
String wantA = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter A");
wantA = in.nextLine();
in.close();
// some code
int want = 0;
Scanner in = new Scanner(System.in);
System.out.println("Save? Press 1 for yes, or 0 for no");
want = in.nextInt();
in.close();
after it prints
Save? Press 1 for yes, or 0 for no
then I get
java.util.NoSuchElementException
How can I fix it?

Remove in.close(); - it is killing the input stream (which never gets reopened).
Instead just keep using the same Scanner.
Change your code to this:
Scanner in = new Scanner(System.in);
System.out.println("Enter A");
String wantA = in.nextLine();
System.out.println("Save? Press 1 for yes, or 0 for no");
int want = in.nextInt();

Related

Multiple Scanner Inputs (Java)

I am currently learning Java and had a question:
I know that using Scanner will allow me to receive input from the console, but how do I receive multiple inputs on one line, rather than just one input per line?
For example:
Enter input: 1 3 5
You don't need multiple scanners. one is more than enough
By an input like 1 3 5 you can read that as a whole line(string)
Scanner sc = new Scanner(System.in);
String input1 = sc.nextLine();
System.out.println(input1);
or just get integer by integer
int inputA1 = sc.nextInt();
int inputA2 = sc.nextInt();
int inputA3 = sc.nextInt();
System.out.println("--------");
System.out.println(inputA1);
System.out.println(inputA2);
System.out.println(inputA3);
You can use below function that will return you multiple inputs from scanner
public List<String> getInputs(String inputseparator)
{
System.out.println("You Message here");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
return line.split(inputseparator);
}
and you can use it like that
List<String> inputs = getInputs(" ");
//iterate inputs and do what you want to . .
You can use nextLine() method of scanner.Below is sample code.
import java.util.Scanner;
public class Test {
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
//sample input: 123 apple 314 orange
System.out.println("Enter multiple inputs on one line");
String st = s.nextLine();
s = new Scanner(st).useDelimiter("\\s");
//once the input is read from console in one line, you have to manually separate it using scanner methods.
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.nextInt());
System.out.println(s.next());
s.close();
}
}

Using exception handling to force user to input a char (letter) instead of String in Java

Say I had some code like:
Scanner scan = new Scanner(System.in);
System.out.print("Please input a letter: ");
char userLetter = nextLine().charAt(0);
I'd like to use exception handling to make sure the user only inputs a letter and nothing more. Is there a good way to do this?
If you need to introduce exception handling here is what I would do:
Scanner scan = new Scanner(System.in);
char c;
while(true) {
System.out.print("Please input a letter: ");
try {
String s = scan.next();
if(s.length() > 1) {
throw new RuntimeException("Input too long!");
}
c = s.charAt(0);
if (Character.isLetter(c)){
throw new RuntimeException("Char is not a letter!");
}
// here you can break the loop and do whatever
} catch(RuntimeException re){
System.out.print(re.getMessage());
// you can break the loop or try again
}
}
P.S. In real-world applications using exceptions for controlling the flow of execution is considered a bad practice. So keep in mind that this code should be used only as an exercise.
Frankly, I wouldn't use exceptions in this situation. There's nothing "exceptional" going on - just the user providing the wrong input. You can check it and prompt the use to input something different:
Scanner scan = new Scanner(System.in);
System.out.print("Please input a letter: ");
String line = nextLine();
while (line.length() != 1 || !Character.isLetter(line.charAt(0))) {
System.out.print("That's not a letter. Please try again: ");
String line = nextLine();
}
If the throwing of exception is required you could do something like this:
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
if(input.length() != 1){
throw new Exception("...");
}
char userLetter = input.charAt(0);
I think this should work.
You could check the length of the String and if it is greater than 1, :
String s = null;
do{
System.out.println("Enter Character : ");
s = scan.next();
if(s.length()!=1)
System.out.println("Error");
}while(s.length()!=1);
System.out.println(s.charAt(0));
If needed, you could add another check for Character#isLetter.
Exceptions should not be used for circumstances that might happen too often.... Instead, we should use if...else to handle regularly occurring situations...
Why don't you use something like this:-
Scanner input = new Scanner(System.in);
String text = new String();
do {
System.out.print("Type a character: ");
text = input.nextLine();
if(text.length() > 1) {
System.out.println("Kindly enter only one character...");
}
} while(text.length() > 1);

Need to close out java with the letter q

I'm pretty new to programming. I need it to say "Enter the letter q to quit or any other key to continue: " at the end. If you enter q, it terminates. If you enter any other character, it prompts you to enter another positive integer.
import java.util.Scanner;
public class TimesTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
}
public static void printMultiplicationTable(int tableSize) {
System.out.format(" ");
for(int i = 1; i<=tableSize;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("------------------------------------------------");
for(int i = 1 ;i<=tableSize;i++) {
System.out.format("%4d |",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
}
Do this to have the user input a letter
Info:
System.exit(0) exits the program with no error code.
nextLine() waits for user to enter string and press enter.
nextInt() waits for user to enter int and press enter.
Hope this helps!
Scanner input = new Scanner(System.in);
String i = input.nextLine();
if(i.equalsIgnoreCase("q")) {
System.exit(0);
}else {
System.out.println("Enter a postive integer: ");
int i = input.nextInt();
//continue with your code here
}
This looks like homework ;-)
One way to solve this problem is to put your code that prints your messages and accepts your input inside a while loop, maybe something like:
Scanner input = new Scanner(System.in);
byte nextByte = 0x00;
while(nextByte != 'q')
{
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
System.out.println("Enter q to quit, or any other key to continue... ");
nextByte = input.nextByte();
}
use a do-while loop in your main method as below
do {
System.out.println("Enter a postive integer: ");
String tableSize = input.next();
if (!"q".equals(tableSize) )
printMultiplicationTable(Integer.parseInt(tableSize));
}while (!"q".equals(input.next()));
input.close();
you would also want to have a try-catch block to handle numberFormatException

Why can't I enter another string after the first time in a for loop?

I want to create a program that allows me to enter name, age, and year of birth for 5 different people. However, I get a problem where I cannot enter another name after I entered the first in my for loop. Here is my code:
public static void main(String[] args) {
String[] names = new String[5];
int[] s = new int[5];
Scanner keyboard = new Scanner (System.in);
for (int i = 0; i < 5; i++) {
System.out.print("Name: ");
names[i] = keyboard.nextLine();
System.out.print("Age: ");
s[i] = keyboard.nextInt();
System.out.print("Year: ");
s[i] = keyboard.nextInt();
}
}
The program works fine when I run it, but it will not allow me to enter the other 4 names after I entered the first. Here is the output I am getting:
Please note:
String java.util.Scanner.next() - Returns:the next token
String java.util.Scanner.nextLine() - Returns:the line that was skipped
Change your code [do while initial lines] as below:
names[i] = keyboard.next();
Take a look- I've fixed your code- added "keyboard.nextLine();" at the end.
public static void main(String[] args) {
String[] names = new String[5];
int[] s = new int[5];
Scanner keyboard = new Scanner (System.in);
for (int i = 0; i < 5; i++) {
System.out.print("Name: ");
names[i] = keyboard.nextLine();
System.out.print("Age: ");
s[i] = keyboard.nextInt();
System.out.print("Year: ");
s[i] = keyboard.nextInt();
keyboard.nextLine();
}
}
The reason you need to add it is that "nextInt()" will only read what you've entered and not the rest of the line. What's left of the line will be then read by "names[i] = keyboard.nextLine();" automatically.
By putting another "keyboard.nextLine()" at the end, I've skipped what left of the line and then "names[i] = keyboard.nextLine();" gets a new line to read input from.
Every beginner in Java encounters this problem sooner or later :)

Java stop reading after empty line

I'm doing an school exercise and I can't figure how to do one thing.
For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.
This is the problem.
The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.
I've done this:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please insert text:");
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
But this is not working properly and I can't figure it out.
Ideally, if the user enters:
This is line one
This is line two
and now press enter, wen printing the array it should give:
[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
Can you help me?
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String in both cases:
while(true) {
String nextLine = sc.nextLine();
if ( nextLine.equals("") ) {
break;
}
text[i] = nextLine;
i++;
}
Here's the typical readline idiom, applied to your code:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
String line;
System.out.println("Please insert text:");
while (!(line = sc.nextLine()).equals("")){
text[i] = line;
i++;
}
The code below will automatically stop when you try to input more than 10 strings without prompt an OutBoundException.
String[] text = new String[10]
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++){ //continous until 10 strings have been input.
System.out.println("Please insert text:");
string s = sc.nextLine();
if (s.equals("")) break; //if input is a empty line, stop it
text[i] = s;
}

Categories