I am getting flickering screen when closing the scanner,but without closing it works fine.
public void removeBranch() {
try {
Scanner input=new Scanner(System.in);
System.out.print("Enter branch id to remove:");
int Id=input.nextInt();
int toDelete=branchPresent(Id);
if(toDelete!=-1) {
branches.remove(toDelete);
System.out.println("Branch removed");
}else {
System.out.println("\n No such Branch!\n");
}
} catch (Exception e) {
System.out.println("\nsomething went wrong while removing !\n");
}
}
Close the scanner in finally block
try{
Scanner input=new Scanner(System.in);
// Do stuff
}
catch {
// Handle exception
}
finally {
input.close();
}
Related
I've been reading about java streams and decided to make a simple input class that will read input from the user(keyboard) and return it back.The problem is that i don't know which stream-class to use for simple,primitive values.I made UserInput class using the DataInputStream ,but noticed that i didn't work,because,as i understood,the DataInputStream supports only bufferedStream,and the problem is that i don't know how to flush the input after i read something(There is no flush method).How do i fix this,or could you suggest me another input stream for primitive values(without casting and using of Integer.valueOf() e.t.c methods).Also,i made UserInput with BufferedReader,but i didn't like it,because i had to use methods like:Double/Integer/Short/etc.valueOf()
Here is the code of my class :
import java.io.*;
import java.util.InputMismatchException;
public class UserInput {
static DataInputStream reader;
public UserInput() {
reader = new DataInputStream(System.in);
}
public int getInt() {
int result = -1;
try {
result = reader.read();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return -1");
}
return result;
}
public double getDouble() {
double result = -1;
try {
result = reader.readDouble();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return -1");
}
return result;
}
public float getFloat() {
float result = -1f;
try {
result = reader.readFloat();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return -1");
}
return result;
}
public long getLong() {
long result = -1l;
try {
result = reader.readLong();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return -1");
}
return result;
}
public short getShort() {
short result = -1;
try {
result = reader.readShort();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return -1");
}
return result;
}
public String getString() {
String result = " ";
try {
result = reader.readUTF();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return empty character ");
}
return result;
}
public char getChar() {
char result = ' ';
try {
result = (char) reader.read();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Couldn't open buffered.Return empty character ");
}
return result;
}
/**
* Closes the buffer.
*
*/
public void close() {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("Inputstream has been closed.");
}
}
}
I think there's a misunderstanding here - you're treating System.in (which is a stream of characters) as a DataInputStream (which is a stream of bytes - something very different)
If your intention is to read various types from System.in you could just use operations similar to this:
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
System.out.println("Got string: " + s);
double d = scanner.nextDouble();
System.out.println("Got double: " + d);
So your class could be set up like this:
public UserInput() {
scanner= new Scanner(System.in);
}
Otherwise if your intention was to read and write primitives, you'd need to first write those primitives onto a DataOutputStream, which is equivalent to a DataInputStream. The System.in would not be relevant to the exercise in this case.
I'm writing a Java Exception Handling program and encountered following issue.
when I enter a invalid input an infinite loop started executing instead of execution start from the try block.
public class Exception_Handling {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
boolean bl=true;
do {
try {
int a = sc.nextInt();
int b = sc.nextInt();
bl=false;
}
catch(InputMismatchException ex) {
System.out.println("Enter Valid Number Format");
System.out.println(ex);
}
}while(bl);
}
}
You need to flush your buffer before re-entering in the loop. Otherwise java tries to read the same input again and again.
import java.util.Scanner;
public class Exception_Handling {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
boolean bl = true;
do {
try {
int a = sc.nextInt();
int b = sc.nextInt();
bl = false;
} catch (Exception ex) {
System.out.println("Enter Valid Number Format");
System.out.println(ex);
sc.next();
}
} while (bl);
}
}
You can also use sc.reset() instead of sc.next()in your case. But if you had configured scanner with useDelimiter, useLocale or useRadix it will reset these parameters too. (see reset() java doc)
You have a catch exception on Input Mismatch so it won't bother to execute this statement:
bl = false;
which would not terminate the loop.
public class Exception_Handling {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
boolean bl=true;
do {
try {
bl=false;
int a = sc.nextInt();
int b = sc.nextInt();
}
catch(InputMismatchException ex) {
System.out.println("Enter Valid Number Format");
System.out.println(ex);
}
}while(bl);
}
}
This question already has answers here:
NoSuchElementException after closing system.in
(1 answer)
Scanner throwing NoSuchElementException
(2 answers)
NoSuchElementException Issue
(1 answer)
Closed 5 years ago.
This is a section of my code from a project that is giving an error. I am practicing encapsulation, but, cannot figure out why I am getting this error when I am setting values inside the Array-list.
There are two classes
1) Create_accountant
2) Adminstoreroom
Both of them are under same package: com.admin
package com.admin;
import java.util.InputMismatchException;
import java.util.Scanner;
class Create_accountant {
Adminstoreroom admin = new Adminstoreroom();
void Creating() {
System.out.println();
System.out.println("\t\t\t\t Create New Accoutant");
System.out.println();
name();
pass();
}
void name() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter his/her name: \t");
String name = null;
try {
admin.setAccName(input.nextLine());
System.out.println("done");
}
catch(InputMismatchException e) {
System.out.println("Wrong input. Please enter the name again.");
name();
}
catch(Exception e) {
System.out.println("Here is the main problem " + e);
}
admin.setAccName(name);
input.close();
}
private void pass() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter his/her password: \t");
try {
admin.setAccPassword(input.nextLine());
}
catch(InputMismatchException e) {
System.out.println("Wrong input. Please enter the password again.");
pass();
}
catch(Exception e) {
System.out.println("Here is the main problem");
}
input.close();
}
The problem is inside the 2 try blocks.
try {
admin.setAccName(input.nextLine());
System.out.println("done");
}
Both of the name() and pass() go for the catch(exception e) block. When I run this code, the output from the above try is
Here is the main problem java.util.NoSuchElementException: No line found
The second class
package com.admin;
import java.util.ArrayList;
class Adminstoreroom {
//These arrays are used for Storing accountant info in the admin sections
private static ArrayList<String> accName = new ArrayList<String>(30);
private static ArrayList<String> accPassword = new ArrayList<String>(30);
//Accountant Names
public void setAccName(String an) {
accName.add(an);
}
public String getAccName(int i) {
return accName.get(i);
}
//Accountant Password
public void setAccPassword(String ap) {
accPassword.add(ap);
}
public String getAccPassword(int i) {
return accPassword.get(i);
}
I'm new here, and I got a problem when I'm trying to read a file.
Here is my code
public void openFile()
{
try
{
if(Board.state == Board.STATE.LEVEL1)
{
scan = new Scanner(new File("D://OOP Photos//Map.txt"));
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
try
{
if(Board.state == Board.STATE.LEVEL2)
{
scan = new Scanner(new File("D://OOP Photos//Map1.txt"));
}
}
catch(Exception e)
{
System.out.println("Error loading MAP !!! ");
}
try
{
if(Board.state == Board.STATE.LEVEL3)
{
scan = new Scanner(new File("D://OOP Photos//Map2.txt"));
}
}
catch(Exception e)
{
System.out.println("Error loading MAP !!! ");
}
}
If I comment out the if statement it is okay, but if I leave it there, it will throw a NullPointerException in the next method:
public void readFile()
{
while(scan.hasNext())
{
for(int i = 0; i < 10; i++)
{
if(scan.hasNext())
{
Map[i] = scan.next();
}
}
}
}
Can you help me ?
Thank You :)
Do something like this:
public static void main(String args[]) {
String filename;
if(Board.state == Board.STATE.LEVEL1) {
filename = "D://OOP Photos//Map1.txt";
}
else if (Board.state == Board.STATE.LEVEL2) {
filename = "D://OOP Photos//Map2.txt";
}
else if (Board.state == Board.STATE.LEVEL3) {
filename = "D://OOP Photos//Map3.txt";
}
readFile(filename);
}
public void readFile(String filename) {
try {
Scanner scan = new Scanner(new File(filename));
int i = 0;
while(scan.hasNext()) {
Map[i] = scan.next();
i++;
}
}
catch(FileNotFoundException e) {
System.out.println("Error loading MAP !!! ");
}
}
Before each IF statement simply print out the values of Board.state and Board.STATE.LEVELx? That will tell you exactly why your IFs are all false. Or just set a breakpoint and inspect the values.
Also try changing your == in the IFs to .equals().
Your app logic makes me confused. Why not jsut make simple public Scanner openFile(String filePath) method, with one try / catch block, with one Scanner scan = new Scanner(new File(filePath))?
Here's something to consider:
public static class Board {
// I'm assuming this is what's happening?
public static State state = State.LEVEL1;
public enum State {
LEVEL1("Map.txt"), LEVEL2("Map1.txt"), LEVEL3("Map2.txt");
private final String fileName;
private State(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
}
};
public void openFile() {
if (Board.state == null)
throw new RuntimeException("board state not set");
File file = new File("D:/OOP Photos/", Board.state.getFileName());
try (Scanner scan = new Scanner(file)) {
// do the scanning
} catch (FileNotFoundException fnfe) {
// handle file not found
} catch (Exception e) {
// handle other errors
}
}
I want to read the barcode and print it in a console in a simple java program as soon as the barcode scans on top of any barcode. Is there any way?
final Scanner scanner;
try
{
scanner = new Scanner();
try {
scanner.release();
scanner.close();
} catch (Exception e) {
}
scanner.open("MotorolaScannerUSB");
scanner.claim(100);
scanner.setDeviceEnabled(true);
scanner.setDataEventEnabled(true);
scanner.addDataListener(new DataListener()
{
public void dataOccurred(DataEvent arg0) {
Scanner scn = (Scanner) arg0.getSource();
if (scn.equals(scanner)) {
try {
scanner.claim(100);
System.out.println(new String(scanner.getScanData()));
scanner.claim(100);
scanner.setDeviceEnabled(true);
scanner.setDataEventEnabled(true);
} catch (JposException e) {
e.printStackTrace();
}
}
}
});
}
catch (Exception e) {
System.err.println("error");
}