Java, method prints both options from if/else - java

Hi this is some code I've constructed for a project which calls several other methods to print a statement about the person. My problem is its printing in double and appears to be running through both if/else statements.
How can I prevent this? if needed I can add the text from my terminal. Code below;
void printPersonDescription(String name, boolean sex, int age) {
if(sex == true && yearsUntilNextMaturityLevel(age) > 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" she has " + yearsUntilNextMaturityLevel(age) + " years left until she is " +
nextMaturityLevel(age) + ".");
}
else if(sex == false && yearsUntilNextMaturityLevel(age) > 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" he has " + yearsUntilNextMaturityLevel(age) + " years left until he is " +
nextMaturityLevel(age) + ".");
}
if (sex == true && yearsUntilNextMaturityLevel(age) <= 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" she has " + yearsUntilNextMaturityLevel(age) + " year left until she is " +
nextMaturityLevel(age) + ".");
}
else {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" he has " + yearsUntilNextMaturityLevel(age) + " year left until he is " +
nextMaturityLevel(age) + ".");
}
}

Note how similar your four cases are. You are just changing some words in the line you print. Those four if/else blocks can be simplified to this:
void printPersonDescription(String name, boolean sex, int age) {
int years = yearsUntilNextMaturityLevel(age);
String gender = sex ? "she" : "he";
String plural = years > 1 ? "s" : "";
println(name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" " + gender + " has " + years + " year" + plural + " left until " + gender + " is " +
nextMaturityLevel(age) + ".");
}
Also, you can make the println a bit more readable by using String.format (assuming that the maturity levels are strings)
String.format("%s is %s. At %d %s has %d year%s left until %s is %s.",
name, getMaturityLevel(age), age, gender, years, plural, gender,
nextMaturityLevel(age))

Third if condition should be else if in your code to avoid double printing.
Instead of:
if (sex == true && yearsUntilNextMaturityLevel(age) <= 1) {
Use:
else if (sex && yearsUntilNextMaturityLevel(age) <= 1) {
btw you don't need to use if (boolVar == true) you can just use if (boolVar)

void printPersonDescription(String name, boolean sex, int age) {
if(sex == true && yearsUntilNextMaturityLevel(age) > 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" she has " + yearsUntilNextMaturityLevel(age) + " years left until she is " +
nextMaturityLevel(age) + ".");
}
else if(sex == false && yearsUntilNextMaturityLevel(age) > 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" he has " + yearsUntilNextMaturityLevel(age) + " years left until he is " +
nextMaturityLevel(age) + ".");
}
else if (sex == true && yearsUntilNextMaturityLevel(age) <= 1) {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" she has " + yearsUntilNextMaturityLevel(age) + " year left until she is " +
nextMaturityLevel(age) + ".");
}
else {
println (name + " is " + getMaturityLevel(age) + ". " + "At " + age +
" he has " + yearsUntilNextMaturityLevel(age) + " year left until he is " +
nextMaturityLevel(age) + ".");
}
}
You need add else before the third if. Otherwise, the final else statement will match the third if, thus, the else statement means
if(sex != true || yearsUntilNextMaturityLevel(age) > 1)

Related

A compiling Error I cannot figure out in BlueJ

I am getting the ')' expected error when I try to compile on one of my print f statements. The project is to write an application that will run on cash registers in a pizza restaurant. Here is the section of code. The problem line is the one inside the double asterisks. Any ideas?
System.out.println();
System.out.println (" Order Summary ");
System.out.println (" *************************");
System.out.println ();
if(NofTopp = 0){
System.out.printf( Size + ", " + crust + " Cheese Pizza : $%.2f", cost);
System.out.println();
}else if(NofTopp = 1){
System.out.printf( Size + ", " + crust + " Pizza with " + Top1 + ": $%.2f", cost);
System.out.println();
}else if(NofTopp = 2){
**System.out.printf (Size + ", " + crust + " Pizza with " + Top1 + " and " + Top2 ": $%.2f",
cost);**
System.out.println();
}else if(NofTopp = 3){
System.out.printf( Size + ", " + crust + " Pizza with " + Top1 + ", " + Top2 + " and " + Top3 +
": $%.2f", cost);
System.out.println();
}
System.out.printf ("Tax: $%.2f",SalesTax );
System.out.println();
System.out.printf ("Total: $%.2f",totalCost );
System.out.println();
I think you forgot a + before the ": $%.2f". Try:
System.out.printf (Size + ", " + crust + " Pizza with " + Top1 + " and " + Top2 + ": $%.2f", cost);

Cannot find item in database when one column is null

I have a program which requires me to input the ID of a product and then will search a database in order to display details about that specific product.
The code works fine for every item in the database except productID 2 and productID 4 because they have no data stored in one of the columns (PRODUCT_TYPE).
I've got an if statement in my code which says:
else if (result.getString("PRODUCT_TYPE") == null && result.getString("DESCRIPTION ") == null)
{
System.out.println("Item ID: " + result.getString("STOCKITEM") + ". \nProduct name: " + result.getString("PRODUCT") + ". \nCost: £" + result.getString("COST") + ". \nStock level: " + result.getString("STOCKLEVEL") + ". \nProduct type: null.");
}
But I cannot figure out why it's unable to find the product if Product type is null but can still find it if description is null.
try{
String searchCode = "SELECT PRODUCTS.PRODUCT, PRODUCTS.COST, PRODUCTS.DESCRIPTION, PRODUCT_STOCK.STOCKITEM , PRODUCT_STOCK.STOCKLEVEL FROM PRODUCT_TYPE INNER JOIN (PRODUCTS FULL OUTER JOIN PRODUCT_STOCK ON PRODUCTS.PRODUCTID = PRODUCT_STOCK.STOCKITEM) ON PRODUCT_TYPE.PRODTYPEID = PRODUCTS.PRODUCT_TYPE WHERE PRODUCTID = " + inputValue + ";";
// sql statement searches the database for the required data
Statement statement = dbConnection.createStatement();
ResultSet result = statement.executeQuery(searchCode);
boolean found = false;
found = result.next();
if (!found) { //if no data is found then display the error message and restart the product search method
System.out.println("That product couldn't be found, please try again.");
searchProduct();
}
else if (result.getString("PRODUCT_TYPE") == null && result.getString("DESCRIPTION ") == null)
{
System.out.println("Item ID: " + result.getString("STOCKITEM") + ". \nProduct name: " + result.getString("PRODUCT") + ". \nCost: £" + result.getString("COST") + ". \nStock level: " + result.getString("STOCKLEVEL") + ". \nProduct type: null.");
}
else if (result.getString("PRODUCT_TYPE") == null && result.getString("DESCRIPTION") != null){
System.out.println("Item ID: " + result.getString("STOCKITEM") + ". \nProduct name: " + result.getString("PRODUCT") + ". \nCost: £" + result.getString("COST") + ". \nStock level: " + result.getString("STOCKLEVEL") + ". \nDescription: " + result.getString("DESCRIPTION") + ". \nProduct type: null.");
}
else if (result.getString("PRODUCT_TYPE") != null && result.getString("DESCRIPTION") == null){
System.out.println("Item ID: " + result.getString("STOCKITEM") + ". \nProduct name: " + result.getString("PRODUCT") + ". \nCost: £" + result.getString("COST") + ". \nStock level: " + result.getString("STOCKLEVEL") + ". \nDescription: null. \nProduct type: " + result.getString("PRODTYPE_DESC") + ".");
}
else if (result.getString("PRODUCT_TYPE") != null && result.getString("DESCRIPTION") != null){
System.out.println("Item ID: " + result.getString("STOCKITEM") + ". \nProduct name: " + result.getString("PRODUCT") + ". \nCost: £" + result.getString("COST") + ". \nStock level: " + result.getString("STOCKLEVEL") + ". \nDescription: " + result.getString("DESCRIPTION") + ". \nProduct type: " + result.getString("PRODTYPE_DESC") + ".");
}
}
catch (Exception e){ // if the product can't be found then display the error message and restart the product search method
System.out.println("Could not find product.");
System.out.println(e.toString());
searchProduct();
}
//goes back to menu once the method has finished
askUser();
}
Any help would be massively appreciated. Thanks.
Do you have a typo?
result.getString("DESCRIPTION ") == null
Should be
result.getString("DESCRIPTION") == null
Note the extra space in "Description " in your current version.

random walk across 10x10 grid array

The purpose of this program is to build a 10x10 array grid made out of periods (.), allow the user to designate a starting point, and then the program will randomly choose numbers which are assigned to directions for the 'walker' to go. Each time it moves it marks its spot with the next letter in the alphabet (the starting point is marked by A). I haven't done this part yet but I know how I will; if the walker crosses out of the bounds of the array (AKA > 10 or < 0) it will say "you were arrested" and if the variable alpha == 'Z' it way say "You made it home".
The main problem as far as I can tell is with the method processing(), where I draw numbers from getRand (which I have confirmed is working) and then assign them directions which are given to the array. But for some reason when it prints the grid it only shows the starting point, and not the movement of the walker.
Another question I have of lesser importance is if there is a more brief way to display my grid than how I have been (A massive brick of text in a System.out.print)
package walktester;
import java.lang.Math;
import java.util.Random;
import java.util.Scanner;
class DrunkWalker {
private char[][] walkgrid = new char[10][10];
private static int randNSEW;
private int randomnum;
private int startrow;
private int startcol;
private char alpha = 'A';
private int nextrow;
private int nextcol;
public DrunkWalker(int r, int c) {
startrow = r;
startcol = c;
nextrow = startrow;
nextcol = startcol;
for (int i = 0; i < 10; i ++) {
for (int j = 0; j < 10; j++)
walkgrid[i][j] = '.';
}
walkgrid[r][c] = alpha;
}
public static void getRand(){
int x100 = 0;
double randomNum = 0.0;
randomNum = Math.random();
x100 = (int) (randomNum * 100);
randNSEW = x100 % 4;
}
public int getNextRow(){
return nextrow;
}
public int getNextCol(){
return nextcol;
}
public void processing(){
for(int i = 0; i < 26; i ++){
getRand();
if(randNSEW == 0){
nextcol--;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 1){
nextrow++;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 2){
nextcol++;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 3){
nextrow--;
walkgrid[nextrow][nextcol] = alpha++;
}
}
}
public char[][] DisplayGrid() {
System.out.print(
walkgrid[0][0] + " " + walkgrid[0][1] + " " + walkgrid[0][2] + " " + walkgrid[0][3] + " " + walkgrid[0][4] + " " + walkgrid[0][5] + " " + walkgrid[0][6] + " " + walkgrid[0][7] + " " + walkgrid[0][8] + " " + walkgrid[0][9] + "\n" +
walkgrid[1][0] + " " + walkgrid[1][1] + " " + walkgrid[1][2] + " " + walkgrid[1][3] + " " + walkgrid[1][4] + " " + walkgrid[1][5] + " " + walkgrid[1][6] + " " + walkgrid[1][7] + " " + walkgrid[1][8] + " " + walkgrid[1][9] + "\n" +
walkgrid[2][0] + " " + walkgrid[2][1] + " " + walkgrid[2][2] + " " + walkgrid[2][3] + " " + walkgrid[2][4] + " " + walkgrid[2][5] + " " + walkgrid[2][6] + " " + walkgrid[2][7] + " " + walkgrid[2][8] + " " + walkgrid[2][9] + "\n" +
walkgrid[3][0] + " " + walkgrid[3][1] + " " + walkgrid[3][2] + " " + walkgrid[3][3] + " " + walkgrid[3][4] + " " + walkgrid[3][5] + " " + walkgrid[3][6] + " " + walkgrid[3][7] + " " + walkgrid[3][8] + " " + walkgrid[3][9] + "\n" +
walkgrid[4][0] + " " + walkgrid[4][1] + " " + walkgrid[4][2] + " " + walkgrid[4][3] + " " + walkgrid[4][4] + " " + walkgrid[4][5] + " " + walkgrid[4][6] + " " + walkgrid[4][7] + " " + walkgrid[4][8] + " " + walkgrid[4][9] + "\n" +
walkgrid[5][0] + " " + walkgrid[5][1] + " " + walkgrid[5][2] + " " + walkgrid[5][3] + " " + walkgrid[5][4] + " " + walkgrid[5][5] + " " + walkgrid[5][6] + " " + walkgrid[5][7] + " " + walkgrid[5][8] + " " + walkgrid[5][9] + "\n" +
walkgrid[6][0] + " " + walkgrid[6][1] + " " + walkgrid[6][2] + " " + walkgrid[6][3] + " " + walkgrid[6][4] + " " + walkgrid[6][5] + " " + walkgrid[6][6] + " " + walkgrid[6][7] + " " + walkgrid[6][8] + " " + walkgrid[6][9] + "\n" +
walkgrid[7][0] + " " + walkgrid[7][1] + " " + walkgrid[7][2] + " " + walkgrid[7][3] + " " + walkgrid[7][4] + " " + walkgrid[7][5] + " " + walkgrid[7][6] + " " + walkgrid[7][7] + " " + walkgrid[7][8] + " " + walkgrid[7][9] + "\n" +
walkgrid[8][0] + " " + walkgrid[8][1] + " " + walkgrid[8][2] + " " + walkgrid[8][3] + " " + walkgrid[8][4] + " " + walkgrid[8][5] + " " + walkgrid[8][6] + " " + walkgrid[8][7] + " " + walkgrid[8][8] + " " + walkgrid[8][9] + "\n" +
walkgrid[9][0] + " " + walkgrid[9][1] + " " + walkgrid[9][2] + " " + walkgrid[9][3] + " " + walkgrid[9][4] + " " + walkgrid[9][5] + " " + walkgrid[9][6] + " " + walkgrid[9][7] + " " + walkgrid[9][8] + " " + walkgrid[9][9] + "\n"
);
return walkgrid;
}
}
public class WalkTester {
public static void main(String[] args) {
Scanner inpr = new Scanner(System.in);
Scanner inpc = new Scanner(System.in);
Scanner inpchoice = new Scanner(System.in);
int r = 0;
int c = 0;
char choice = 'y';
while(choice == 'y' || choice == 'Y') {
System.out.println("Please enter x coordinate between 1 and 10.");
r = inpr.nextInt();
r = r - 1;
System.out.println("Please enter y coordinate between 1 and 10");
c = inpr.nextInt();
c = c - 1;
if(r < 0 || r > 9 || c < 0 || c > 9){
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
if(choice == 'y' || choice == 'Y'){
continue;
}
else if(choice == 'n' || choice == 'N'){
return;
}
else{
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
}
}
DrunkWalker drunkwalker = new DrunkWalker(r, c);
drunkwalker.DisplayGrid();
System.out.println("Restart? y/n");
choice = inpchoice.next().charAt(0);
if(choice == 'y' || choice == 'Y'){
continue;
}
else if(choice == 'n' || choice == 'N'){
return;
}
else{
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
}
}
}
}
The code that moves the walker is in a method called processing(), but you never call it.
You can make your DisplayGrid() method simpler (and it will still print the same stuff):
public char[][] DisplayGrid() {
for(int y = 0; y < 10; y++) {
for(int x = 0; x < 10; x++) {
System.out.print(walkgrid[x][y] + " ");
}
System.out.println();
}
return walkgrid;
}
Your processing() method needs to check if the walker leaves the bounds of the area. If you don't, you'll get an ArrayIndexOutOfBoundsException.
public boolean processing(){
for(int i = 0; i < 26; i ++){
getRand();
if(randNSEW == 0){
nextcol--;
}
if(randNSEW == 1){
nextrow++;
}
if(randNSEW == 2){
nextcol++;
}
if(randNSEW == 3){
nextrow--;
}
if(nextrow < 0 || nextrow >= 10 || nextcol < 0 || nextcol >= 10) {
return false;
}
walkgrid[nextrow][nextcol] = alpha++;
}
return true;
}
Now you need to call processing() and check the return value to see if the walker succeeded:
DrunkWalker drunkwalker = new DrunkWalker(r, c);
boolean walkerSucceeded = drunkwalker.processing();
drunkwalker.DisplayGrid();
if(walkerSucceeded) {
System.out.println("You made it home");
} else {
System.out.println("You were arrested");
}
And keep in mind (as you will see when you test this), that the walker can cross their own tracks (so you might see some letters missing).

How to skip/not run a code in java

bSub.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(t1.getText().equals("Name") || t2.getText().equals("Section") || t3.getText().equals("Age")){
JOptionPane.showMessageDialog(null, "Please fill in the incomplete fields");
}
//If the 'if statement' above is true, these code below will not execute
t8.setText(t1.getText() + " of " + t2.getText() + " -- " + t3.getText() + " years old");
t9.setText(t1.getText() + " of " + t2.getText() + " -- " + t3.getText() + " years old");
t10.setText(t1.getText() + " of " + t2.getText() + " -- " + t3.getText() + " years old");
t11.setText(t1.getText() + " of " + t2.getText() + " -- " + t3.getText() + " years old");
t12.setText(t1.getText() + " of " + t2.getText() + " -- " + t3.getText() + " years old");
}
});
Is it possible to tell the compiler to skip a code if the 'If Statement' is true?
Place the other code in an else:
public void actionPerformed(ActionEvent e){
if(t1.getText().equals("Name") || t2.getText().equals("Section") || t3.getText().equals("Age")){
JOptionPane.showMessageDialog(null, "Please fill in the incomplete fields");
} else {
//If the 'if statement' above is true, these code below will not execute
t8.setText(t1.getText() + " of " + t2.getText() + " -- " + t3.getText() + " years old");
t9.setText(t1.getText() + " of " + t2.getText() + " -- " + t3.getText() + " years old");
t10.setText(t1.getText() + " of " + t2.getText() + " -- " + t3.getText() + " years old");
t11.setText(t1.getText() + " of " + t2.getText() + " -- " + t3.getText() + " years old");
t12.setText(t1.getText() + " of " + t2.getText() + " -- " + t3.getText() + " years old");
}
}
You may skip by return keyword:
if(t1.getText().equals("Name") || t2.getText().equals("Section") || t3.getText().equals("Age")){
JOptionPane.showMessageDialog(null, "Please fill in the incomplete fields");
return;
}

Writing the resultset to csv file

I have a method getstaffinfo, which has 3 parameter (var_1, connection, filewriter fw), the var_1 value is read from a text file. So the method will be called as many times based on all the var_1 value passed from text file . approx ( 15000)
public static String getstaffid(String var_1, Connection connection,
FileWriter fw) throws SQLException, Exception
// Create a statement
{
String record = null;
ResultSet rs = null;
Statement stmt = connection.createStatement();
boolean empty = true;
try {
rs = stmt
.executeQuery("select username, firstname, lastname, middlename, street, city, stateorprovince, ziporpostalcode, countryorregion, fax, phone, extension, mobile, pager, title, primaryemail, secondaryemail, officename, description, comments, suspendeddate, userdata, employeeid, createuser, updateuser, createdate, updatedate, employeetype, servicedeskticketnumber, startdate, enddate, manager, businessapprover, technicalapprover, delegate, location, jobcodes, customproperty1, customproperty2, customproperty3, customproperty4, customproperty5, customproperty6, customproperty7, customproperty8, customproperty9, customproperty10 from globalusers where username = '"+ var_1 + "'");
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList<String> records = new ArrayList<String>();
while (rs.next()) {
empty = false;
//record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4) + " " + rs.getString(5) + " " + rs.getString(6) + " " + rs.getString(7) + " " + rs.getString(8) + " " + rs.getString(9) + " " + rs.getString(10) + " " + rs.getString(11) + " " + rs.getString(12) + " " + rs.getString(13) + " " + rs.getString(14) + " " + rs.getString(15) + " " + rs.getString(16) + " " + rs.getString(17) + " " + rs.getString(18) + " " + rs.getString(19) + " " + rs.getString(20) + " " + rs.getString(21) + " " + rs.getString(22) + " " + rs.getString(23) + " " + rs.getString(24) + " " + rs.getString(25) + " " + rs.getString(26) + " " + rs.getString(27) + " " + rs.getString(28) + " " + rs.getString(29) + " " + rs.getString(30) + " " + rs.getString(31) + " " + rs.getString(32) + " " + rs.getString(33) + " " + rs.getString(34) + " " + rs.getString(35) + " " + rs.getString(36) + " " + rs.getString(37) + " " + rs.getString(38) + " " + rs.getString(39) + " " + rs.getString(40) + " " + rs.getString(41) + " " + rs.getString(42) + " " + rs.getString(43) + " " + rs.getString(44) + " " + rs.getString(45) + " " + rs.getString(46) + " " + rs.getString(47);
for (int i = 1; i <= columns; i++) {
String value = rs.getString(i);
records.add(value);
}
for (int j = 0; j < records.size(); j++) {
record = records.get(j) + ",";
}
fw.append(record);
}
/*fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append('\n'); */
} finally {
fw.flush();
rs.close();
stmt.close();
}
return record;
}
As you can see, am executing a query for 47 values, which could be null or it can have some value.
Then i iterate through this 47 column, take the value and store it to an array list. Then i iterate the array list and write all the values to the string record with comma seperated value. Which is written to a csv file.
But it does not work fine. Any inputs would be appreciated...
You may have already solved the problem. Just let you know that I tried to use your code just now and found the issue was here:
record = records.get(j) + ",";
You should use something like this:
record = record + records.get(j) + ",";
Also change String to StringBuffer will improve the performance.
You didn't write the exact problem you face, but there is one for sure: you never write a line break into the file, so all data gets in one line.
while (rs.next()) {
... // your code, with the for loops
fw.append(record); //writing out the line, from your code
fw.append("\r\n"); //line break -- add this line
} //this is the end of the "while(rs.next())" loop
...

Categories