Java Printing out exceptions thrown and no exceptions throw in different places - java

I was not sure how to formulate the title however I have the following problem. I'm making a program which reads out things out of a CSV file and types it out. In a file where there are no problem I get my results normally. When I run my other file which has errors thrown my program still prints out the things I have in catch but not in a order I want it to- I want to put all parts with errors throw on top and the ones which have no errors on the bottom of the print. How can i do that?
This is the code I currently have
String []arrayS = line.split(",");
if(arrayS.length==7){
String fName = "";
String lName = "";
//String
int bDay;
int bMonth;
int bYear;
int weight;
double height;
try{
//System.out.printf("%15s%15s%15s%15s \n", fnlName , birthDate, sWeight, sHeight);
fName = arrayS[0];//gets first line in csv- name
lName = arrayS[1];//gets second line in csv- last name
try{
bDay = Integer.parseInt(arrayS[2].trim());//gets third line in csv- birth day
}catch (NumberFormatException nfe){
System.err.println("Error found in" + arrayS[0] + ", " + arrayS[1] + ", " + arrayS[2] + ", " + arrayS[3] + ", " + arrayS[4] + ", " + arrayS[5] + ", " + arrayS[6] +"\n Offending item is: Birth day");
continue;
}try{
bMonth = Integer.parseInt(arrayS[3].trim());//gets four line in csv- birth month
}catch (NumberFormatException nfe){
System.err.println("Error found in" + arrayS[0] + ", " + arrayS[1] + ", " + arrayS[2] + ", " + arrayS[3] + ", " + arrayS[4] + ", " + arrayS[5] + ", " + arrayS[6] +"\n Offending item is: Birth month");
continue;
}try{
bYear = Integer.parseInt(arrayS[4].trim());//gets fifth line in csv- birth year
}catch (NumberFormatException nfe){
System.err.println("Error found in" + arrayS[0] + ", " + arrayS[1] + ", " + arrayS[2] + ", " + arrayS[3] + ", " + arrayS[4] + ", " + arrayS[5] + ", " + arrayS[6] +"\n Offending item is: Birth year");
continue;
}try{
weight = Integer.parseInt( arrayS[5].trim());//gets sixth line in csv- weight
}catch (NumberFormatException nfe){
System.err.println("Error found in" +arrayS[0] + ", " + arrayS[1] + ", " + arrayS[2] + ", " + arrayS[3] + ", " + arrayS[4] + ", " + arrayS[5] + ", " + arrayS[6] +"\n Offending item is: Weight");
continue;
}try{
height = Double.parseDouble(arrayS[6].trim());//gets seventh line in csv- height
}catch (NumberFormatException nfe){
System.err.println("Error found in" + arrayS[0] + ", " + arrayS[1] + ", " + arrayS[2] + ", " + arrayS[3] + ", " + arrayS[4] + ", " + arrayS[5] + ", " + arrayS[6] +"\n Offending item is: Height");
continue;
}
System.out.printf("%15s%15s%02d/%02d/%4d %d %.1f\n" , fName , lName , bDay , bMonth , bYear , weight , height);
}catch(NumberFormatException nfe ){
System.out.println("Cannot read student:" + fName);
continue;
}}```

Do not write the output directly to System.out and System.err but instead collect them first. You can use different approaches like using a List<String> or use a StringBuilder. When you have read the CSV file completely you can finally output the result you have collected at the end, first the errors and then the error-free entries. The code can look like this:
List<String> errors = new ArrayList<String>();
List<String> output = new ArrayList<String>();
while (/*reading a line */) {
/* [...] */
try {
/* [...] */
output.add(String.format("...", a, b, c, d, ...);
} catch (...) {
errors.add(...);
}
}
// now show the result, but show the errors first
if (!errors.isEmpty()) {
System.err.println("There were errors:");
for (String str: errors) {
System.err.println(str);
}
}
System.out.println("Your result");
for (String str: output) {
System.out.println(str);
}

Related

How can I print something based on the result of a boolean method?

I have two methods
*`public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}`*
validateMarks(): Used to validate qualifying exam marks - qualifying marks is in the range of 65 to 100(both inclusive)
validateCourseId(): Used to validate the course entered, based on the courseId - given in the table above
calculateCourseFee(): Used to calculate the course fee after applying the discount.
So when is less than 65 print print "not elegible, you've failed" and when the course is not valid "course is not correct, please try again with the correct number of the course"
and this is my calculateCourseFee method
***if(this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("Wroog for course");
}
***
I make two different ifs for the two requirements, but everytime I run it, it prints the else statement to, even if marks is greather than 65... am I missing something?
Reviewing my code and tell me what am I missing or what am I doing wrong
The portion of the code you have shown here seems to be working as expected.
public class Driver {
public static void main(String args[]) {
Eligible e1 = new Eligible();
e1.calculateCourseFee();
}
}
class Eligible{
int qualifyingMarks = 66;
int courseId = 1002;
public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}
public void calculateCourseFee(){
if(this.validateMarks()) {
System.out.println("works for marks");
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
System.out.println("works for course");
}else {
System.out.println("Wroog for course");
}
}
}
output:
works for marks
works for course
Maybe the issues is with how you set the values for the qualifyingMarks and courseId variables?
I wish I could give you a like or thumbs up, I finally did it, thanks to all of your answers you gave me, and I just combined the two ifs into one. here's the code:
if(this.validateCourseId() && this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else if(!this.validateCourseId()) {
System.out.println("Wrong course");
}
else if(!this.validateMarks()) {
System.out.println("You've failed");
}
Thanks everyone!!
maybe qualifyingMarks is zero or another value, print qualifyingMarks in method "validateMarks",u will get the reason of your problem.

Condition based returns for a toString()

Here is my toString
#Override
public String toString() {
return
"Name: " + name +
" Date of birth: " + dateOfBirth + " Serial number: " + userSerialNumber +
" Gold Status: " + if(goldStatus == true){ return " Gold" } else {return "Standard"};
}
The last phrase is what I've tried, but I get a "java: illegal start of expression" compiler error. How do I make this code compilable?
#Override
public String toString() {
return
"Name: " + name +
" Date of birth: " + dateOfBirth + " Serial number: " + userSerialNumber +
" Gold Status: " + (goldStatus ? " Gold" : "Standard");
}

How to prompt user to enter which [row][column]

I want the user to enter which row and which column in order to read the data in it
for example if the user enter row = 6 column = 0, it will print out Pw1
static String fullChessBoard[][] = {
{"Rb1", "Kb1", "Bb1", "Qb1", "Ab1", "Bb2", "Kb2", "Rb2"},
{"Pb1", "Pb2", "Pb3", "Pb4", "Pb5", "Pb6", "Pb7", "Pb8"},
{" ", " ", " ", " ", " ", " ", " ", " "},
{" ", " ", " ", " ", " ", " ", " ", " "},
{" ", " ", " ", " ", " ", " ", " ", " "},
{" ", " ", " ", " ", " ", " ", " ", " "},
{"Pw1", "Pw2", "Pw3", "Pw4", "Pw5", "Pw6", "Pw7", "Pw8"},
{"Rw1", "Kw1", "Bw1", "Qw1", "Aw1", "Bw2", "Kw2", "Rw2"},
};
System.out.println(Player1W + ", please make a move");
int row = scan.nextInt();
int column = scan.nextInt();
Try this code
import java.util.Scanner;
public class HelloChess{
static String fullChessBoard[][] = {
{"Rb1", "Kb1", "Bb1", "Qb1", "Ab1", "Bb2", "Kb2", "Rb2"},
{"Pb1", "Pb2", "Pb3", "Pb4", "Pb5", "Pb6", "Pb7", "Pb8"},
{" ", " ", " ", " ", " ", " ", " ", " "},
{" ", " ", " ", " ", " ", " ", " ", " "},
{" ", " ", " ", " ", " ", " ", " ", " "},
{" ", " ", " ", " ", " ", " ", " ", " "},
{"Pw1", "Pw2", "Pw3", "Pw4", "Pw5", "Pw6", "Pw7", "Pw8"},
{"Rw1", "Kw1", "Bw1", "Qw1", "Aw1", "Bw2", "Kw2", "Rw2"},
};
public static void main(String []args){
Scanner scan = new Scanner(System.in);
System.out.print("Enter Row: ");
int row = scan.nextInt();
System.out.print("Enter Column: ");
int column = scan.nextInt();
System.out.println("Result : "+fullChessBoard[row][column]);
scan.close();
}
}
I'm assuming this program you are writing is a command line program, where the user puts information into the command prompt and your program responds. If it's not, please let me know, as my answer operates under that assumption.
There's more than one way to get input from the command line in Java. The following link has a few great examples:
[https://www.geeksforgeeks.org/ways-to-read-input-from-console-in-java/][1]
Here's a quick example I chalked up that outputs the first repeated letter from a string the user enters, it uses the BufferedReader class set to get input from the System.in object wrapped by an InputStreamReader. I'm sure that sounds complicated, but the code explains it better:
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Set;
import java.util.TreeSet;
public class FirstRecurringCharacter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your string: ");
String toAnalyze = reader.readLine();
returnFirstRecurring(toAnalyze);
}
private static Character returnFirstRecurring(String toAnalyze) {
String toSearch = toAnalyze;
Set<Character> seenCharacters = new TreeSet<>();
for (int i = 0; i < toSearch.length(); i++) {
if (seenCharacters.contains(toSearch.charAt(i))) {
System.out.println(toSearch.charAt(i));
return toSearch.charAt(i);
} else {
seenCharacters.add(toSearch.charAt(i));
}
}
System.out.println("No repeating characters.");
return null;
}
}
The .readLine() method gets the users input after they hit enter on the console. Try it yourself!
With your program, you might want to prompt them, one at a time, to insert a row index, then a column index, you can cast their input to integers if needed, and then use them in the remainder of the program. I hope this helps!

.txt array out from user input

I have since updated this code per suggestions for this forum. I am still confused as to how to get my .txt file selection to out print all instances of the name entered. my file in which all my .txt files are contained is named, namesbystate. To access this and all instances of the names entered are where I am getting issues. I am wondering if I replace myFile with namesbystate as a pathway extension or not?
package babynamestatesocial;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class BabyNameStateSocial {
private Scanner x;
public static void main(String[] args) throws FileNotFoundException {
// Scanner variable set up to intake user input for state selection and person's name
Scanner scan = new Scanner(System.in);
System.out.println("Available state files are: \n" +
"AK " + "AL " + "AR " + "AZ " + "CA " + "CO " + "\n" +
"CT " + "DC " + "DE " + "FL " + "GA " + "HI " + "\n" +
"IA " + "ID " + "IL " + "IN " + "KS " + "KY " + "\n" +
"LA " + "MA " + "MD " + "ME " + "MI " + "MN " + "\n" +
"MO " + "MS " + "MT " + "NC " + "ND " + "NE " + "\n" +
"NH " + "NJ " + "NM " + "NV " + "NY " + "OH " + "\n" +
"OK " + "OR " + "PA " + "RI " + "SC " + "SD " + "\n" +
"TN " + "TX " + "UT " + "VA " + "VT " + "WA " + "\n" +
"WI " + "WV " + "WY " + "\n");
System.out.print("Enter a state to read names from: " + "\n");
String filename = scan.nextLine() + ".txt";
System.out.println("Which name would you like to look up?");
String personName = scan.nextLine();
File myFile = new File(filename);
openFile(myFile,personName);
}
private static void openFile(File myFile, String personName){
try {
Scanner sc = new Scanner(myFile);
while (sc.hasNext()) {
// nextLine variable now has the line from the file in it that matches the name the person input
String nextLine = sc.nextLine();
if (nextLine.contains(personName)) {
}
}
} catch(FileNotFoundException e) {
System.out.print(e.getMessage());
}
}
}
Something like this will get you to where you want to be. I do not have the format of your state text files so I couldn't write the full program for you
(Edit - I just changed the code slightly. Instead of sc.next(), I should have written sc.nextLine(). The following program runs successfully with that edit):
package babynamestatesocial;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class BabyNameStateSocial {
private Scanner x;
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println("Available state files are: \n" +
"AK " + "AL " + "AR " + "AZ " + "CA " + "CO " + "\n" +
"CT " + "DC " + "DE " + "FL " + "GA " + "HI " + "\n" +
"IA " + "ID " + "IL " + "IN " + "KS " + "KY " + "\n" +
"LA " + "MA " + "MD " + "ME " + "MI " + "MN " + "\n" +
"MO " + "MS " + "MT " + "NC " + "ND " + "NE " + "\n" +
"NH " + "NJ " + "NM " + "NV " + "NY " + "OH " + "\n" +
"OK " + "OR " + "PA " + "RI " + "SC " + "SD " + "\n" +
"TN " + "TX " + "UT " + "VA " + "VT " + "WA " + "\n" +
"WI " + "WV " + "WY " + "\n");
System.out.print("Enter a state to read names from: " + "\n");
String filename = scan.nextLine() + ".txt";
System.out.println("Which name would you like to look up?");
String personName = scan.nextLine();
File myFile = new File(filename);
openFile(myFile,personName);
}
private static void openFile(File myFile, String personName){
try {
Scanner sc = new Scanner(myFile);
while (sc.hasNext()) {
String nextLine = sc.nextLine();
if (nextLine.contains(personName)) {
//nextLine variable now has the line from the file in it that matches the name the person input so you need to parse that line and do something with it
}
}
} catch(Exception e) {
System.out.print(e.getMessage());
}
}
}

Storing part of method as another method?

Basically, I have code that uses the same few lines in different scenarios, and it makes the code a bit messy (especially since I probably overcomplicated what I made, but that's another issue). What I wanted to do is store that piece of code as another function and calling it in the longer one. WHich should work as far as I know, except, the longer function has variables that aren't set in the shorter one, and if they were, I'm pretty sure it would change the final result of the function.
Here is the longer code:
public static void combat(Character a,Character b){
int battleturn = 1;
int maxTurns=20;
int draw1 = 0;
//stop after 20 turns, or stop when one player has 0 HP.
while (a.health > 0 && b.health > 0 && maxTurns > 0){
/* run a round of combat*/
if (b.health < 0.25 * b.maxHealth){
if (b.getFlee(a)){
System.out.println(">>>>>>>>>>The enemy has fled successfully<<<<<<<<<<");
break;
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + "health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}
}
As you can see there is a part of code that is repeated, and that is.
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
It won't compile if I set that chunk of code as a method, because it doesn't have the variables battleturn, maxturns, draw1, but if I put them in there, the amount of battle turns messes up.
Any ideas?
Java applications should be modular: each class fulfilling its own function, each method generally performing a single operation.
In a method you can use either class variables or its own local variables.
If you need several methods work with the same data, it should either be part of a class (instance and/or static variables) or passed to each method as parameters.
Make sure that you do not define class variables in a method. This will create local variables that will shadow class variables.
This might help you accomplish what you're trying to do.
private static void reportDamage(Character a,
Character b) {
System.out.println(a.name + " dealt "
+ a.combatRound(b) + " damage to " + b.name
+ "." + " Enemy has " + b.getHealth() + "/"
+ b.getMaxHealth() + " health.");
}
I suggest changing your combat method like this.
int battleturn = 0;
int maxTurns = 20;
// stop after 20 turns, or stop when one player has 0
// HP.
Scanner input = new Scanner(System.in);
try {
while (a.health > 0 && b.health > 0
&& battleturn < maxturn) {
battleturn++;
/* run a round of combat */
if (b.getFlee(a)) {
System.out.println(">>>>>>>>>>"
+ "The enemy has fled successfully"
+ "<<<<<<<<<<");
break;
} else {
System.out.println("Battle turn "
+ battleturn + ", <attack> or <flee>?");
boolean isFlee = false;
boolean isAttack = false;
String move = input.next();
for (;;) {
isAttack = "attack".equalsIgnoreCase(move);
isFlee = "flee".equalsIgnoreCase(move);
if (isFlee || isAttack) {
break;
}
System.out.println("Error: "
+ "Please input <attack> or <flee>.");
move = input.next();
}
if (isAttack) {
reportDamage(a, b);
reportDamage(b, a);
} else { // isFlee
if (a.getFlee(b)) {
System.out.println(">>>>>>>>>>"
+ "You have fled successfully"
+ "<<<<<<<<<<");
break;
} else {
// b is fleeing.
// reportDamage(a, b);
reportDamage(b, a);
}
}
}
}
} finally {
input.close();
}

Categories

Resources