I just started to learn Java, so have a lot of questions. And now I need to return to the beginning of program if a problem occurs.
public static int getchartoint() throws IOException {
int a;
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
String k = bReader.readLine();
a = Integer.parseInt(k);
return a;
}
catch (NumberFormatException exc) {
System.out.println(exc);
return a = 0;
}
finally {
}
}
and I have a = 0, I could write case in main() body:
case 0: {
System.out.println("Your entered an incorrect number...");
}
My question is: how can I add a line that moves me to exactly that line of code?
Call the "getchartoint" method before your switch/case statements.
Then when it returns integer 0 it will execute the case statement.
It looks like you just want to return 0; instead of return a=0;.
Related
Is there a way to create a regex, that will check for proper 'closure' of a checkstyle (which begins with //)?
// CHECKSTYLE:OFF
protected void doSomething() {
}
// CHECKSTYLE:ON
// CHECKSTYLE:OFF
protected void doSomethingElse() {
// CHECKSTYLE:ON
}
If there is a typo in the first CHECKSTYLE:ON, the rest of checkstyles will be ignored.
I don't know if a pure regex would be appropriate here. Your problem is the really the stuff with which parsers are concerned. Actually, I don't even know how we would detect // CHECKSTYLE:ON with a typo in it. But, one option here would be to simply scan your file line by line, and fail if we ever encounter two // CHECKSTYLE:OFF in a row. If that happens, then it implies that either the ON checkstyle was completely omitted, or it was mispelled.
static final String CHECK_ON = "// CHECKSTYLE:ON";
static final String CHECK_OFF = "// CHECKSTYLE:OFF";
File file = new File("your_input.ext");
boolean checkstyleIsOn = false;
try {
Scanner sc = new Scanner(file);
int lineNum = 0;
while (sc.hasNextLine()) {
++lineNum;
String line = sc.nextLine();
if (CHECK_OFF.equals(line)( {
if (!checkStyleIsOn) {
System.out.println("Found extra checkstyle off at line " + lineNum);
break;
}
else {
checkStyleIsOn = false;
}
}
if (CHECK_ON.equals(line)( {
if (checkStyleIsOn) {
System.out.println("Found extra checkstyle on at line " + lineNum);
break;
}
else {
checkStyleIsOn = true;
}
}
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
I'm trying to validate german postcodes in a input form.
But somehow i get stuck in line 15 and my function is just printing "Give me input" in an endless loop.
I expected that sc_plz.nextLine() would be a blocking function but somehow it's not.
import View.AddressView;
import java.io.IOException;
import java.util.Scanner;
public class AddressController {
AddressView view = new AddressView();
public Address addAddress()throws IOException{
//other input questions
Scanner sc_plz = new Scanner(System.in);
int code = 0;
while (!validatePostcode(code))
view.askPostcode(); //simple System.out.println("Input something")
String postcode = sc_plz.nextLine();
try {
code = Integer.parseInt(postcode);
}
catch (NumberFormatException e){
view.invalidData(); //warning about not got a number
}
//other input questions
}
private boolean validatePostcode(int plz) throws IOException {
//legal postcodenumbers are between 01000 -99999
if (1000 <= plz && plz <= 99999){
return true;
}
else {
return false;
}
}
}
Did you forget brackets for your while statement? As it is right now it will always do whatever is in view.askPostcode();. I imagine this is what it should look like:
while (!validatePostcode(code)) {
view.askPostcode(); //simple System.out.println("Input something")
String postcode = sc_plz.nextLine();
try {
code = Integer.parseInt(postcode);
} catch (NumberFormatException e){
view.invalidData(); //warning about not got a number
}
}
My project need to parse two type of text data into database.
one format is like this:
<lineNumber>19</lineNumber>
<begin>
2013-08-15,2013-08-15,pek001,123456,08654071,CANX,,,,,,011
<end>
one is like that
<lineNumber>27</lineNumber>
<begin>
2012-11-02,08683683,pek001,00001234,vvip,1
<end>
the difference of the two text is between the begin and end tag.
so our parsing code come out:
first one is:
inputStreamReader = new InputStreamReader(new FileInputStream(FileOne),"gbk"); --different place
br=new BufferedReader(inputStreamReader);
lineNumber = 0;
boolean isDataContent = false;
while (br.ready()) {
String line = br.readLine();
if(line == null){
continue;
}
if(line.contains("<lineNumber>"))
{
try {
lineNumber = Integer.parseInt(StringTools.getDigitalInString(line));
} catch (NumberFormatException e) {
log.error("there is no lineNumber。");
}
continue;
}
if(line.trim().equals("<begin>"))
{
isDataContent = true;
continue;
}
if(line.trim().equals("<end>"))
{
break;
}
if(isDataContent)
{
insertFirstToDatabase(line,vo); --just this is different.
}
}
second one is :
inputStreamReader = new InputStreamReader(new FileInputStream(FileTwo),"gbk");
--different place
br=new BufferedReader(inputStreamReader);
lineNumber = 0;
boolean isDataContent = false;
while (br.ready()) {
String line = br.readLine();
if(line == null){
continue;
}
if(line.contains("<lineNumber>"))
{
try {
lineNumber = Integer.parseInt( StringTools.getDigitalInString(line));
} catch (NumberFormatException e) {
log.error("there is no lineNumber");
}
continue;
}
if(line.trim().equals("<begin>"))
{
isDataContent = true;
continue;
}
if(line.trim().equals("<end>"))
{
break;
}
if(isDataContent)
{
insertSecondToDatabase(line,vo); --only this is different.
}
}
The two piece of code is in two different service code. How can I refactor this reduplicate code? so that each place Just only call one same function to check the lineNumber.
Have the duplicated code in a class that both the other classes either inherit (inheritance) or include a copy of (composition). Alternatively you could even make it a static method in a utility class.
Your code is identical until a single statement, and it's not shown how you determined which of these sequences of code you should be executing, but just move that branching into the if (isDataContent):
// copy/paste from your own, change the if to:
if(isDataContent) {
if (flagFirst) {
insertFirstToDatabase(line,vo); --just this is different.
} else {
insertSecondToDatabase(line,vo); --only this is different.
}
}
Where flagFirst is either a boolean variable or a boolean expression to determine which of the inserts should be done.
You can add 'kind' parameter for selecting usded inserting method as following:
public void process(int kind) {
....
while (br.ready()) {
String line = br.readLine();
if(line == null){
continue;
}
if(line.contains("<lineNumber>"))
{
try {
lineNumber = Integer.parseInt( StringTools.getDigitalInString(line));
} catch (NumberFormatException e) {
log.error("there is no lineNumber");
}
continue;
}
if(line.trim().equals("<begin>"))
{
isDataContent = true;
continue;
}
if(line.trim().equals("<end>"))
{
break;
}
if(isDataContent)
{
if (kind == 1) {
insertFirstToDatabase(line,vo); --just this is different.
}
if (kind == 2) {
insertSecondToDatabase(line,vo); --only this is different.
}
}
}
}
2 things:
duplicated code? - put in static method in utility class
how to differentiate dataContent? -
i. this can be determined while parsing the line depending on the order of fields
(or)
ii. the callee of the static method can determine the same by sending a flag. But this is not good design. You are placing too much implementation i.e. 2 behaviors in a utility method.
(or)
iii. Let the static method parse the XML and return just the line details to the callee. Let the callee handle however it likes. First callee might just want to print, second callee might want to put into db.
So, here it goes,
public static LineDetails parseXML(String filename)
{
inputStreamReader = new InputStreamReader(new FileInputStream(new File(filename));
br=new BufferedReader(inputStreamReader);
lineNumber = 0;
boolean isDataContent = false;
LineDetails lineDetails = new LineDetails();
while (br.ready()) {
String line = br.readLine();
if(line == null){
continue;
}
if(line.contains("<lineNumber>"))
{
try {
lineNumber = Integer.parseInt( StringTools.getDigitalInString(line));
} catch (NumberFormatException e) {
log.error("there is no lineNumber");
}
lineDetails.setLineNumber(lineNumber);
continue;
}
if(line.trim().equals("<begin>"))
{
isDataContent = true;
continue;
}
if(line.trim().equals("<end>"))
{
break;
}
if(isDataContent)
{
// parse line
lineDetails.setLine(line);
}
}
return lineDetails;
}
public class LineDetails
{
private int lineNumber=0;
private String line="";
// getters setters
}
//First callee
methodA()
{
LineDetails lineDetails = parseXML(filename);
if(lineDetails!=null && lineDetails.getLineNumber==19 && lineDetails.getLine()!=null && !lineDetails.getLine.equals(""))
{
insertFirstToDatabase(line);
}
}
//Second callee
methodB()
{
LineDetails lineDetails = parseXML(filename);
if(lineDetails!=null && lineDetails.getLineNumber==27 && lineDetails.getLine()!=null && !lineDetails.getLine.equals(""))
{
insertSecondToDatabase(line);
}
}
I am trying to write a try catch block like the following, but put it inside a loop. My issue is that when i put it in a while loop, it runs x amount of times. i want it to stop when the first try is successful. but give the option to run up to 3 times.
try {
myDisplayFile();
} catch (FileNotFoundException e1) {
System.out.println("could not connect to that file..");
e1.printStackTrace();
}
public static void myDisplayFile() throws FileNotFoundException{
Scanner kin = new Scanner(System.in);
System.out.print("Enter a file name to read from:\t");
String aFile = kin.nextLine();
kin.close();
Scanner fileData = new Scanner(new File(aFile));
System.out.println("The file " + aFile + " contains the following lines:");
while (fileData.hasNext()){
String line = fileData.next();
System.out.println(line);
}//end while
fileData.close();
}
int max_number_runs = 3;
boolean success = false;
for( int num_try = 0 ; !success && num_try < max_number_runs ; num_try++ )
{
try
{
/* CODE HERE */
success = true;
}
catch( Exception e )
{
}
}
int someCounter = 0;
boolean finished = false;
while(someCounter < 3 && !finished) {
try {
//stuff that might throw exception
finished = true;
} catch (some exception) {
//some exception handling
someCounter++;
}
}
You can break; within a try catch block and it will exit the loop that it's in (not just the try catch block), but from a readability stand point, this posted code might be better.
finished = true should be the final line of the try block. It won't throw an exception. And it will only execute if every other line of the try block executed without an exception. So if you get to finished = true, you didn't throw and exception, so you can toggle your flag and exit the loop.
Otherwise, if an exception is thrown, the finished = true; line won't execute. You'll deal with the exception, then increment the someCounter++ variable.
This is ideal from a readability standpoint because all possible while loop exits are marked in the conditional part of the while loop. The loop will continue until either someCounter is too large, or finished returns true. So if I'm reading your code, all I have to do is look through your loop for the parts where these variables are modified, and I can quickly understand the loop logic, even if I don't yet understand everything the loop is doing. I don't have to hunt for break; statements.
I hope I understood your problem correctly. Here's a way.
int noOfTries = 0;
boolean doneWithMyStuff = false;
final int MAX_LOOP_VAL = 10;
int noOfLoops = 0;
while(noOfTries < 3 && noOfLoops < MAX_LOOP_VAL && !doneWithMyStuff) {
try {
// Do your stuff and check success
doneWithMyStuff = true;
}
catch (Exception e) {
noOfTries++;
e.printStackTrace();
}
finally {
// Close any open connections: file, etc.
}
noOfLoops++;
}
I get an error message as follows: Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at emp.MainClass.main(MainClass.java:52)
Using the following code, how do I alleviate this problem?
public class MainClass {
//main class
public static void main(String[] args){
// variable
String input;
boolean salaryError = true;
boolean dependentError = true;
boolean nameError = true;
boolean charError = true;
Employee emp1 = new Employee();
displayDivider("EMPLOYEE INFORMATION");
do{
input = getInput(" First Name");
nameError = nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setfirstName(input);
do{
input = getInput(" Last Name");
nameError =nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setlastName(input);
do{
input = getInput(" Gender: M or F");
charError = characterChecker(input.charAt(0));
if(!charError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!charError);
char g = input.charAt(0);
emp1.setgender(g);// validates use of M or F for gender
do{
input = getInput(" number of dependents");
dependentError = integerChecker(input);
if(!dependentError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!dependentError);
emp1.setdependents(Integer.parseInt(input));
do{
input = getInput(" annual salary");
salaryError = doubleChecker(input);
if(!salaryError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
} while(!salaryError);
emp1.setannualSalary(Double.parseDouble(input));
emp1.displayEmployee();//displays data for emp1
Employee emp2 = new Employee("Speed","Racer",'M',1,500000.00);
displayDivider("EMPLOYEE INFORMATION");
emp2.displayEmployee();// displays data for emp2
terminateApplication(); //terminates application
System.exit(0);//exits program
}//end of main
// gets Input information
public static String getInput(String data)
{
String input = "";
input = javax.swing.JOptionPane.showInputDialog(null,"Enter your " + data);
return input;
}// end getInput information
// The display divider between employees
public static void displayDivider(String outputLab)
{
System.out.println("********" + outputLab + "********");
}// end display divider
// Terminates the application
public static void terminateApplication()
{ javax.swing.JOptionPane.showMessageDialog(null,"Thanks for the input!");
}// end terminateApplication
public static boolean doubleChecker(String inStr){
boolean outBool = true;
double tmpDbl = 0.0;
try{
tmpDbl = Double.parseDouble(inStr);
if(tmpDbl <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean integerChecker(String intStr){
boolean outBool = true;
int tmpInt = 0;
try{
tmpInt = Integer.parseInt(intStr);
if(tmpInt <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean nameValidate(String str){
for(char ch : str.toCharArray()){
if(!Character.isDigit(ch)){
return true;
}
}
return false;
}
public static boolean characterChecker(char gen){
boolean outBool = true;
try{
if(!( gen ==( 'M') || gen ==('F')))
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
}//end of Main Class
Your string is length 0. Make sure string.length() > 0 before accessing its elements. The problem is at the line the exception says the problem is on.
Better answer: are you using an IDE? If so, observe the line the exception tells you you have an error on. Set a breakpoint before that line, debug, and note the contents of the object on which the error happened (in this case the string). Then check the javadoc for the method that threw the exception to see if there is any problem calling that method on that string.
If you are not using an IDE, you will either need to use one or find a standalone debugger. Having a good debugger is a requirement of Java development.
This should save you a lot of SO questions going forward.
StringIndexOutofBoundsException means you're try to access the String using an index and the index is either negative or greater than the size of the string.
You're wrong in this part:
charError = characterChecker(input.charAt(0));
Because you're not check if the input length is 0.
Try to change that line to this:
charError = input != null && input.length() > 0 && characterChecker(input.charAt(0));