...

View Full Version : Help writing the statement for Y/N

limeleaf
03-09-2012, 12:33 AM
Hi all,

Forgive me if my questions are too silly. I am a Java beginner (very much of a beginner), and I received the following assignment:

"Many public schools in California are experiencing a shortage of funds for special student activities. Some schools started Jog-A-Thons as a fundraiser. Each student gathers sponsors for a particular amount per lap jogged. Write a program that tracks this activity.

The program repeats until all sponsors are entered. It accumulates the grand total funds owed the school. For each sponsor, the program prompts for the name of the student. It then prompts for the sponsors’ name, and amount pledged for each lap. The program asks if the sponsor is a company (Y/N). Then the program prompts for the amount of laps the student actually jogged. The program calculates the amount owed to the school (pledge times laps). If the sponsor is not a company, the maximum amount owed the school is set to \$100.00, (There is no maximum if the sponsor is a company). Finally, display on the screen the students name and sponsor name changed to all uppercase (whether or not it was entered in upper case), the pledge amount, the number of laps, and the amount calculated. Prompt if there is another sponsor (Y/N). After all sponsors are entered successfully, display the grand total funds owed the school. All money must be formatted appropriately."

So, I am stuck at figuring out how to write at the Y/N cases.

here is what I've got so far:

/* Andrew B
Test
03/01/2012
This program uses
System.out.println for standard output */

import java.util.Scanner; // Import the Scanner Class Library
import java.text.*;

public class Test
{
public static void main(String args[])
{
// variable declaration

int amountSchool, laps, count = 0;
String s, , more_sp, st_name, spon_name, Uname_st, Uname_spon;
float dolla, laps, total = 0;

Scanner input = new Scanner(System.in); //Create Scanner object "input"

DecimalFormat df = new DecimalFormat("###,##0.##");

// Print Title
System.out.print( "\t\t\tMy Jog-A-Thon Fundraising Activity\n\n" );

do
{

// Prompt for student name
System.out.println("\tEnter student's name: ");
st_name = input.nextLine();

// Student name to upper case
Uname_st = st_name.toUpperCase;

spon_name = input.nextLine();

// Sponsor name to upper case
Uname_spon = spon_name.toUpperCase;

System.out.print( "\n\n\n\t\t\tEnter U.S. dollar amount pledged for each lap: \n\t\t\t" );
dolla = input.nextFloat();

System.out.print( "\n\n\n\t\t\tIs the sponsor a company (Y/N)?\n\t\t\t" );
System.out.print( "\n\n\n\t\t\tPlease type Y for 'yes' and N for 'no'\n\t\t\t" );
s = input.nextLine();
choice = s.charAt(0);

if (s == 'y' || s == 'Y')

{

System.out.print( "\n\n\n\t\t\tEnter the number of laps student has jogged:\n\t\t\t" );
laps = input.nextFloat();

amountSchool = laps* dolla;

System.out.println( "\n\t\t\tAmount owed to school is \$" + df.format(amountSchool));
}

else if (s == 'n' || s == 'N')
{
System.out.print( "\n\n\n\t\t\tEnter the number of laps student has jogged:\n\t\t\t" );
laps = input.nextFloat();

amountSchool = laps* dolla;

if (amountSchool > 100)
{
System.out.println( "\n\t\t\tAmount owed to school is \$100");
}
else
{
System.out.println( "\n\t\t\tAmount owed to school is \$" + df.format(amountSchool));
}
}
else
{
System.out.println( "\n\t\t\tInvalid character");

count++;
total += amountSchool;

}

}

System.out.print("\nStudent's name: " + st_name);
System.out.print( "\nAmount pledged for each lap: \n\t\t\t" + de.format(dolla));
System.out.println("\nTotal laps = " + count);
System.out.println("\nTotal amount owed to school= \$" + df.format(total));

System.out.print( "\n\n\n\t\t\tIs tthere another sponsor (Y/N)?\n\t\t\t" );
more_spon = input.nextLine();
}
while (more_spon == 'y' || more_spon == 'Y');

System.out.println("\nTotal amount owed to school=\$" + df.format(total));
}
}

I need to keep repeating this program until all sponsors are entered. I am confused with all the repetitions, since I already used them for other reason, please help.

Fou-Lu
03-09-2012, 04:00 AM
The loop itself requires the while loop before the printing of the student name and whatnot. That is where the closing brace for the do{} is.

There is a lot more wrong than this though. You have undeclared variables, and a lot of comparison mismatches between strings and chars. Personally I wouldn't bother with the chars, just use strings and compare them with .equalsIgnoreCase("y") instead; strings cannot be reasonably compared to using == operators, as this compares the immutable values together ("y" == "y", but s = new String("y") != "y"), so as objects always compare them using .equals (or equalsIgnoreCase). Also, variables used for control structures such as a do/while will need to be declared before the loop in order to compare the value within the condition; if its created within the do its not scoped for visibility in the while.

limeleaf
03-09-2012, 06:32 AM
The loop itself requires the while loop before the printing of the student name and whatnot. That is where the closing brace for the do{} is.

There is a lot more wrong than this though. You have undeclared variables, and a lot of comparison mismatches between strings and chars. Personally I wouldn't bother with the chars, just use strings and compare them with .equalsIgnoreCase("y") instead; strings cannot be reasonably compared to using == operators, as this compares the immutable values together ("y" == "y", but s = new String("y") != "y"), so as objects always compare them using .equals (or equalsIgnoreCase). Also, variables used for control structures such as a do/while will need to be declared before the loop in order to compare the value within the condition; if its created within the do its not scoped for visibility in the while.

Can you please show in my example how to do this - .equalsIgnoreCase("y").

Are you saying that I need to create 2 cases:

if s.equalsIgnoreCase("y") ...?

what do I do next?

limeleaf
03-09-2012, 06:43 AM
Can you please show in my example how to do this - .equalsIgnoreCase("y").

Are you saying that I need to create 2 cases:

if s.equalsIgnoreCase("y") ...?

what do I do next?

You also mentioned that I have " lot of comparison mismatches between strings and chars" - where do I have chars and how do I fix this?

thank you

limeleaf
03-09-2012, 08:16 AM
Okay, here is where i got so far:

import java.util.Scanner; // Import the Scanner Class Library
import java.text.*;
import java.lang.*;

public class Lab6_v2
{
public static void main(String[] args)
{

// variable declaration
int count = 0;
String more_spon, stName, spon_name, Uname_st, Uname_spon, s;
float dolla, laps, total = 0, amountSchool;
char choice, m;

Scanner Keyboard = new Scanner(System.in); //Create Scanner object "Keyboard"

DecimalFormat df = new DecimalFormat("###,##0.##");

// Print Title
System.out.println( "\t\t\tMy Jog-A-Thon Fundraising Activity\n\n" );

do
{

// Prompt for student name
System.out.print("\tEnter student's name: ");
stName = Keyboard.next();

// Student name to upper case
Uname_st = stName.toUpperCase;

spon_name = Keyboard.next();

// Sponsor name to upper case
Uname_spon = spon_name.toUpperCase;

System.out.print( "\n\n\n\t\t\tEnter U.S. dollar amount pledged for each lap: \n\t\t\t" );
dolla = Keyboard.nextFloat();

System.out.print( "\n\n\n\t\t\tIs the sponsor a company (Y/N)?\n\t\t\t" );
System.out.println( "\n\n\n\t\t\tPlease type Y for 'yes' and N for 'no'\n\t\t\t" );
s = Keyboard.nextLine();
choice = s.charAt(0);

if (choice == 'y' || choice == 'Y')

{

System.out.print( "\n\n\n\t\t\tEnter the number of laps student has jogged:\n\t\t\t" );
laps = Keyboard.nextFloat();

amountSchool = laps* dolla;

System.out.println( "\n\t\t\tAmount owed to school is \$" + df.format(amountSchool));
}

else if(choice == 'n' || choice == 'N')
{
System.out.print( "\n\n\n\t\t\tEnter the number of laps student has jogged:\n\t\t\t" );
laps = Keyboard.nextFloat();

amountSchool = laps* dolla;

if (amountSchool > 100)
{
System.out.println( "\n\t\t\tAmount owed to school is \$100");
}
else
{
System.out.println( "\n\t\t\tAmount owed to school is \$" + df.format(amountSchool));
}
}
else
{
System.out.println( "\n\t\t\tInvalid entry");
}

count++;
total += amountSchool;

System.out.println("\nStudent's name: " + stName);
System.out.println( "\nAmount pledged for each lap: \n\t\t\t" + df.format(dolla));
System.out.println("\nTotal laps = " + count);
System.out.println("\nTotal amount owed to school= \$" + df.format(total));

System.out.print( "\n\n\n\t\t\tIs tthere another sponsor (Y/N)?\n\t\t\t" );
more_spon = Keyboard.nextLine();
m = more_spon.charAt(0);
}

while (m == 'y' || m == 'Y');

System.out.println("\nTotal amount owed to school=\$" + df.format(total));
}
}

Now, here is the mistake I keep getting OVER AND OVER again, I can't figure it out, can anybody?

Lab6_v2.java:41: cannot find symbol
symbol : variable toUpperCase
location: class java.lang.String
Uname_st = stName.toUpperCase;
^
Lab6_v2.java:48: cannot find symbol
symbol : variable toUpperCase
location: class java.lang.String
Uname_spon = spon_name.toUpperCase;
^
2 errors

----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.

Fou-Lu
03-09-2012, 12:01 PM
Cannot find symbol is the same as saying this variable / property doesn't exist. .toUpperCase doesn't exist in String, but .toUpperCase() does. Change those from properties to methods. Then you just need to initialize the variable for amountSchool and it will compile.
Using the scanner with next# type calls will require you to flush the buffer. Call Keyboard.nextLine() after any fetch to a number to clear the linefeed off of the buffer.

limeleaf
03-09-2012, 09:05 PM
Cannot find symbol is the same as saying this variable / property doesn't exist. .toUpperCase doesn't exist in String, but .toUpperCase() does. Change those from properties to methods. Then you just need to initialize the variable for amountSchool and it will compile.
Using the scanner with next# type calls will require you to flush the buffer. Call Keyboard.nextLine() after any fetch to a number to clear the linefeed off of the buffer.

Thank you, Fou-Lu. I fixed my mistakes as you said and it compiled. Now I am having an error when I run the application - when I entered "10" for dollar amount, I got an error saying "exception in thread "main" ... - string index out of range 0"

can you please look at the attached image? thanks!

limeleaf
03-09-2012, 09:18 PM
I see what I did wrong - I didn't clear the buffer every time, now I did it, and it is fixed.

One more thing - when it calculates laps, it doesn't do the count right. I enter 2, and it puts out 1...

then when I put N to show that company is not a sponsor, it still counts total over \$100.

Also, I keep seeing that error so it seems that buffer need to be cleaned more:

limeleaf
03-09-2012, 09:44 PM
Thanks again, I fixed my code, looking good now except for one little thing: how can I get so that after I asked if there is another sponsor, screen gets clean again?

I appreciate you looking at this, your explanations actually make a lot of sense, thank you:

import java.util.Scanner; // Import the Scanner Class Library
import java.text.*;
import java.lang.*;

public class Exam1
{
public static void main(String[] args)
{

// variable declaration
int count = 0;
String more_spon, stName, spon_name, Uname_st, Uname_spon, s;
float dolla, laps = 0, total = 0, amountSchool = 0;
char choice, m;

Scanner Keyboard = new Scanner(System.in); //Create Scanner object "Keyboard"

NumberFormat dollar = NumberFormat.getCurrencyInstance();

// Print Title
System.out.println( "\t\t\t=====================================" );
System.out.println( "\t\t\tMy Jog-A-Thon Fundraising Activity" );
System.out.println( "\t\t\t=====================================\n\n" );

do
{

// Prompt for student name
System.out.print("\n\tEnter student's name: ");
stName = Keyboard.next();

// Student name to upper case
Uname_st = stName.toUpperCase();

spon_name = Keyboard.next();

// Sponsor name to upper case
Uname_spon = spon_name.toUpperCase();

System.out.print( "\n\tEnter dollar amount pledged for each lap: " );
dolla = Keyboard.nextFloat();

Keyboard.nextLine();

System.out.print( "\n\tIs the sponsor a company (Y/N)?\t" );
s = Keyboard.nextLine();
choice = s.charAt(0);

switch (choice)

{
case 'y':
case 'Y':
System.out.print( "\n\tEnter the number of laps student has jogged:\t" );
laps = Keyboard.nextFloat();

Keyboard.nextLine();

amountSchool = laps* dolla;

System.out.println( "\n\t\t\tAmount owed to school is " + dollar.format(amountSchool));
break;

case 'n':
case 'N':
System.out.print( "\n\tEnter the number of laps student has jogged:\t" );
laps = Keyboard.nextFloat();

Keyboard.nextLine();

amountSchool = laps* dolla;

if (amountSchool > 100)
{
amountSchool = 100;

System.out.println( "\n\n\t\t\tAmount owed to school is " + dollar.format(amountSchool));
}
else
{

System.out.println( "\n\n\t\t\tAmount owed to school is " + dollar.format(amountSchool));
}
break;

default:
System.out.println("Nothing selected\n");

}

count+= laps;
total += amountSchool;

System.out.println( "\n\t=================================================================\n" );
System.out.println("\n\tStudent's name: " + Uname_st);
System.out.println( "\n\tAmount pledged for each lap: " + dollar.format(dolla));
System.out.println("\n\tTotal laps = " + count);
System.out.println( "\n\t=================================================================\n" );
System.out.println("\n\t\t\tTotal amount owed to school= " + dollar.format(total));
System.out.println( "\n\t=================================================================\n" );

System.out.print( "\n\t\t\tIs there another sponsor (Y/N)?\n\t\t\t" );
more_spon = Keyboard.nextLine();
m = more_spon.charAt(0);

}

while (m == 'y' || m == 'Y');

System.out.println( "\n\t=================================================================" );
System.out.println("\n\tTotal amount owed to school= " + dollar.format(total));
System.out.println( "\n\t=================================================================" );
}
}

Fou-Lu
03-09-2012, 10:38 PM
Clearing the console isn't really doable in Java. Since its designed for cross platform support, hooking into the console just wasn't something that they put that much effort into.
I recall the escape sequence ("\033[2J") used to work, but I just tried it and it did not clear the console. Sadly 100 empty lines seems to be the best route for console clear in Java (avoid a system call whenever possible).

limeleaf
03-21-2012, 12:07 AM
Hi Fou-Lu,

Okay, I received a new assignment, and I am a bit lost again:

And here are my Lab6 files that assignment refers to:

File "Foreign":

import java.util.Scanner;
import java.text.*;

public class Foreign
{
private double convRate;
private double dollars;
private double convAmount;
private String country;

private DecimalFormat fmt = new DecimalFormat("###,##0.00");

// initialize data;
public Foreign()
{
convRate = 0;
dollars = 0;
convAmount = 0;
String country = null;
}

// display the menu and get a choice;
{
Scanner keyboard = new Scanner(System.in);

System.out.print( "\n\tForeign Exchange \n" );

System.out.println("\t2. U.S.to Mexico");
System.out.println("\t3. U.S.to Japan");
System.out.println("\t4. U.S.to Euro");
System.out.println("\t0. = Quit");

{
}

}

// return the choice selected;
{
}

// get the dollars input and assign country and conversion rate;
public void getDollars()
{
Scanner keyboard = new Scanner(System.in);

System.out.print( "\n\tEnter U.S. dollar amount: " );
dollars = keyboard.nextDouble();

{
case 1:
convRate = 0.997;
break;
case 2:
country = "Mexican Dollars";
convRate = 12.82;
break;
case 3:
country = "Japanese Yen";
convRate = 123.78;
break;
case 4:
country = "Euros";
convRate = 0.747;
break;
}
}

// calculate the new converted amount;
public void calculate()
{
convAmount = dollars * convRate;
}

// display the values vertically;
public void displayVertically()
{
System.out.println("\n\tCountry: " + country);
System.out.println("\tRate: " + fmt.format(convRate));
System.out.println("\tDollars: " + fmt.format(dollars));
System.out.println("\tValue: " + fmt.format(convAmount));
}

// display the data horizontally with one space between values
@Override
public String toString()
{
return "\n\t" + country + " " +
fmt.format(convRate) + " " +
fmt.format(dollars) + " " +
fmt.format(convAmount);
}
}

And second file, the actual program Lab6:

public class Lab6
{
public static void main(String args[])
{
// create a Foreign object
Foreign f = new Foreign();

do // main loop
{

// get menu choice - if quit
break;

// get dollar amount and calculate the converted amount
f.getDollars();
f.calculate();

// display results vertically and horizontally
f.displayVertically();
System.out.println(f);

}while(true);

System.exit(1);
}
}

Any help or guidance would be appreciated!!

Thank you!