Userinput scanner unknow source - java

i run the code it gives an these errors:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Main.start(Main.java:15)
at Main.main(Main.java:9)
this code is ment to take the input out of the main then put the data in the save and let the text you add to the file safe the words and keeps updating but i keep getting errors whit wrong user input if some1 can help me fix the error i would apprecieet it here the code there in the directionary and the files are connect (no package needed)
Main java
import java.util.Scanner;
public class Main{
Save option = new Save();
public static void main(String[] args) {
Main main = new Main();
main.start();
}
public void start(){
Scanner scanner = new Scanner(System.in);
System.out.println("1. Add random words to file");
int result = scanner.nextInt();
scanner.nextLine();
if (result == 1 ) {
try{
String safeWordsString = "";
System.out.println("Type some words");
safeWordsString = scanner.nextLine();
option.safeWords(safeWordsString);
} catch (Exception e) {
start();
}
}
}
}
Save java
import java.util.*;
import java.io.*;
public class Save
{
public void safeWords(String saveTekst)
{
try{
//USER INPUT BINNEHALEN
// Scanner userInput = new Scanner(System.in);
// System.out.println("Welke regel wil je toevoegen");
// String regel = userInput.nextline();
// ORIGINELE DATA VERZAMELEN
File original = new File("test.txt");
Scanner scanner = new Scanner(original);
StringBuilder temp = new StringBuilder();
while (scanner.hasNext()){
temp.append(scanner.nextLine() + "\n");
}
// NIUEWE DATA APPENDEN
PrintWriter pw = new PrintWriter(original);
pw.println(temp);
pw.println(new Date() + " " + saveTekst);
pw.close();
System.out.println("End");
} catch (Exception e) {
System.out.println("Error");
}
}
}

You should accept your input as String
public void start(){
Scanner scanner = new Scanner(System.in);
System.out.println("1. Add random words to file");
String result = scanner.nextLine();
if("1".equals(result)){
...
}
}

In the program itself, you are trying to get the integer from Scanner..
if the integer is 1, then you are proceeding further to add random words, it is just like choosing an option from list of options..
Here you have only 1 option, so please choose it first(type 1 and enter), then proceed further to add your random words..

Related

How can I fix java.util.NoSuchElementException

I would like to fix the java.util.NoSuchElementException bug.
I keep getting the error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Main.newUser(Main.java:28)
at Main.main(Main.java:18)
with this code
import java.util.Scanner;
import java.io.*;
class Main2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
input.close();
newUser();
}
private static void newUser()
{
try
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the name for the new user.");
String userNameNew = input.nextLine();
System.out.println("Please enter the password for the new user.");
String userPassWordNew = input.nextLine();
System.out.println("The new user: " + userNameNew + " has the password: " + userPassWordNew + "." );
PrintWriter out = new PrintWriter("users.txt");
out.print(userNameNew + "\r\n" + userPassWordNew);
out.close();
input.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
Can you please help me? Thank you.
I found the reason why you are getting this exception.
So in your main method, you initialized your Scanner class object and immediately close it.
Here is the problem. Because when scanner calls the close() method, it will close its input source if the source implements the Closeable interface.
When a Scanner is closed, it will close its input source if the
source implements the Closeable interface.
https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html
And InputStream class which is the input source in your case implements the Closeable interface.
https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html
And further you initialized the Scanner class object into your newUser() method. Here scanner class object initialized successfully but your input source is still close.
So my suggestion is that close scanner class object only once.
Please find the updated code of yours.
class Main2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
newUser(input);
//input.close()
}
private static void newUser(Scanner input)
{
try {
System.out.print("Please enter the name for the new user.");
String userNameNew = input.nextLine();
System.out.println("Please enter the password for the new user.");
String userPassWordNew = input.nextLine();
System.out.println("The new user: " + userNameNew + " has the password: " + userPassWordNew + "." );
PrintWriter out = new PrintWriter("users.txt");
out.print(userNameNew + "\r\n" + userPassWordNew);
out.close();
} catch (IOException e) { e.printStackTrace(); }
}
}

How to read from a text file and move onto next line

I am making a program that will scan a text file to find all the ints, and then print them out, and move onto the next line
Ive tried turning if statements into while loops to try to improve, but my code runs through the text file, writes out all the numbers, but fails at the end where it runs into a java.util.NoSuchElementException. If I have a text file with the numbers
1 2 3
fifty 5,
then it prints out
1
2
3
5
But it crashes right at the end everytime
import java.util.Scanner;
import java.io.*;
public class filterSort
{
public static void main()
{
container();
}
public static void run()
{
}
public static void container()
{ Scanner console = new Scanner(System.in);
int count = 0;
int temp;
try
{
System.out.print("Please enter a file name: ");
String fileName = console.nextLine();
Scanner file = new Scanner(new File(fileName));
while(file.hasNextLine())
{
while(file.hasNextInt())
{
temp = file.nextInt();
System.out.println(temp);
}
file.next();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
}
}
}
Replace
file.next();
with
if(file.hasNextLine())
file.nextLine();
Every time you try to advance on a scanner, you must check if it has the token.
Below is the program which is working for me . Also it is good practice to close all the resources once done and class name should be camel case. It's all good practice and standards
package com.ros.employees;
import java.util.Scanner;
import java.io.*;
public class FileTest
{
public static void main(String[] args) {
container();
}
public static void container()
{ Scanner console = new Scanner(System.in);
int count = 0;
int temp;
try
{
System.out.print("Please enter a file name: ");
String fileName = console.nextLine();
Scanner file = new Scanner(new File(fileName));
while(file.hasNextLine())
{
while(file.hasNextInt())
{
temp = file.nextInt();
System.out.println(temp);
}
if(file.hasNextLine())
file.next();
}
file.close();
console.close();
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
}
}
}

Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source)

I am getting java.util.NoSuchElementException.
Scanner only works one time (the first loop).
The full stack trace is:
Exception in thread "main"
java.util.NoSuchElementException at
java.util.Scanner.throwFor(Unknown Source) at
java.util.Scanner.next(Unknown Source)
Could you please help me fix my code:
import java.util.Scanner;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
String answer;
do
{
input = new Scanner(System.in);
System.out.println("MAIN MENU");
System.out.println("- Start a new Game (S)");
System.out.println("- Exit (E)");
System.out.println("Please enter your choice: ");
answer = input.next();
if (answer.equals("s") || answer.equals("S"))
{
Hangman h1 = new Hangman();
h1.getWord();
h1.printData();
h1.CountTheLetters();
h1.GiveTheLetters();
}
} while (!answer.equals("e") && !answer.equals("E"));
input.close();
System.out.println("Thank you for the game");
}
}
try instantiating Scanner object inside the do-while loop instead of instantiating it in the main function..
Your code seems to work on Eclipse,are you using any online IDE like Ideone,because online IDE's take input only once like all input only once so there is a runtime error I would suggest you to run your code on eclipse If that doesn't seem to work do something as I have done below:
import java.util.Scanner;
import java.io.*;
public class Main {
public static void funct(Scanner input){
System.out.println("MAIN MENU");
System.out.println("- Start a new Game (S)");
System.out.println("- Exit (E)");
System.out.println("Please enter your choice: ");
String answer = input.next();
if(answer.equals("e")||answer.equals("E")){
System.out.println("Thank You For the Game");
}
else{
funct(input);
}
}
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
funct(input);
}
}

Make user only input integer in scanner Java

i have some problems here.
I want to user only can input as an integer. I have tried by many code, but still doesn't work. Btw, this is my code
import java.util.Scanner;
public class test {
public static void main (String []args){
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
}
}
When error, the message will shown as
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at test.main(test.java:6)
Please help me (Beginner Programmer);
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (!scan.hasNextInt()) {
System.out.println("Input is not a number.");
scan.nextLine();
}
int number = scan.nextInt();
}
This code will check if the input is an Integer, if it is then it will continue.
Try this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a number -> ");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
break;
} catch (NumberFormatException ne) {
System.out.println("This is not a number");
}
}
}
This program will end when the user enter a integer input value.
Output
Such an error only occurs if the user did not enter an integer.For such a situation, you could create a try-catch block, that catches the exception, like this:
String input = sc.next();
int number = 0;
try {
number = Integer.valueOf(input);
} catch (NumberFormatException ne) {
System.out.println("Invalid input!");
}
To optimize the solution even more, put this all in a loop, and break out of it in the try-block, and keep polling for input if the user enters a bad number.

Reading x lines of text at a time from a text file in Java

I'm trying to write a method for a school project for displaying a list of contacts from a text file. Only four contacts are supposed to display at a time and then re-entering "d" should display the next 4 until all have been displayed. Does anyone have any advice in how I could achieve this? Right now I just have it so it reads all of the lines of text.
import java.util.Scanner; import java.io.*;
public class Contacts
{
public static void main(String [] args) throws IOException
{
File aFile = new File("contacts.txt");
if (!aFile.exists())
System.out.println("Cannot find file");
else
{
Scanner in = new Scanner(aFile);
String input;
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
if (input.contains("d"))
{
String aLineFromFile;
while(in.hasNext())
{
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
}
in.close();
}
}
}
}
As MadProgrammer said, use a counter to track groups of 4.
else {
Scanner in = new Scanner(aFile);
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
while(input.contains("d")) {
int limit = 4;
String aLineFromFile;
while(in.hasNext() && limit > 0) {
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
limit--;
}
if(in.hasNext()) {
input = keyboard.nextLine();
}
else {
break;
}
}
}

Categories