Consume bad data in text file java - java

import java.io.*;
import java.util.*;
public class DemoEx {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("BP.txt"));
int badData = 0;
int goodData = 0;
while (in.hasNext()) {
try {
int value = in.nextInt();
if (value < 0)
throw new BPIllegalValueException("value cannot be less than zero");
else goodData++;
} catch (InputMismatchException ex) {
// Consume badData
badData++;
} catch (BPIllegalValueException ex) {
badData++;
}
}
System.out.println("gooddata" + goodData);
System.out.println("baddata" + badData);
}
}
public class BPIllegalValueException extends Exception {
BPIllegalValueException(String message){
System.out.println(message);
}
}
I'm writing a program the reads a txt file and then outputs the number of pieces of "good" and "bad" data with good data being any non-negative integer number and bad data being anything else.
However, I'm not sure how to consume and move to the next piece of data if my program encounters a string.

Loop with a check on encountering the int:
if (in.hasNextInt()) {
... all
} else {
++badData();
in.next();
}

What do You mean by "consume"? You propably want to advance to another token. Reading the documentation should give You the answer:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
next() method will allow You to go to a next token...

Related

What is supertype?

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
//star my method lab
public class Method extends JPanel {
//two array lists that I am going to use.
ArrayList<String> english = new ArrayList<>();
ArrayList<String> french = new ArrayList<>();
//bring text file as an array
public void loadEnglishWords() {
//input my file
String filename = "english.txt";
File f = new File(filename);
try {
Scanner s = new Scanner(f);
//scan all array line by line
while (s.hasNextLine()) {
String line = s.nextLine();
english.add(line);
}
} catch (FileNotFoundException e) { //wrong file name makes error massage pop up
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!",JOptionPane.ERROR_MESSAGE);
}
}
//same array job with English to compare
public void loadFrenchWords() {
String filename = "french.txt";
File f = new File(filename);
try {
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
String line = s.nextLine();
french.add(line);
}
} catch (FileNotFoundException e) {
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!",JOptionPane.ERROR_MESSAGE);
}
}
//check each line to parallel my arrays to get to same position
public String lookup(String word){
for (int i = 0; i < english.size();i++) {
if (word.equals(english.get(i))) {
return french.get(i);
}
}
//wrong values in arrays
return "No match found";
}
//infinite loop to run my program until get the result
public void mainLoop() {
while (true) {
//pop-up box to ask English words
String tmp = JOptionPane.showInputDialog("Please Enter an English Word!");
//store the result in variable r
String r = lookup(tmp);
String a;
//
if (r == ("No match found")) {
a = "Write a Right Word!";
} else {
a = "The French word is : " + r + ". Play agian?";
}
//asking want to play more or not
int result;
result = JOptionPane.showConfirmDialog(null,a,"RESULT!",JOptionPane.YES_NO_OPTION);
//doens't want to play then shut down
if (result == JOptionPane.NO_OPTION) {
break;
}
}
}
//make all things run in order
#Override
public void init() {
loadEnglishWords();
loadFrenchWords();
mainLoop();
}
}
//My problem is that everytime I compile this program the error message would be:
"Method.java:88: error: method does not override or implement a method from a supertype
#Override
^
1 error"
//This program is to translate french words to english words using arraylist
I`m using a .txt file for my set of english and french words and have it run through arraylist to translate
//In my program I need to use a JPanel or pop-up box to ask the user to input the word that they wish to translate
//Please note that I am a beginner with Java, please somebody help me and point out on where I got it wrong so I can change it. Thank you so much!
What the error is saying is that in line 88, you are using the #Override to redefine a method named init from parent class JPanel. But because JPanel is what it is (i.e. a part of Java), it does not have init method, you can not redefine it, hence the error. Most likely, you should just remove the #Override, which will mean you want to add a new method instead of redefining it.
Inheritance is a mechanism where you take an existing class and modify it according to your needs. In your case, your class is named Method and it extends (inherits from) JPanel, so JPanel is the supertype of your class.
If you're just beginning, go read and educate yourself on object-oriented concepts. There are many tutorials, including YouTube videos. Happy learning!
Aside from what was previously mentioned, you need to change a few things:
public void init() { should be public static void main(String args[]) {
Then you need to make your methods static, i.e.
public static void loadEnglishWords() {
Also, the arrayLists need to also be static
And one other thing, you should compare with .equals() and not ==
I've re-written your code slightly and now it should work:
static ArrayList<String> english = new ArrayList<>();
static ArrayList<String> french = new ArrayList<>();
//bring text file as an array
public static void loadEnglishWords() {
//input my file
try {
Scanner s = new Scanner(new File("english.txt"));
//scan all array line by line
while (s.hasNextLine()) {
String line = s.next();
english.add(line);
}
} catch (FileNotFoundException e) { //wrong file name makes error massage pop up
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!", JOptionPane.ERROR_MESSAGE);
}
}
//same array job with English to compare
public static void loadFrenchWords() {
try {
Scanner s = new Scanner(new File("french.txt"));
while (s.hasNextLine()) {
String line = s.nextLine();
french.add(line);
}
} catch (FileNotFoundException e) {
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!", JOptionPane.ERROR_MESSAGE);
}
}
//check each line to parallel my arrays to get to same position
public static String lookup(String word) {
for (int i = 0; i < english.size(); i++) {
if (word.equals(english.get(i))) {
return french.get(i);
}
}
//wrong values in arrays
return "No match found";
}
//infinite loop to run my program until get the result
public static void mainLoop() {
while (true) {
//pop-up box to ask English words
String tmp = JOptionPane.showInputDialog("Please Enter an English Word!");
//store the result in variable r
String r = lookup(tmp);
String a;
//
if (r.equals("No match found")) {
a = "Write a Right Word!";
} else {
a = "The French word is : " + r + ". Play agian?";
}
//asking want to play more or not
int result;
result = JOptionPane.showConfirmDialog(null, a, "RESULT!", JOptionPane.YES_NO_OPTION);
//doens't want to play then shut down
if (result == JOptionPane.NO_OPTION) {
break;
}
}
}
//make all things run in order
public static void main(String args[]) {
loadEnglishWords();
loadFrenchWords();
mainLoop();
}
}

Avoiding nested try/catch

import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String str = input.next();
int a;
try{
try{
a = Integer.parseInt(str);
}
catch(NumberFormatException nfe){
throw new CustomException("message");
}
if (a>50) throw new CustomException("message");
}
catch(CustomException e){
//do something
}
}
}
If str is something other than numbers, parseInt will throw a NumberFormatException. But I want to 'convert' it so that I'll have a CustomException with "message" instead. Can I do this without using a nested try/catch blocks like above?
you could refator your example to
try {
a = Integer.parseInt(str);
if (a > 50) {
throw new CustomException("message");
}
} catch (NumberFormatException | CustomException e){
//do something
}
Use the Scanner.hasNextInt() to parse the int without worrying about exceptions.
see this question for detailed code.
You could write:
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String str = input.next();
int a;
try{
a = Integer.parseInt(str);
if (a>50) throw new NumberFormatException("message");
}
catch(NumberFormatException e){
//do something
}
}
but I suggest you to use your version, since the code is more readable. My version, even if removes the inner try, is less readable than yours.

Required: variable Found:value Error Java Text-Based Calculator

Hello Stack Overflow.
I have a problem with my code. The goal is to create a text-based calculator that reads an input file and processes the equations. The first number tells the program how many lines are there. I think I set up that part right, count is the number of lines. Here's what I got so far.
Scanner equationScan;
int count;
double a=0;
double b=0;
double calc1;
equationScan = new Scanner(new File("calculator.txt"));
count = equationScan.nextInt();
while(count > 0)
{
String line = equationScan.nextLine();
if(line.equals("sin"))
{
a = equationScan.nextDouble(); *Error shows up here. Req: variable Found: value
Math.sin(a)= calc1;
}
}
The goal is a number of 'if' statements for the program to follow. I understand that part, but I can't get past this error. The first line of the text file reads an integer and I'm trying to see the second line of the file that reads sin of a double and to calculate that and store it. Help would be greatly appreciated!
Changes are in comment.
package calculator;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class calc {
public static void main(String[] args) {
Scanner equationScan = null;
int count;
double a=0;
double b=0;
double calc1;
try { //optional: add a try catch block to catch FileNotFoundException exception
equationScan = new Scanner(new File("calculator.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count = equationScan.nextInt();
equationScan.nextLine(); //add a nextline() according to what TOM pointed
while(count > 0)
{
String line = equationScan.nextLine();
if(line.equals("sin"))
{
String value=equationScan.nextLine(); //Parse the double to a string
a=Double.parseDouble(value);
calc1 = Math.sin(a) ; //Assignment should be at the right sign of the = operator
}
}
}
}
Assignments are always in the format
variable = value;
And what you did is write the value you are calculating on the left hand side of the assignment operator =, and the variable you want to put the value in, on the right side.

Delete else statement but requires else statment

So basically I'm doing a java tutorial but in order to follow along I need to make a class file. Everything was already given to me but it gives me an error. The error is: Delete else statement or something along those lines. But when I delete it it tells me to put another else statement there.
The code is : Is this a problem with eclipse or is there something wrong with the code?
import java.io.*;
import java.text.*;
public class In {
static InputStreamReader r = new InputStreamReader(System.in);
static BufferedReader br = new BufferedReader(r);
// Read a String from the standard system input
public static String getString() {
try {
return br.readLine();
} catch (Exception e) {
return "";
}
}
// Read a number as a String from the standard system input
// and return the number
public static Number getNumber() {
String numberString = getString();
try {
numberString = numberString.trim().toUpperCase();
return NumberFormat.getInstance().parse(numberString);
} catch (Exception e)
{
// if any exception occurs, just return zero
return new Integer(0);
}
}
// Read an int from the standard system input
public static int getInt() {
return getNumber().intValue();
}
// Read a long from the standard system input
public static long getLong() {
return getNumber().longValue();
}
// Read a float from the standard system input
public static float getFloat() {
return getNumber().floatValue();
}
// Read a double from the standard system input
public static double getDouble() {
return getNumber().doubleValue();
}
// Read a char from the standard system input
public static char getChar() {
String s = getString();
if (s.length() >= 1)
return s.charAt(0);
else
return’\ n’;
}
}
What is actually causing the error here is that whatever messed up marks you have around \n are not apostrophes... I have no idea what they are. After rewriting the code exactly as you did, except with apostrophes (plus using curly braces in the if and else statements because I prefer it that way), there were no errors:
public static char getChar ()
{
String s = getString();
if (s.length() >= 1){
return s.charAt(0);
}else{
return '\n';
}
}
Please, in the future, make sure to use correct indentations in your questions to make it much easier for us to read.

Error: cannot find symbol for Exceptions in Java

I am writing a very simple program in Java that tries to divide 10 by a user-entered number and catches a DivideByZeroException. Here is the code:
public class EnhancedCatchExceptions6 {
public static void main(String[] args) {
System.out.println();
for (int i = 0 ; i < i; i++) {
try {
int b = Input.getInt("Enter an integer to divide by:");
divide(10, b);
break;
} catch (DivideByZeroException e) {
System.out.println("Error: Divided by zero. Try again.\n");
}
}
}
public static int divide(int x, int y) throws DivideByZeroException {
System.out.println();
int result = 0;
try {result = x/y;}
catch (ArithmeticException e) {throw new DivideByZeroException(y);}
return result;
}
}
For some reason is returns an error: cannot find symbol for every 'DivideByZeroException.' If I change DivideByZeroException to Exception it does not return that error. The same error appears when I was writing other programs with other exceptions.
I don't understand why this error is returned and I would appreciate any help. Thanks!
Most likely this is happening because you forget to import your DivideByZeroException. Change the first lines of your class adding:
import your.package.name.DivideByZeroException;
and you should be fine. Do not forget to use real package name of yours, of course.
The other guess - if you want a class that represents an exception and comes with JDK, not your own, consider replacing DivideByZeroException with ArithmeticException.

Categories