Cannot get a java variable to print - java

I cannot get the variable adjustedCharge to print out (the text is printed but not the value) I have tried to trace but still cannot get it to print properly. No errors are present either.
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
//Declare scanner
Scanner input = new Scanner(System.in);
//Prompt for information
System.out.print("Customer's name:");
String name = input.nextLine();
System.out.print("Customer's address:");
String address = input.nextLine();
System.out.print("Customer's phone number:");
String phone = input.nextLine();
System.out.print("Customer's licence number:");
String licence = input.nextLine();
System.out.print("Customer's credit card number:");
String ccard = input.nextLine();
System.out.print("Credit card expiry date (MM/YYYY):");
String expiry = input.nextLine();
System.out.print("Hire length (in days):");
int hire = Integer.parseInt(input.nextLine());
System.out.print("Make/Model:");
String model = input.nextLine();
System.out.print("Registration of car:");
String rego = input.nextLine();
System.out.print("Hire rate (per day) Either S, M, L:");
char inputRate = input.nextLine().charAt(0);
System.out.print("Total days hired out:");
int totalDays = Integer.parseInt(input.nextLine());
//
double dtotalDays = totalDays;
double surcharge = dtotalDays - hire;
//Daily hire rate / Stage 2
double rate = 0;
if (inputRate == 'S' || inputRate == 's'){
rate = (char) 80.0;
}
if (inputRate == 'M' || inputRate == 'm'){
rate= 110.0;
}
if (inputRate == 'L' || inputRate == 'l'){
rate= 140.0;
}
//Calculate late fees
double penalty = rate * (surcharge * 2);
//Start Stage 3
double dCost=0;
double tCost=0;
StringBuilder dDetail = new StringBuilder("The damage Details are:" + "\n");
StringBuilder tDetail = new StringBuilder("The traffic fines are:" + "\n");
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("<<<Enter one of the following commands:>>>");
System.out.println("A - Damage Repair");
System.out.println("B - Traffic Infringement");
System.out.println("X - Exit Menu");
String schoiceEntry = input.next();
char choiceEntry = schoiceEntry.charAt(0);
//Integer.parseInt(input.nextLine());
double damageCost = 0;
switch (choiceEntry){
case 'A':
case 'a':
input.nextLine();
System.out.println("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.println("Enter the damage cost:");
damageCost = input.nextInt();
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append("-" + damageDetail + "\n");
dCost = dCost + damageCost;
System.out.println("----------------------------------");
break;
case 'B':
case 'b':
input.nextLine();
System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.println("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append("-" + trafficDetail + "\n");
tCost = tCost + trafficCost;
System.out.println("----------------------------------");
break;
case 'X':
case 'x':
quit = true;
System.out.print("***Menu entry has been terminated***" + "\n");
//System.out.printf("Total traffic cost is: %75s\n", "$" + tCost + "\n");
//System.out.printf("Total Damage cost is: %77s\n", "$" + dCost + "\n");
//System.out.printf(tDetail + "\n");
//System.out.print(dDetail + "\n");
break;
default:
System.out.print("Please enter either a valid menu selection (A, B, or X):" + "\n");
break;
}
}
double dhire = hire;
double charge = dhire*rate;
double adjustedCharge = charge + penalty;
//Print summary
System.out.println("---------------------------------------------"+
"------------------------------------------------------\n" +
"***CUSTOMER DETAILS:***\n");
System.out.printf("Name: %93s\n", name);
System.out.printf("Address: %90s\n", address);
System.out.printf("Phone Number: %85s\n", phone);
System.out.printf("Licence Number: %83s\n", licence);
System.out.printf("Credit Card Number: %79s\n", ccard);
System.out.printf("Credit Card Expiry: %79s\n", expiry);
System.out.println( "\n***CAR HIRE DETAILS:***\n");
System.out.printf("Make/Model: %87s\n", model);
System.out.printf("Registration Number: %78s\n", rego);
System.out.printf("Hire Length (days): %79s\n", model);
System.out.printf("Daily Hire Rate: %82s\n", rate);
System.out.printf("Basic Hire Charge: %80s\n\n", charge);
System.out.printf("Days hired: %87s\n", totalDays);
if (totalDays == hire){
System.out.printf("Late Return Surcharge: %76s\n", "$0.00");
}
if (totalDays > hire){
System.out.printf("Late Return Surcharge: %76s\n", + penalty);
}
System.out.printf("Adjusted Hire Charge: %77s\n", "\n", "$" + adjustedCharge + "\n");
System.out.print(dDetail + "\n");
System.out.printf("Total damage cost is: %78" + "s\n", "$" + dCost + "\n");
System.out.printf(tDetail + "\n");
System.out.printf("Total traffic fines incurred: %70s\n", "$" + tCost + "\n");
System.out.printf("Final hire charge: %79s\n", "$" + (adjustedCharge + dCost + tCost));
}
}

I just changed the way you printed out the adjustedCharge so you can still use printf
System.out.printf("Adjusted Hire Charge: %77s","$");
System.out.printf("%.1f",adjustedCharge);
System.out.printf("\n");
With printf you need to format the value you're printing and in this case, because you're trying to print a double, you'll need to format it with %f
I also noticed that my previous answer messed up the spacing you had for the rest of your output. So here's the fixed solution! Just change up the spacing to however you'd like

Or you can
use
Pass two arguments to printf
System.out.printf("Adjusted Hire Charge: %77s\n", "$" + adjustedCharge + "\n")
instead of
System.out.printf("Adjusted Hire Charge: %77s\n", "\n", "$" + adjustedCharge + "\n");

Related

While loop problems in Java

I am having trouble with my while loop. After it executes the third time, it won't take user input it just outputs "Enter your first name". I have tried multiple things but they don't seem to be working. The loop should continue to run until the user types in "No".
I know I'm close!
System.out.print("Would you like to enter another patient? Type Yes or No: ");
String userInput = input.nextLine();
if (userInput.equals("Yes"))
{
while (userInput.equals("Yes"))
{
System.out.print("Enter your first name: ");
String firstName2 = input.nextLine();
System.out.print("Enter your last name: ");
String lastName2 = input.nextLine();
System.out.print("Enter your address: ");
String address2 = input.nextLine();
System.out.print("Enter your city: ");
String city2 = input.nextLine();
System.out.print("Enter your state: ");
String state2 = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip2 = input.nextLine();
System.out.print("Enter amount owed: ");
String amount2 = input.nextLine();
System.out.print("Enter your payment amount: ");
String payment2 = input.nextLine();
System.out.print("Enter the date of payment: ");
String date2 = input.nextLine();
System.out.println("\t\t\t\t\t" + "XYZ Hospital");
System.out.println();
System.out.println("Name Information" + "\t\t\t\t" + "Address" + "\t\t\t\t\t\t" + "Payment");
System.out.println();
System.out.println("Last" + "\t" + "First" + "\t\t\t" + "Address Line 1" + "\t" + "City" + "\t" + "State" + "\t" + "Zip" + "\t" + "Amount Owed" + "\t" + "Payment Amount" + "\t" + "Payment Date");
System.out.println();
System.out.println(lastName2 + " " + firstName2 + "\t" + address2 + " " + city2 + ", " + state2 + " " + zip2 + "\t" + amount2 + "\t\t" + payment2 + "\t\t" + date2);
System.out.print("Would you like to enter another patient? Type Yes or No: ");
}
}
else if (userInput.equals("No"))
{
System.out.println("Goodbye");
}
For these type of programs you can use do-while loops. That runs first time without condition and then you can get input from user in userInput variable.
String userInput;
do{
System.out.print("Enter your first name: ");
String firstName2 = input.nextLine();
System.out.print("Enter your last name: ");
String lastName2 = input.nextLine();
System.out.print("Enter your address: ");
String address2 = input.nextLine();
System.out.print("Enter your city: ");
String city2 = input.nextLine();
System.out.print("Enter your state: ");
String state2 = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip2 = input.nextLine();
System.out.print("Enter amount owed: ");
String amount2 = input.nextLine();
System.out.print("Enter your payment amount: ");
String payment2 = input.nextLine();
System.out.print("Enter the date of payment: ");
String date2 = input.nextLine();
System.out.println("\t\t\t\t\t" + "XYZ Hospital");
System.out.println();
System.out.println("Name Information" + "\t\t\t\t" + "Address" + "\t\t\t\t\t\t" + "Payment");
System.out.println();
System.out.println("Last" + "\t" + "First" + "\t\t\t" + "Address Line 1" + "\t" + "City" + "\t" + "State" + "\t" + "Zip" + "\t" + "Amount Owed" + "\t" + "Payment Amount" + "\t" + "Payment Date");
System.out.println();
System.out.println(lastName2 + " " + firstName2 + "\t" + address2 + " " + city2 + ", " + state2 + " " + zip2 + "\t" + amount2 + "\t\t" + payment2 + "\t\t" + date2);
System.out.print("Would you like to enter another patient? Type Yes or No: ");
userInput = input.nextLine();
}while (userInput.equals("Yes"));
I think the problem is that you are doing the while loop inside the if statement. Try to insert the if inside the loop , like this:
Scanner input=new Scanner(System.in);
System.out.println("enter details");
String answer=input.next();
while(answer.equals("yes")) {
if(answer.equals("yes")) {
System.out.println("name");
String name=input.next();
System.out.println("last name");
String last=input.next();
System.out.println("enter details");
answer=input.next();
} }
System.out.println("bye");
}
You never get out of your loop because userInput only is set once before the loop and is never set inside it, meaning you never change the while condition.
System.out.print("Would you like to enter another patient? Type Yes or No: ");
String userInput = input.nextLine();
if (userInput.equals("Yes")) {
while (userInput.equals("Yes")) {
//your data entry...
System.out.print("Would you like to enter another patient? Type Yes or No: ");
// change userInput here, else, you're never going out of the loop.
// so add this
userInput = input.nextLine();
}
} else if (userInput.equals("No")) {
System.out.println("Goodbye");
}
Although, your solution will probably fit your needs more in this format :
System.out.print("Would you like to enter another patient? Type Yes or No: ");
String userInput = input.nextLine();
while (userInput.equals("Yes")) {
//your data entry...
System.out.print("Would you like to enter another patient? Type Yes or No: ");
userInput = input.nextLine();
}
System.out.println("Goodbye");
This way, while the user enters "Yes", you will get in the loop and get out when he enters something else. If the user enters something else than "yes" from the start, you never get in the loop and close the app right away.
Working Code : Kindly check the Code
import java.util.Scanner;
public class temp {
static String userInput;
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
System.out
.print("Would you like to enter another patient? Type Yes or No: ");
userInput = input.nextLine();
while (userInput.equals("Yes")) { //while loop will iterate till "userInput is equals to Yes"
System.out.print("Enter your first name: ");
String firstName2 = input.nextLine();
System.out.print("Enter your last name: ");
String lastName2 = input.nextLine();
System.out.print("Enter your address: ");
String address2 = input.nextLine();
System.out.print("Enter your city: ");
String city2 = input.nextLine();
System.out.print("Enter your state: ");
String state2 = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip2 = input.nextLine();
System.out.print("Enter amount owed: ");
String amount2 = input.nextLine();
System.out.print("Enter your payment amount: ");
String payment2 = input.nextLine();
System.out.print("Enter the date of payment: ");
String date2 = input.nextLine();
System.out.println("\t\t\t\t\t" + "XYZ Hospital");
System.out.println();
System.out.println("Name Information" + "\t\t\t\t" + "Address"
+ "\t\t\t\t\t\t" + "Payment");
System.out.println();
System.out.println("Last" + "\t" + "First" + "\t\t\t"
+ "Address Line 1" + "\t" + "City" + "\t" + "State" + "\t"
+ "Zip" + "\t" + "Amount Owed" + "\t" + "Payment Amount"
+ "\t" + "Payment Date");
System.out.println();
System.out.println(lastName2 + " " + firstName2 + "\t" + address2
+ " " + city2 + ", " + state2 + " " + zip2 + "\t" + amount2
+ "\t\t" + payment2 + "\t\t" + date2);
System.out
.print("Would you like to enter another patient? Type Yes or No: \n");
userInput = input.nextLine(); // Taking user choice for "Yes" or "No"
if (userInput.equals("No")) {
break; // will Exit loop when user enter "No"
}
}
if (userInput.equals("No")) {
System.out.println("Goodbye");
} else {
System.out.println(" Invalid input :("); // will print when user enter anything other than "Yes" or "No"
}
}
}
You were not taking the input from the user again once you finished
taking data from the user inside the while loop. Also check the code
Comments for more info.
Well the big issue is that you never change the value of userInput after the very first check. So regardless of whether they type "Yes" or "No" at the end of the loop, it will keep looping. You never even give the user the option to input anything at the end of the loop when you ask if they want to enter another patient. Secondly you should probably be checking if they entered "yes, Yes, YES, y" using a to lower function

output formatting Java

my question is simple, how can i get my output to format two values with two decimal places. for whatever reason i cant output the "current balance" & "new balance" with two decimal places. separately they work fine but when together i get a conversion error. is this a rule i'm unaware of? i would like do do this with one action if possible. this is simply a cosmetic issue and all operations perform fine when i take out the formatting.
thanks,
public static void main(String[] args)
{
double min;
int accNum;
char accType;
double bal;
double newBal;
//user inputs
System.out.println("Please enter your account number: ");
accNum = console.nextInt();
System.out.println();
System.out.println("Enter the account type: s(savings) or c(checking)");
accType = console.next().charAt(0);
System.out.println();
//savings v checking
switch (accType)
{
case 's':
case 'S':
System.out.println("Enter the current balance: ");
bal = console.nextDouble();
System.out.println("Enter the minimum balance: ");
min = console.nextDouble();
System.out.println();
if (bal < min)
{
newBal = bal - S_MIN_FEE;
System.out.println("Insufficient Funds (-$10.00)");
}
else
newBal = bal + (bal * S_INT);
System.out.printf("Account #: " + accNum + "\n"
+ "Account Type: Savings" + "\n" + "Current Balance: "
+ "$%.2f%n", bal + "New Balance: $%.2f", newBal);
case 'c':
case 'C':
System.out.println("Enter the current balance: ");
bal = console.nextDouble();
System.out.println("Enter the minimum balance: ");
min = console.nextDouble();
System.out.println();
if (bal < min)
{
newBal = bal - C_MIN_FEE;
System.out.println("Insufficent Funds (-$25.00)");
}
else if (bal < C_BAL_MAX && bal >= min)
newBal = bal + (bal * C_INT);
else
newBal = bal + (bal * C_INT_MAX);
System.out.printf("Account #: " + accNum + "\n"
+ "Account Type: Checking" + "\n" + "Current Balance: "
+ "$%.2f%n", bal + "New Balance: $%.2f%n", newBal);
That is because you put the format first, and only first.
System.out.printf("%.2f %.2f%n", bal, newBal);
This is the same problem/mistake as posted an hour ago. java.util.IllegalFormatConversionException: f != java.lang.String Error

Unsure about the best loop to use

public static void main(String[] args) {
Scanner keybNum = new Scanner(System.in);
Scanner keybStr = new Scanner(System.in);
boolean yn = false;
//Start of program
System.out.println("Welcome to The Currency Exchange Converter");
System.out.print("Are you an Account Holder (y or n)? ");
String AccHolder = keybStr.next();
boolean blnYN = true;
//validation of y/n answer
while (blnYN) {
if (AccHolder.equalsIgnoreCase("y")) {
yn = true;
blnYN = false;
break;
}//if
else if (AccHolder.equalsIgnoreCase("n")) {
yn = false;
blnYN = false;
break;
}//else if
else {
System.out.println("Invalid value entered. Choose either y/n.");
AccHolder = keybStr.next();
}//else
}//while
//Start of menu choices
System.out.println("Please choose from the following menu.");
System.out.println("\n1: Exchange another currency for Sterling");
System.out.println("2: Buy another currency from us");
System.out.println("0: Exit");
System.out.print("Which option? ");
int MenuChoice = keybNum.nextInt();
//Exchange Variables (First option)
double Euro = 1.37;
double USAD = 1.81;
double JapYen = 190.00;
double Zloty = 5.88;
//Buy Variables (Second Option)
double EuroB = 1.21;
double USADB = 1.61;
double JapYenB = 163.00;
double ZlotyB = 4.89;
//First menu choice screen
if (MenuChoice == 1) {
System.out.println("Which of the following currencies do you wish to exchange into sterling?");
System.out.println("Euro - EUR");
System.out.println("USA Dollar - USD");
System.out.println("Japanese Yen - JPY");
System.out.println("Polish Zloty - PLN");
System.out.print("Please enter the three letter currency: ");
//Currency input validation
String CurChoice = "";
boolean isCorrectCurrency = false;
do {
CurChoice = keybStr.next();
isCorrectCurrency = CurChoice.matches("^EUR|USD|JPY|PLN$");
if (isCorrectCurrency) {
System.out.println("");
} else {
System.out.print("Invalid Currency Entered. Please Retry: ");
}
} while (!isCorrectCurrency);
//Exchange amount calculator
System.out.print("Enter the amount you wish to exchange of " + CurChoice + ": ");
double ExcAmount = keybStr.nextInt();
double result = 0.00;
//Selection and calculation of user's input
if (CurChoice.equals("EUR")) {
result = ExcAmount / Euro;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("USD")) {
result = ExcAmount / USAD;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("JPY")) {
result = ExcAmount / JapYen;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("PLN")) {
result = ExcAmount / Zloty;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else {
System.out.println("");
}
DecimalFormat df = new DecimalFormat("#.##");
double commission = 0;
if (ExcAmount < 1000) {
commission = result * 0.02;
} else {
commission = result * 0.01;
}
String stringToPrint = "";
if (!yn) {
stringToPrint = "Commission\t=£" + df.format(commission);
} else {
stringToPrint = "Commission \t= Not charged";
}
System.out.println(stringToPrint);
double netPayment = result - commission;
System.out.println("Total\t\t=£" + df.format(netPayment));
}//if
//Start of second option
else if (MenuChoice == 2) {
System.out.println("Which of the following currencies do you wish to buy from us?");
System.out.println("Euro - EUR");
System.out.println("USA Dollar - USD");
System.out.println("Japanese Yen - JPY");
System.out.println("Polish Zloty - PLN");
System.out.print("Please enter the three letter currency: ");
//Currency input validation
String CurChoice = "";
boolean isCorrectCurrency = false;
do {
CurChoice = keybStr.next();
isCorrectCurrency = CurChoice.matches("^EUR|USD|JPY|PLN$");
if (isCorrectCurrency) {
System.out.println("");
} else {
System.out.print("Invalid Currency Entered. Please Retry: ");
}
} while (!isCorrectCurrency);
System.out.print("Enter the amount you wish to buy in £ of " + CurChoice + ": £");
double BuyAmount = keybStr.nextInt();
double result = 0.00;
//Selection and calculation of user's input
if (CurChoice.equals("EUR")) {
result = BuyAmount * EuroB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else if (CurChoice.equals("USD")) {
result = BuyAmount * USADB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else if (CurChoice.equals("JPY")) {
result = BuyAmount * JapYenB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else if (CurChoice.equals("PLN")) {
result = BuyAmount * ZlotyB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else {
System.out.println("");
}
DecimalFormat df = new DecimalFormat("#.##");
double commission = 0;
if (BuyAmount < 1000) {
commission = result * 0.02;
} else if (BuyAmount >= 1000) {
commission = result * 0.01;
} else {
}
String stringToPrint = "";
if (!yn) {
stringToPrint = "Commission\t= " + df.format(commission) + " " + CurChoice;
} else {
stringToPrint = "Commission \t= Not charged";
}
System.out.println(stringToPrint);
double netPayment = result - commission;
System.out.println("Total\t\t= " + df.format(netPayment) + " " + CurChoice);
}//else if
//Action if the user selects 0 to close the system.
else {
System.out.println("Thank you for visiting.");
}//else
}//main
So I'm not sure about the best loop to use on my program. I want the program to repeat if the user inputted either 1 or 2 at the start of the program. The programs a simple currency exchange converter. Any help?
Ideally, you have a program logic according to:
int choice = 0;
while( (choice = readChoice()) != 0 ){
// process according to choice
// ...
}
Wrap the first menu in a static method:
public static int readChoice()
And add the while statement.
(All of your code would benefit from being structured in methods. It's getting unwieldy as you are adding new features. Remember - I have seen an older version)
Consider a do { } while(...); loop. it should be do {...} while (MenuChoice == 1 || MenuChoice == 2); Make sure MenuChoice is always given a value before reaching the while statement. The do while should surround starting from the line //Start of menu choices and to the bottom.
Also, consider a switch case for the MenuChoice

Nesting another Java If/Else statement to print out when a Wrong Character is Entered

So, I'm having an issue getting my program to print out You must enter either C or F or Y or N depending on the response that is inputted. I have tried putting other if-else statements inside the program, but it does not function correctly and breaks the for loop.
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
// Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
// Response String
String response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("You entered no. Bye.");
}
else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact.");
//case1
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is " + standardCompact + " per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is " + couponCompact + " per day.");
}
}
else if (response.equals("F")) {
System.out.println("You have selected Full-Size. ");
//case 2
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is " + standardFullSize + " per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is " + couponFullSize + " per day.");
}
}
}
}
}
When constructing an if statement, else can be used to handle all other conditions not caught by previous if or else if statements.
int x = 0;
if(x ==1){
System.out.println("1");
}else if(x ==2){
System.out.println("2");
}else{
//execute if none of the other conditionals are true
System.out.println("Other Conditions not met");
}
//Outputs: Other Conditions not met
Consider using a combination of a boolean flag, and 'else' statements. Therefore, if the user does not enter N or Y, set this flag to true. Similarly, if the user does not enter C or F, set this flag to true.
Later, at the end of the for-loop, check this flag. If it is true, print your message. This could be worth a try...
public static void main(String[] args) {
boolean notValidCharacter;
for(int i = 0; i < 4; i++) {
notValidCharacter = false;
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")){
System.out.println("You entered no. Bye. ");
}
else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
//case1
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
}
}
else if(response.equals("F")) {
System.out.println("You have selected Full-Size. ");
//case 2
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
else {
notValidCharacter = true;
}
}
else {
notValidCharacter = true;
}
if (notValidCharacter) {
System.out.println("You must enter either C or F or Y or N");
}
}
}

How to fix the column alignment in my code?

This is just for the sake of formality/neatness. Backlash t (\t), which is all I know, doesn't seem to work very well. Here's my code:
import java.util.Scanner;
public class RegisterStudent {
public static void register() {
System.out.println("----------------------------------------");
System.out.println("Student Class Card Evaluation System");
System.out.println("----------------------------------------");
System.out.println("Personal Data");
Scanner input = new Scanner(System.in);
System.out.print("\tEnter student no.: ");
long studNo = input.nextLong();
System.out.print("\tEnter first name: ");
String fName = input.next();
System.out.print("\tEnter last name: ");
String lName = input.next();
System.out.print("\tEnter course: ");
String course = input.next();
System.out.println();
System.out.println("----------------------------------------");
System.out.println("Subject: Computer Programming 2");
System.out.println("----------------------------------------");
System.out.println();
System.out.print("\tPrelim Grade: ");
double pg = input.nextDouble();
System.out.print("\tMidterm Grade: ");
double mg = input.nextDouble();
System.out.print("\tPrefinal Grade: ");
double pfg = input.nextDouble();
System.out.print("\tFinal Grade: ");
double fg = input.nextDouble();
System.out.println();
System.out.println("----------------------------------------");
double gwa = (pg + mg + pfg + fg)/4;
System.out.println();
System.out.println("Student Evaluated successfully...");
System.out.println("Viewing Report...");
System.out.println();
System.out.println("--------------------------------------------------------------------------------------------");
System.out.println("ID No.\t\t" + "LASTNAME\t\t" + "FIRSTNAME\t\t" + "COURSE\t\t"
+ "PG\t\t" + "MG\t\t" + "PFG\t\t" + "FG\t\t" + "GWA");
System.out.println("--------------------------------------------------------------------------------------------");
System.out.println(studNo + "\t\t" + lName + "\t\t" + fName + "\t\t" + course + "\t\t"
+ pg + "\t\t" + mg + "\t\t" + pfg + "\t\t" + fg + "\t\t" + gwa);
The output should look something like this:
Everything that the user will input should be properly aligned. Please help me fix my program, thanks guys!
My current output is this:
You see it's not properly aligned
Since this is homework, here are a couple of hints:
The printf method on a PrintWriter or PrintStream classes can do alignment. So can String.format and the Formatter class.
Don't use TAB characters (i.e. '\t') for alignment in simple text output if you want the alignment to be portable. Different OSes have different ideas on the "width" of a TAB.
The number of tabs you need on each line of input will be determined by the length of the prompt text which appears first on the line i.e. the shorter the prompt, the more tabs required. Simple trial and error should sort out your output to give you the required result.

Categories

Resources