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