Condition based returns for a toString() - java

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");
}

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.

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

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);
}

.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());
}
}
}

Formatting a return string

I am trying to format this return string to display ratings at one decimal place.
return String.format(title + "," + genre + "," + releaseYear + "(" + (getRating() == -1 ? "No ratings" : getRating()) + "): " + numOfDeaths + " deaths");
I keep getting an error saying too few parameters passed.
You want java.text.DecimalFormat.
DecimalFormat df = new DecimalFormat("0.0##");
String result = df.format(getRating());
return String.format(title + "," + genre + "," + releaseYear + "(" + (getRating() == -1 ? "No ratings" : result) + "): " + numOfDeaths + " deaths");

how to deserialize unknown named array json using gson

The json looks like this :
"hour_totals": {
"382423": {
"imp": 126,
"clk": 1,
"spend": "$0.03",
"conv": 0,
"cpm": "$0.22",
"cpc": "$0.03",
"ctr": "0.79%",
"cpa": "$Inf"
},
"382424": {
"imp": 209,
"clk": 1,
"spend": "$0.05",
"conv": 0,
"cpm": "$0.23",
"cpc": "$0.05",
"ctr": "0.48%",
"cpa": "$Inf"
}}
I read more than 20 answers, but unable to find how to deserialize such a structure, please help on what would the class look like since the hour is not a fixed string.
To parse this JSON with Gson you need two steps.
Define this classes:
public class Total {
Map<String, HourData> hour_totals;
#Override
public String toString() {
return "Total [hour_totals=" + hour_totals + "]";
}
}
where HourData is
public class HourData {
Integer imp;
Integer clk;
String spend;
Integer conv;
String cpm;
String cpc;
String cpa;
#Override
public String toString() {
return "HourData [imp=" + imp + ", clk=" + clk + ", spend=" + spend
+ ", conv=" + conv + ", cpm=" + cpm + ", cpc=" + cpc + ", cpa="
+ cpa + "]";
}
}
Hack a bit your "Json string" since it's not a valid Json (see more details below). You just need to add braces like this code:
public class Q19201300 {
public static void main(String[] args) {
String json = "\"hour_totals\": { "
+ " \"382423\": { "
+ " \"imp\": 126, "
+ " \"clk\": 1, "
+ " \"spend\": \"$0.03\", "
+ " \"conv\": 0, "
+ " \"cpm\": \"$0.22\", "
+ " \"cpc\": \"$0.03\", "
+ " \"ctr\": \"0.79%\", "
+ " \"cpa\": \"$Inf\" "
+ "}, "
+ "\"382424\": { "
+ " \"imp\": 209, "
+ " \"clk\": 1, "
+ " \"spend\": \"$0.05\", "
+ " \"conv\": 0, "
+ " \"cpm\": \"$0.23\", "
+ " \"cpc\": \"$0.05\", "
+ " \"ctr\": \"0.48%\", "
+ " \"cpa\": \"$Inf\" "
+ "}} ";
Total t = new Gson().fromJson("{" + json + "}", Total.class);
System.out.println(t);
}
}
This will give you:
Total [hour_totals={382423=HourData [imp=126, clk=1, spend=$0.03,
conv=0, cpm=$0.22, cpc=$0.03, cpa=$Inf], 382424=HourData [imp=209,
clk=1, spend=$0.05, conv=0, cpm=$0.23, cpc=$0.05, cpa=$Inf]}]
About your string. From JSON official grammar (http://www.ietf.org/rfc/rfc4627.txt):
JSON Grammar
A JSON text is a sequence of tokens. The set of tokens includes
six structural characters, strings, numbers, and three literal
names.
A JSON text is a serialized object or array.

Categories

Resources