I am creating a small algorithm and this is a part of it.
If the user enters non integer values, I want to output a message and let the user enter a number again:
boolean wenttocatch;
do
{
try
{
wenttocatch = false;
number_of_rigons = sc.nextInt(); // sc is an object of scanner class
}
catch (Exception e)
{
wenttocatch=true;
System.out.println("xx");
}
} while (wenttocatch==true);
I am getting a never ending loop and I can't figure out why.
How can I identify if the user enters some non integer number?
If the user enters a non integer number, how can I ask the user to enter again?
Update
When I am printing the exception I get 'InputMismatchException', what should I do?
The Scanner does not advance until the item is being read. This is mentioned in Scanner JavaDoc. Hence, you may just read the value off using .next() method or check if hasInt() before reading int value.
boolean wenttocatch;
int number_of_rigons = 0;
Scanner sc = new Scanner(System.in);
do {
try {
wenttocatch = false;
number_of_rigons = sc.nextInt(); // sc is an object of scanner class
} catch (InputMismatchException e) {
sc.next();
wenttocatch = true;
System.out.println("xx");
}
} while (wenttocatch == true);
You dont have to do a try catch. This code will do the trick for you :
public static void main(String[] args) {
boolean wenttocatch = false;
Scanner scan = new Scanner(System.in);
int number_of_rigons = 0;
do{
System.out.print("Enter a number : ");
if(scan.hasNextInt()){
number_of_rigons = scan.nextInt();
wenttocatch = true;
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(!wenttocatch);
}
Anytime you get an exception, wenttocatch is set to true and the program will be stuck in an infinite loop. As long as you don't get the exception you'll not get an infinite loop.
The logic if sc.nextInt() causing the error is this
1) wenttocatch is set to false
2) sc.nextInt() throws error
3) wenttocatch is set to true
4) repeat[because wenttocatch is true]
To solve this set wentocatch=false in catch statement
catch (Exception e) {
wenttocatch=false;
System.out.println("xx");
}
if you are doing more than you show here, use a counter[if your counting or a boolean if you are not], but unless you are doing more, do the first thing above
boolean wenttocatch;
int count = 0;
do{
try {
wenttocatch=false;
number_of_rigons=sc.nextInt(); // sc is an object of scanner class
} catch (Exception e) {
count++;
wenttocatch=true;
System.out.println("xx");
}
}while(wenttocatch==true && count < 1);
Answer Comment:
I think you want to get ints until a user doesn't enter anymore. Depending on your input one way of doing that is this
int number_of_rigons;
while((number_of_rigons = sc.nextInt()) != null){
//do something
}
you simply can use the hasNext(); method in java, instead of try and catch.
The hasNext() is a method of Java Scanner class that returns true if this scanner has another token in its input.
String[] stringArray = new String[lines];
int i = 0;
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String data=sc.nextLine();
stringArray[i] = data;
i++;
}
} catch (FileNotFoundException fileNotFoundException) {
System.err.println("Error opening file.");
throw new FileNotFoundException();
} catch (NoSuchElementException e) {
System.err.println("Error in file record structure");
throw new NoSuchElementException();
} catch (Exception e) {
e.printStackTrace();
}
/*added the scanner declaration inside try im new on programming its worked for me but I don't know if its good practice
*/ :
boolean wenttocatch;
do
{
try
{
Scanner sc=new Scanner(System.in);
wenttocoatch = false;
number_of_rigons = sc.nextInt();
}
catch (Exception e)
{
wenttocatch=true;
System.out.println("xx");
}
} while (wenttocatch==true);
....
try {
....
} catch (Exception e) {
sc.next();
wenttocatch=true;
System.out.println("xx");
}
Related
I am trying to read integers from a text file but I failed.
(It fails to read even the first integer)
public void readFromFile(String filename) {
File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
if (scanner.hasNextInt()) {
int x = scanner.nextInt();
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File to load game was not found");
}
}
The error I get is: NoSuchElementException.
The file looks like this:
N,X1,Y1,X2,Y2,X3,Y3
While n equals 3 in this example.
I call this method a in the main method like this:
readFromFile("file.txt");
I am not sure whether you would like to display only the integers after separating them from the string. If that is the case, I would suggest you to use BufferedInputStream.
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
String input = br.readLine();
int count = 0;
for(int i = 0; i < input.length()- 1; i++){
if(isNumeric(input.charAt(i))){
// replace the Sysout with your own logic
System.out.println(input.charAt(i));
}
}
} catch (IOException ex){
ex.printStackTrace();
}
where isNumeric can be defined as follows:
private static boolean isNumeric(char val) {
return (val >= 48 && val <=57);
}
Scanneruses whitespace as the default delimiter. You can change that with useDelimiter See here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
I'm trying to create a List by reading a txt file. For example:
12345; Mary Jane ; 20
12365; Annabelle Gibson; NA
Each line contains: number; name; Grade (grade can be a String or a int)
I created the following method;
public static List <Pauta>leFicheiro( String nomeF) throws FileNotFoundException{
List<Pauta> pautaT = new LinkedList<Pauta>();
try {
Scanner s = new Scanner(new File (nomeF));
try{
List<Pauta> pautaS =pautaT;
while ( s.hasNextLine()){
String line = s.nextLine();
String tokens[]= line.split(";");
if(s.hasNextInt()) {
System.out.println ("next int = " + s.nextInt());
}
pautaS.add(new Pauta (s.nextInt(), tokens[1],tokens[2]);
}
pautaT = pautaS;
}
finally {
s.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (ParseException e){
e.printStackTrace();
}
return pautaT;
}
Pauta is a class that receives as arguments ( int, String, String), I thought Grade as a String to make it more simple, but if you have ideas on how to still create a List (main goal) by having it String or int I would be thankful.
Now the problem is: The part s.nextInt() is returning error : InputMismatchException
So I put this following code:
catch (InputMismatchException e) {
System.out.print(e.getMessage());}
which says it returns a null.
How can I solve this?
Instead of using the s.nextInt(), parse the first token to an Integer.
See the example below.
public static void main(String... args) throws FileNotFoundException {
List<Pauta> pautaT = new LinkedList<Pauta>();
try {
Scanner s = new Scanner(new File("test.txt"));
try{
List<Pauta> pautaS =pautaT;
while ( s.hasNextLine()){
String line = s.nextLine();
String tokens[]= line.split(";");
pautaS.add(new Pauta (Integer.parseInt(tokens[0]), tokens[1],tokens[2]));
}
pautaT = pautaS;
}
finally {
s.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
This results in the list to be populated.
Yo may use StringTokenizer and save each token of the same line into a variable and then use them as you want.
Whenever I run this method, it produces an error saying that there is no line. The file (inv.txt) is a 1 on 25 lines, So 25 ones, each on a seperate line.
public class Inventory
{
File inventory = new File("Resources/inv.txt");
File db = new File("Resources/db.txt");
FileWriter write;
StringBuilder writethis;
public void addItem(int item, int slot)
{
int i = 1;
writethis = new StringBuilder();
Scanner scan;
try
{
scan = new Scanner(inventory);
if (scan.hasNextLine())
{
while (i < slot)
writethis.append(scan.nextLine()); // This is where it says the
// error is. For reference,
// slot is 2. It may somehow
// be making an infinite loop,
// but I don't know why it
// would.
scan.nextLine();
writethis.append(item);
while (i < 24)
writethis.append(scan.nextLine());
System.out.println(writethis.toString());
scan.close();
}
try
{
write = new FileWriter(inventory);
write.write(writethis.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Could this be due to the fact that the instance variable i is never incremented?
I would also close the data streams in a finally block.
I have a text file that reads:
Description|SKU|Retail Price|Discount
Tassimo T46 Home Brewing System|43-0439-6|17999|0.30
Moto Precise Fit Rear Wiper Blade|0210919|799|0.0
I've got it so that I read everything, and it works perfectly, save for the fact that it reads the first line, which is a sort of legend for the .txt file, which must be ignored.
public static List<Item> read(File file) throws ApplicationException {
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
throw new ApplicationException(e);
}
List<Item> items = new ArrayList<Item>();
try {
while (scanner.hasNext()) {
String row = scanner.nextLine();
String[] elements = row.split("\\|");
if (elements.length != 4) {
throw new ApplicationException(String.format(
"Expected 4 elements but got %d", elements.length));
}
try {
items.add(new Item(elements[0], elements[1], Integer
.valueOf(elements[2]), Float.valueOf(elements[3])));
} catch (NumberFormatException e) {
throw new ApplicationException(e);
}
}
} finally {
if (scanner != null) {
scanner.close();
}
}
return items;
}
How do I ignore the first line using the Scanner class?
Simply calling scanner.nextLine() once before any processing should do the trick.
how about calling scanner.nextLine() as outside your loop.
scanner.nextLine();//this would read the first line from the text file
while (scanner.hasNext()) {
String row = scanner.nextLine();
scanner.nextLine();
while (scanner.hasNext()) {
String row = scanner.nextLine();
....
Struggling still with this after hours or research.. I have a simple helper class which is my first foray into try/catch error handling. I want to know if an input is valid against the type required and ask for a new input if it isn't... simple or so I thought. The class is being used in a simple term deposit calculator and is called multiple times (i.e. initial deposit, interest rate etc).
Here is the offending class, if this isn't sufficient to resolve I'll post up some additional snippets.
private Float inFloat;
private String temp;
private int inInt;
private String inString;
BufferedReader in = null;
boolean validInput = false;
public Float getFloat(String prompt) {
validInput = false;
do {
try {
in = new BufferedReader(new InputStreamReader(System.in));
System.out.print(prompt);
temp = in.readLine();
inFloat = Float.valueOf(temp);
validInput = true;
} catch (IOException e) {
System.out.println("Please enter a valid float value");
} finally {
try {
if (in != null) {
in.close();
}
} catch(IOException e) {
e.printStackTrace();
}
}
} while (validInput == false);
return inFloat;
}
Update - Fixed!!!
Thanks for the quick feedback... I managed to find another post that mentioned I shouldn't be closing off the BufferedReader and came up with the following adjustments so it now works. I'm now catching a NumberFormatException as well.. thanks for the tip :)
Not sure why it works now that I don't close off the BufferedReader... but I'll take the result!!
private Float inFloat;
private String temp;
private int inInt;
private String inString;
BufferedReader in = null;
boolean validInput = false;
public Float getFloat(String prompt) {
validInput = false;
do {
try {
in = new BufferedReader(new InputStreamReader(System.in));
System.out.print(prompt);
temp = in.readLine();
inFloat = Float.valueOf(temp);
validInput = true;
} catch (NumberFormatException e) {
System.out.println("Please enter a valid float value");
} catch (IOException e) {
e.printStackTrace();
}
} while (validInput == false);
return inFloat;
}
Float.valueOf(String s) will throw a NumberFormatException if it can't parse the input. Catch that one in addition to IOException.
In your code, NumberFormatException is thrown (if the input is invalid) but not catched inside the method, so the method will return immediatly after completing the finally block.