First, last and sometime middle name detection Java - java

I am trying to write a code to give off the user's name in different formats after they enter it. However, if a user does not have a middle name, the system should print that there was an error. I have it so it works perfectly if the user enters three names but does not work if the user enters two names. Here is my code:
import java.util.Scanner;
public class Assignment3
{
public static void main(String[] args)
{
String fullName;
Scanner in = new Scanner(System.in);
System.out.print ("What are your first, middle, and last names? ");
fullName = in.nextLine();
System.out.println(fullName);
if (fullName.contains(" "))
{
String[] nameParts = fullName.split(" ");
String firstInitial = nameParts[0].substring(0,1).toUpperCase();
String secondInitial = nameParts[1].substring(0,1).toUpperCase();
String thirdInitial = nameParts[2].substring(0,1).toUpperCase();
if (nameParts[2].isEmpty())
{
System.out.println("No Middle Name Detected");
}
else
{
System.out.println ("Your initials are: " + firstInitial + secondInitial + thirdInitial);
String lastVariationOne = nameParts[2].substring(0, nameParts[2].length());
lastVariationOne = lastVariationOne.toUpperCase();
String firstVariationOne = nameParts[0].substring(0, nameParts[0].length());
firstVariationOne = firstVariationOne.substring(0,1).toUpperCase() + firstVariationOne.substring(1, nameParts[0].length());
System.out.println("Variation One: " + lastVariationOne + ", " + firstVariationOne + " " + secondInitial + ".");
String lastVariationTwo = nameParts[2].substring(0, nameParts[2].length());
lastVariationTwo = lastVariationTwo.substring(0,1).toUpperCase() + lastVariationTwo.substring(1, nameParts[2].length());
System.out.println("Variation Two: " + lastVariationTwo + ", " + firstVariationOne);
}
}
else
{
System.out.println("Wrong. Please enter your name properly.");
}
}
}

Instead of this:
if (nameParts[2].isEmpty())
{
System.out.println("No Middle Name Detected");
}
something like
if(nameParts.length != 3)
{
System.out.println("Invalid entry");
}
might be preferrable.
Basically, in the case that there are only two names entered, split() will return an array of length 2, whose elements are accessible by indices 0 and 1.
But in your if condition you attempt to access index 2, which could be out of bounds (it would be OOB for the case where you entered only two names).
To resolve this, you could either (a) try it like you do, but catch the ArrayIndexOutOfBoundsException or (b) check first that split produced a properly sized array, then go from there (this was the approach I took with the change I listed).
I'd suggest (b), but both approaches seem fine.

If you don't input middlename, would the array size be 2?
So there is NO namespart[2].
Just check size of namespart.
#jedwards jedwards's solution is there.

Related

Java Lab Project

So I am currently working on a lab for class. I'll attach the lab below:
For this lab, you will use a series of nested if-else or if-else-if statements in order to convert a Roman Numeral number into its String word form. The numerals we are concerned with are I, II, III, IV, V, VI, VII, VIII, which coincide with One, Two, Three, Four, Five, Six, Seven, Eight. Numbers outside of this range are denied – you must tell the user that they are denied as input.
Your code must not fall for inputs like ‘I am the best roman numeral, ‘IIIlikefish’, or ‘VIII is delicious.’ Those inputs should be denied just like an input outside of I to VIII would be
What are possible ways to avoid falling for fake inputs?
Also, I currently have 8 different if statements, is there a faster way to do this?
import java.util.Scanner;
public class RomanNumeralChecker {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String romanNum;
System.out.println("Please enter a Roman Numeral between the values 1 and 8:");
romanNum = keyboard.next();
if (romanNum.equalsIgnoreCase("I")){
System.out.println(romanNum + " represents the number \"One\"");
}
else if (romanNum.equalsIgnoreCase("II")){
System.out.println(romanNum + " represents the number \"Two\"");
}
else if (romanNum.equalsIgnoreCase("III")){
System.out.println(romanNum + " represents the number \"Three\"");
}
else if (romanNum.equalsIgnoreCase("IV")){
System.out.println(romanNum + " represents the number \"Four\"");
}
else if (romanNum.equalsIgnoreCase("V")){
System.out.println(romanNum + " represents the number \"Five\"");
}
else if (romanNum.equalsIgnoreCase("VI")){
System.out.println(romanNum + " represents the number \"Six\"");
}
else if (romanNum.equalsIgnoreCase("VII")){
System.out.println(romanNum + " represents the number \"Seven\"");
}
else if (romanNum.equalsIgnoreCase("VIII")){
System.out.println(romanNum + " represents the number \"Eight\"");
}
else {
System.out.println("Sorry, but " + romanNum + " is out of the desired range.");
}
}
}
Your code is fine for what you need it to do. There are ways to check for valid entry other than what you have implemented but they may be a bit more involved. Professors tend to become upset (Maybe mines was just a jerk) when student do more than what is required for a coding lab.
In the code shown by #nakano531, there's no way that a "trick input" will work. If it what they input, literally does not match the HashMap, it will prompt them that they have entered an invalid answer. ( Don't have the necessary reputation points to say this under his answer, but I wanted to let you know)
Your code is using
romanNum = keyboard.next();
This will return first word from the given input.But you should use .
romanNum = keyboard.nextLine();
Which will read the entire String provided by the use like the ones( ‘I am the best roman numeral, ‘IIIlikefish’, or ‘VIII is delicious.’) you mentioned.
i Hope this will help you.
https://stackoverflow.com/help/someone-answers
public class answer {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String a0 = sc.nextLine();
String[]a1 = {"I","II","III","IV","V","VI","VII","VIII"};
String[]a2 = {"One","Two","Three","Four","Five","Six","Seven","Eight"};
for(int i=0;i<a1.length;i++) {
if(a0.equals(a1[i])) {
System.out.println(a0+" represent "+a2[i]);
}
else {
System.out.println("You Type smth wrong");
}
}
}
}
Okay, this is where we are now. The issue is I can't get the JOption windows to pop up after taking the users input.
public class RomanNumeralChecker {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String romanNum;
JOptionPane.showInputDialog(null,"Please enter a Roman Numeral between the values 1 and 8: ");
romanNum = keyboard.nextLine();
if (romanNum.charAt(0) == 'I') {
if (romanNum.equalsIgnoreCase("I"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"One\"");
if (romanNum.equalsIgnoreCase("II"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Two\"");
if (romanNum.equalsIgnoreCase("III"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Three\"");
if (romanNum.equalsIgnoreCase("IV"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Four\"");
}
else if (romanNum.charAt(0) == 'V') {
if (romanNum.equalsIgnoreCase("V"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Five\"");
if (romanNum.equalsIgnoreCase("VI"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Six\"");
if (romanNum.equalsIgnoreCase("VII"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Seven\"");
if (romanNum.equalsIgnoreCase("VIII"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Eight\"");
}
else {
JOptionPane.showMessageDialog(null,"Not in valid range.");
}
}
}
You can reduce the number of if statement by using Map.
import java.util.Scanner;
import java.util.*;
public class RomanNumeralChecker {
public static void main(String[] args) {
Map<String, String> m = new HashMap<String, String>();
m.put("I", "One");
m.put("II", "Two");
m.put("III", "Three");
m.put("IV", "Four");
m.put("V", "Five");
m.put("VI", "Six");
m.put("VII", "Seven");
m.put("VIII", "Eight");
System.out.println("Please enter a Roman Numeral between the values 1 and 8:");
Scanner keyboard = new Scanner(System.in);
String romanNum = keyboard.next();
String num = m.get(romanNum);
if (num != null) {
System.out.println(romanNum + " represents the number \"" + num + "\"");
} else {
System.out.println("Sorry, but " + romanNum + " is out of the desired range.");
}
}
}

InputMismatchException: String not recognized

I wrote the piece of Java code below. When running it and typing in any value (either one defined, e.g. latte, or any other, e.g. az integer), I get an InputMismatchException.
As far as I could find answers, this exception means that the input type does not match the expected type. What am I missing, why isn't the code recognizing a String input? Thanks for the supprort.
Cheers, Gabor
package Lesson1;
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
//I define the type of coffees as Strings, plus the order as String as well
String espresso = "espresso";
String americano = "americano";
String cappuccino = "cappuccino";
String latte = "latte";
String order = new String();
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
if (order.equals(choice.next(espresso))) {
System.out.println("Your order: " + espresso);
} else if (order.equals(choice.next(americano))) {
System.out.println("Your order: " + americano);
} else if (order.equals(choice.next(cappuccino))) {
System.out.println("Your order: " + cappuccino);
} else if (order.equals(choice.next(latte))) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}
}
}
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Lesson1.Coffee.main(Coffee.java:22)
You write once in default input, but you're trying to read multiple times using choice.next(..).
One solution is assign your choice in a String before the if-else statement and then check it using equalsIgnoreCase.
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
String picked = choice.next();
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
if (picked.equalsIgnoreCase(espresso)) {
System.out.println("Your order: " + espresso);
} else if (picked.equalsIgnoreCase(americano)) {
System.out.println("Your order: " + americano);
} else if (picked.equalsIgnoreCase(cappuccino)) {
System.out.println("Your order: " + cappuccino);
} else if (picked.equalsIgnoreCase(latte)) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}
I think you are using the Scanner wrong. Trying using the next() method with no parameters to get the user input, and only call it once (instead of inside each if else branch). Like this:
package com.company;
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
//I define the type of coffees as Strings, plus the order as String as well
String espresso = "espresso";
String americano = "americano";
String cappuccino = "cappuccino";
String latte = "latte";
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
String order = choice.next();
if (order.equals(espresso)) {
System.out.println("Your order: " + espresso);
} else if (order.equals(americano)) {
System.out.println("Your order: " + americano);
} else if (order.equals(cappuccino)) {
System.out.println("Your order: " + cappuccino);
} else if (order.equals(latte)) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}
}
}

Why isn't my program returning the value of my expression?

I am currently taking an AP Computer Science class in my school and I ran into a little trouble with one of my projects! The project requires me to create a calculator that can evaluate an expression and then solve it. I have got most of that down, but I ran into a little trouble because my teacher asked me to use a while loop to continuously ask for input and display the answer, and I am stuck on that. To end the program the user has to type in "quit" and I can't use system.exit() or any cheating thing like that, the program has to just run out of code. I have got most of that down too, but I am not able to find a why to return the expression in the Method MethodToReadInput(); Does anyone have any tips?
import java.util.*;
public class Calculator {
public static void main(String[] args) {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
MethodToReadInput();
MethodToTestInput(MethodToReadInput());
}
public static String MethodToReadInput() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
}
else {
return expression;
}
}
public static void MethodToTestInput(String expression) {
while (!expression.equalsIgnoreCase("quit")) {
MethodToReadInput();
MethodtoEvaluateInput(expression);
}
System.out.println("Goodbye!");
}
public static void MethodtoEvaluateInput(String expression) {
if (OperatorFor2OperandExpressions(expression).equals("+")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) + SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("*")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) * SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("-")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) - SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("/")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) / SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("^")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + Math.pow(FirstOperandFor2OperandExpressions(expression),SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("|")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.abs(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("v")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sqrt(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("~")) {
double x = 0.0;
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + (Math.round(OperandFor1OperatorExpressions(expression))+ x));
}
else if (OperatorFor1OperandExpressions(expression).equals("s")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sin(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("c")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.cos(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("t")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.tan(OperandFor1OperatorExpressions(expression)));
}
}
public static double FirstOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static double SecondOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[2];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static String OperatorFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
return OperandOrOperator;
}
public static String OperatorFor1OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
return OperandOrOperator;
}
public static double OperandFor1OperatorExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
}
You need to put the MethodToReadInput and MethodtoEvaluateInput inside a loop. For example:
public static void main(String[] args)
{
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
String input = MethodToReadInput();
while (input != null)//exit the loop and the program when input is null
{
MethodtoEvaluateInput(input);//process the input
input = MethodToReadInput();//ask the user for the next input
}
}
public static String MethodToReadInput()
{
Scanner kb = null;
try
{
kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit"))
{
System.out.println("Goodbye!");
return null;
}
else
{
return expression;
}
}
finally
{//always close the Scanner before leaving the method
if (kb != null)
kb.close();
}
}
Also, you should follow the Java Naming Convention and use shorter names for your methods.
Try to simplify your code, and use do-while-loop instead while-loop should produce a better code, do while will at least do one loop and then inspect the next condition before do the next loop, but while will inspect the condition first, if it is okay, it will do the loop. So here is the code:
public class Calculator {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
String expression = "";
do {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit"))
System.out.println("Goodbye!");
else
MethodtoEvaluateInput(expression);
} while (!expression.equalsIgnoreCase("quit"));
inRn.close();
inSw.close();
}
}
Do this:
public static String MethodToReadInput() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
return "";
}
else {
return expression;
}
By returning an empty string you know what to look for when the user wants to exit. It needs to be an empty string that you return because your method is supposed to return a string. Also adding this return statement is needed because the compiler will complain otherwise because it is possible to reach the end of a non-void function (something that returns something) without actually reaching a return statement (so when you enter the if statement as you have it now). You must specify a return case for all possibilities if you specify a return type. In other words you must always return what you say you will.
There are several things that should be fixed about this.
First, let's answer your actual question. You can have a number of choices.
You can just simply return whatever the user has input. In fact, you may not actually need the method for this. But anyway, if your method returns "quit", the while loop can check while ( ! expression.equals("quit") ) just as it does now.
You could return null. This indicates that "The expression is not an actual expression". Then your while could be while ( expression != null ) which is more efficient than string comparison.
But you have other design issues with your program:
You are calling the same methods again and again to retrieve the same things. Those methods split the string - a relatively heavy operation - again and again. You should probably just have a parseExpression() method that returns your tokens, and then something that tests whether these tokens represent a unary operator or a binary one. Something along the lines of:
String [] tokens = parseExpression( expression );
if ( isUnaryExpression( tokens ) ) {
String operator = tokens[0];
String operand = tokens[1];
// Do something with operator and operand.
} else if ( isBinaryExpression( tokens ) ) {
String operator = tokens[1];
String operand1 = tokens[0];
String operand2 = tokens[2];
// Do something with operator and operands {
} else {
System.err.println( "Bad expression!" );
}
You are calling MethodToReadInput twice from your main. This means it will Read one input, do nothing about it, and then read another one which will be passed to MethodToTestInput. Drop the first call, it's unnecessary.
In the cause of better encapsulation, the main method should actually not even call MethodToReadInput. It should become the responsibility of MethodToTestInput to call that method. So you just call MethodToTestInput() from main without passing a parameter at all.
So the structure should be:
main: Display introduction, call your looping method.
looping method: Call input method. Loop while returned expression is still an expression rather than "quit". Inside the loop, call expression handler method.
expression handler method: Call parseExpression() method, check what the tokens are, do the math.
Finally, about your naming issues:
In Java, we name only classes with an uppercase first letter. Constants are named with all capitals (words separated by underscore). Method names begin with a lowercase letter.
You don't name a method MethodThatDoesThis. You should name it doThis, instead. This makes reading your code easier because it actually describe what is happening. So I'd name the methods something like:
The input method: getNextExpression
The looping method: runCalculator, or doCalculatorMainLoop or something like that.
The expression handler method: parseAndCalculate.
Or something along these lines.

Prompting to print all of that type, and calculate the total of that type

I have a file that is needed to be read:
public static int start_program1(int rcount,int[]reservation_code,int[]fl_number,String[]last_name,String[]first_name,String[]seat_type,double[]seat_cost)
{
String newLine;
try
{
//define a file valuable for Buffered read
BufferedReader Reservation_file = new BufferedReader(new FileReader("reservationx.dat"));
//read lines in file until there are no more lines in the file to read
while ((newLine = Reservation_file.readLine()) != null)
{
//there is a "#" between each data item in each line
StringTokenizer delimiter = new StringTokenizer(newLine,"#");
rcount=rcount+1;
reservation_code[rcount] = Integer.parseInt(delimiter.nextToken());
fl_number[rcount] = Integer.parseInt(delimiter.nextToken());
last_name[rcount] =delimiter.nextToken();
first_name[rcount] =delimiter.nextToken();
seat_type[rcount] =delimiter.nextToken();
seat_cost[rcount] = Double.parseDouble(delimiter.nextToken());
}//while loop
Reservation_file.close();
}//end try
catch (IOException error)
{
//there was an error on the file writing
System.out.println("Error on file read " + error);
}//error on read
return rcount;
}//end start_system1
The file being read (reservations.dat) is simply below: (Wasn't sure of an easier way to post this)
(reservation code#flight number#last name#first name#seat type#seat cost)
1189#1234#Smith#James#coach#299.99#
1190#9876#Jones#Marie#coach#150.00#
1191#2000#Atkins#John#first#789.00#
1192#1000#Gallo#James#first#465.00#
1193#4567#Marion#Kevin#business#300.00#
1194#4444#Johnson#Greg#business#765.99#
1195#8888#Brown#Andrew#first#567.39#
1196#4567#Green#Eric#coach#234.00#
1197#9876#Thomas#Chris#business#1900.99#
1198#7777#Hilling#Cara#first#876.76#
1199#2222#Cole#James#coach#256.99#
1200#9281#Bartko#Grant#business#896.00#
1201#2000#Best#Curtis#first# 543.99#
1202#1000#Campbell#Nicholas#coach#287.00#
1203#4444#Dietz#Merrialyce#coach# 219.00#
1204#9281#Duran#Alexander#business#690.00#
1205#2892#Gurung#Suraj#first# 789.99#
1206#7777#Kumpfmiller#Ryan#first#278.99#
1207#4444#Mccomb#David#coach#451.99#
1208#8888#Mclain#Jaime#coach#199.00#
1209#9876#Mullen#Matthew#coach#189.00#
1210#1234#Nguyen#Tommy#coach#299.00#
1211#1234#Ossler#Aimee#coach#300.00#
1212#7777#Polenavitch#Michael#coach#198.99#
1213#2222#Raymond#Chase#first#908.99#
1214#2222#Rosales#David#coach#216.99#
1215#2892#Schwartz#Dustin#business#987.00#
1216#4444#Short#Samuel#coach#245.99#
1217#8888#Soltis#Josh#coach#178.00#
1218#1234#Webster#Ronald#business#892.00#
1219#1234#Wielock#William#first#589.00#
1220#2892#Bonelli#Andrew#coach#178.00#
1221#4444#Bright#Adam#coach#235.00#
1222#9876#Clymer#Jesse#coach#568.00#
1223#4444#Costello#Michael#coach#200.00#
1234#7777#Currin#Sean#business#908.00#
1225#1000#Farrar#Gary#first#588.00#
1226#1000#Finn#Lynn#business#799.00#
1227#4567#Freise#Brian#coach#254.00#
1228#4567#Huang#Pao-Jen#coach# 199.00#
1229#4567#Kamani#Nelson#coach#150.00#
1230#2000#Loughner#Ryan#coach#175.00#
1231#2000#Menzies#Adam#coach#199.00#
1232#1234#Neupane#Kiran#coach# 135.00#
1233#1234#Nickel#Brandon#first#999.00#
1234#7777#Ropchack#Joseph#first#899.00#
1235#7777#Whitten#Walter#coach#786.99#
1236#4444#Woods#Mary#coach#299.00#
1237#4444#Xing#Zhenli#coach#126.00#
Here is the method, doing the calculation in question:
public static void seat_value(int rcount,int[]reservation_code,int[]fl_number,String[]last_name,String[]first_name,String[]seat_type,double[]seat_cost)
{
int i;
double total=0;
String search_seat = "";
String output = "Enter the Seat Type you are searching for";
search_seat = JOptionPane.showInputDialog(null,
output, " ",
JOptionPane.QUESTION_MESSAGE);
for (i = 0; i <=rcount; ++i) {
//CHECK IF coach, first, or business
if(seat_type[i].equals("coach"))
{
total=total+seat_cost[i];
}
if (seat_type.equals("first"))
{
total=total+seat_cost[i];
}
if(seat_type.equals("business"))
{
total=total+seat_cost[i];
}
}
System.out.println("The total for " +search_seat+ " = " +total);
}
My issue in detail is this: Whenever I have it prompt for a type ("coach", "first", "business")
I cannot figure out how to get it to print ALL reservations of THAT type & TOTAL COST of THAT type?
CURRENTLY GETTING: 2051.97 8900.94 8094.45
ACTUAL TOTALS: 7230.93 8295.11 8138.98
COACH FIRST BUSINESS
PS, you will obviously call these methods
Hope this is explains it well.
Well in this loop:
for (i = 0; i <=rcount; ++i) {
//CHECK IF coach, first, or business
if(seat_type[i].equals("coach"))
{
total=total+seat_cost[i];
}
if (seat_type[i].equals("first"))
{
total=total+seat_cost[i];
}
if(seat_type[i].equals("business"))
{
total=total+seat_cost[i];
}
}
you add the cost to the same total every single time regardless of the seat type. So you will end up with the total of all the seats each time.
Basically heres what you are doing in english:
I am going to go through each customer. For each customer, I will do the following:
If their seat type is coach, add it to the total.
If their seat type is first, add it to the total.
If their seat type is business, add it to the total.
Basically, you are adding every customers ticket price to the total because every customer will satisfy one of the three conditions you are testing.
You should replace the three if statements with the following:
if(seat_type[i].equals(search_seat)) {
total += seat_cost[i];
System.out.println( reservation_code[i] + "," + fl_number[i] + "," + last_name[i] + "," + first_name[i] + "," + seat_type[i] + "," + seat_cost[i]);
}

Incompatible operand types String and char syntax error

**Awesome guys I got this to work correcting my comparisons and my IF statement but I am now working on the console to print the information as on the file. No more error codes however console just says java.io.PrintWriter.....any pointers on how to use outputFile and import javax.swing.JOptionPane ? Corrected code below
import java.io.File;
import java.util.Scanner;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
public class StudentFile {
public static void main(String[] args) throws Exception {
// Declare and initialize variables
String studentSummary = "Student Summary Report";
String eligibleBachelorsReport = "Eligible Bachelors Report";
// input record
String firstName;
String lastName;
String gender;
int age;
String maritalStatus;
// counters
int marriedMen = 0;
int singleMen = 0;
int marriedWomen = 0;
int singleWomen = 0;
// create studentInput to read from StudentFile.txt
File inputFile = new File("StudentFile.txt");
Scanner input = new Scanner(inputFile);
while (input.hasNext()) {
// read name, gender, age, maritalStatus
firstName = input.next();
lastName = input.next();
gender = input.next();
age = input.nextInt();
maritalStatus = input.next();
if (gender.equals("F"))
{
if(maritalStatus.equals("M"))
{
marriedWomen = marriedWomen ++;
}
else {
singleWomen = singleWomen ++;
}
}
else if (maritalStatus.equals("M")){
marriedMen = marriedMen++;
}else{
singleMen = singleMen++;
}
if( age > 30) {
eligibleBachelorsReport += " "+firstName + " "+lastName;
}
System.out.println(firstName + " " + lastName + " " + gender + " " + age + " "
+ maritalStatus);
}
// write studentSummary, eligibleBachelorsReport to StudentReport.txt
PrintWriter outputFile = new PrintWriter("StudentReport.txt");
outputFile.println(studentSummary);
outputFile.println(eligibleBachelorsReport);
// write studentSummary, eligibleBachelorsReport to the console
System.out.println(studentSummary);
System.out.println(eligibleBachelorsReport);
JOptionPane.showMessageDialog(null, outputFile);
input.close();
outputFile.close();
}}
I am trying to get this code to work and I can't seem to figure out what I'm doing wrong. i understand that I am trying to compare the string data in this text file that I've imported/attached to this program but it can't seem to go through.
The code I have is below and the txt file that I have imported is labeled StudentFile.txt and has three rows of information in the following order: name, gender, age, marital status
Ex: Mick Jagger M 22 S
What am I doing wrong and why do I keep getting syntax errors? I'm using easy eclipse and I can generally find what I've done wrong with this by using their debugger but I'm kinda stuck. Please help! thx
import java.io.File;
import java.util.Scanner;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
public class StudentFile {
public static void main(String[] args) throws Exception {
// Declare and initialize variables
String studentSummary = "Student Summary Report";
String eligibleBachelorsReport = "Eligible Bachelors Report";
// input record
String firstName;
String lastName;
String gender;
int age;
String maritalStatus;
// counters
int marriedMen = 0;
int singleMen = 0;
int marriedWomen = 0;
int singleWomen = 0;
// create studentInput to read from StudentFile.txt
File inputFile = new File("StudentFile.txt");
Scanner input = new Scanner(inputFile);
while (input.hasNext()) {
// read name, gender, age, maritalStatus
firstName = input.next();
lastName = input.next();
gender = input.next();
age = input.nextInt();
maritalStatus = input.next();
if (gender.equals(F)){
}if maritalStatus.equals(M)){
marriedWomen = marriedWomen ++;
} else {
singleWomen = singleWomen ++;
}else{
}if maritalStatus.equals(M)){
marriedMen = marriedMen ++
}else{
singleMen = singleMen ++
if age > 30 {
eligibleBachelorsReport += ""firstName + ""lastName
}
System.out.println(firstName + " " + lastName + " " + gender + " " + age + " "
+ maritalStatus);
}
// write studentSummary, eligibleBachelorsReport to StudentReport.txt
PrintWriter outputFile = new PrintWriter("StudentReport.txt");
outputFile.println(studentSummary);
outputFile.println(eligibleBachelorsReport);
// write studentSummary, eligibleBachelorsReport to the console
System.out.println(studentSummary);
System.out.println(eligibleBachelorsReport);
input.close();
outputFile.close();
}}
Review your string comparisons for gender:
gender.equals(F)){
}if maritalStatus.equals(M)){
You're using bare tokens here, and not comparing against the strings "M", and "F".
Also look over that code, you have a syntax error there - and in many of your if statements - and an empty block if gender.equals("F"), and you're stringing together multiple else statements, instead of using intermediate else if.
This is incorrect:
if (test)
{
}
else
{ ; }
else // wrong, can only have one final else
{ ; }
For three branches, you need an intervening if:
if (test)
{
}
else if (someOtherTest)
{
}
else // ok, one final else
{ ; }
if (gender.equals(F))
F is no variable in your code.. You should use "F" here to compare..
Also, you are using your if as: - if age > 30.. This is not the correct way..
You need to put brackets around: - if (age > 30)
You say if (gender.equals(F)), but what is F? Is that a variable you've defined somewhere? I think it's more likely that you mean the string "F". Same for if (maritalStatus.equals(M)) (which is missing and opening parenthesis, by the way)
There are several issues with the code. I'll try to make a quick resume (showing a single example of each case, the rest of the related issues are similar) of what I've seen so far and I'll be updating the answer if I find more:
gender.equals(F)
What's F?, It's not a defined variable nor a valid value. If you want to compare against a string you need to use quotes, like "F".
if age > 30
Most statements need ()'s to delimit what will you check. The if statement is one of those, requiring it to be like if(age > 30). Also, remember that you need to use brackets if your if encloses more than a single line of code.
eligibleBachelorsReport += ""firstName + ""lastName
There's no need to use quotes before a String variable to concatenate them. Still, ig you wanted to add a blank space between the strings, do eligibleBachelorsReport += " " + firstName + " " + lastName + " - ". The - at the end is just a suggestion. Remember that if you're going to concatenate a lot of things together. Also, you can use \n if you need to insert a line break.
eligibleBachelorsReport += ""firstName + ""lastName
marriedMen = marriedMen ++
There's no semicolon at the end of those lines, amongst others.
singleMen = singleMen ++
Not an issue itself but unnecesary. Just do singleMen++ which is the same than singleMen = singleMen + 1 or also singleMen += 1.
As a final note, check your if statements. There is only one else per if, think of it as avoiding orphan else since there's no condition associated to them. The structure is:
if(condition) {
} else {
}
or, if the if and/or else enclose only one line (tough I always use brackets. It allows a clearer delimitation of the statements and improves readability IMHO.):
if(condition)
//code
else
//code
or, to nest statements:
if(condition) {
} else if(condition2) {
} else if(condition3) {
}

Categories

Resources