Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Help an idiot with JavaScript?
New Posts  All Forums:Forum Nav:

Help an idiot with JavaScript?

post #1 of 6
Thread Starter 
So I have this project I am doing for my Comp. Science class and I have had no issues with the other two assignments. This program I am writing is designed to take orders (it doesnt record them, it just keeps a running total and outputs a total price at the end). The user has to input a valid size and a valid flavor (cant use radio buttons). If these conditions are met, the program prompts the user if they want to add another item to the order. If they then enter 'y', the while statement continues to run, compounding on the total price each time until it falls out of this loop and outputs the final total.

I think my issue lies entirely in nesting... Right now it doesnt work after adding the flavor validation
Code:

var price=0;
var another_order="y";
var size

while (another_order=="y") {
     var order=prompt("What flavor shave ice would you like?"){
          if (flavor=="cherry" || flavor=="lime" || flavor=="watermelon" || flavor=="grape" || flavor=="orange" );
                else  alert("Please enter a valid size, large or small, upper or lowercase abbreviations are     permitted")
  }
    size=prompt("What size is this order?") {
         if (size=="large" || size=="l" || size=="Large" || size=="L")
              price=price+3;
         else if (size=="small" || size=="s" || size=="Small" || size=="S")
              price=price+2;
   }
     another_order=prompt("Are there any more orders on this ticket?");
}
alert("Thank you! The total of the purchase is $" +price.toFixed(2))


Below is the last variant of the program that worked:
Code:

var price=0;
var another_order="y";
var size

while (another_order=="y") {
     var order=prompt("What flavor shave ice would you like?")
          size=prompt("What size is this order?")
               if (size=="large" || size=="l" || size=="Large" || size=="L")
                    price=price+3;
               else if (size=="small" || size=="s" || size=="Small" || size=="S")
                    price=price+2;
   
    another_order=prompt("Are there any more orders on this ticket?");
}
alert("Thank you! The total of the purchase is $" +price.toFixed(2))


Edited by raidmaxGuy - 11/13/13 at 11:22am
K9 UN1T
(33 items)
 
Blackout
(18 items)
 
 
CPUMotherboardGraphicsGraphics
i5-3570k ASRock Z77 Extreme6 Gigabyte GTX 770 Superclocked Windforce Gigabyte GTX 770 Superclocked Windforce 
RAMRAMHard DriveHard Drive
Kingston HyperX T1 G-Skill Ripjaws Sandisk SSD Hitachi Desktar 
Hard DriveHard DriveOptical DriveCooling
Seagate Barracuda Green Western Digital Asus DVD-RW Corsair H100 
CoolingCoolingCoolingOS
Corsair SP 120 Quiet Edition (x2) Bitfenix Spectre Pro LED 140mm White/Red Bitfenix Spectre Pro LED 120mm White/Red (x2) Windows 8.1 Pro 
MonitorMonitorKeyboardPower
AOC I2757Fh 27" IPS LED 1080p monitor Dell E207WFP 20.5'' TFT LCD monitor CM Storm QuickFire TK Cooler Master V-750 Modular 80 Plus Gold 
CaseMouseMouse PadAudio
Cooler Master Storm Stryker Roccat Savu HyenaAgenda 18'' gaming mat JVC HA RX700 
AudioAudioAudioAudio
Logitech G930 Wireless Headset Sound Blaster Z JVC RX-6000V 500W receiver Bose Acoustimass 3 Series III 
OtherOtherOtherOther
SMK LINK Bluetooth 4.0 +EDR Adaptor Logysis Red 12" CCFL Belkin n52te speedpad Logitech Wireless Gamepad F710 
Other
Logitech Extreme 3D Pro 
CPUMotherboardGraphicsGraphics
Phenom II x6 1055T Gigabyte 990FXA-UD3 XFX R7770 Double Dissipation GHz Edition XFX R7770 Double Dissipation GHz Edition 
RAMHard DriveHard DriveHard Drive
Corsair Vengeance Sandisk SSD Seagate Barracuda Western Digital Caviar SE 
Optical DriveCoolingOSMonitor
Lite-On DVD-RW Corsair H60 in push/pull Windows 7 Pro Samsung SyncMaster 226BW 
KeyboardPowerCaseMouse
Corsair K70 Rosewill HIVE 550w Modular Antec LanBoy Air Black Microsoft Wheel Mouse Optical 
AudioOther
Sharper Image USB speakers TP-Link TL-WDN4800 5GHz 450mbps WLAN card 
CPUGraphicsGraphicsRAM
Intel i7 6820HK Intel(R) HD Graphics 530 Nvidia GeForce 980m Hynix DDR4 2133 
Hard DriveOSMonitorPower
1TB HGST 7K1000 7200RPM Windows 10 x64 Home Edition IGZO-IPS TrueLife 400 nits UHD display Dell 240W AC Adapter 
CaseMouseAudio
Alienware 17 R3 Logitech G502 Proteus Core Creative Sound Blaster Recon3Di 
  hide details  
Reply
K9 UN1T
(33 items)
 
Blackout
(18 items)
 
 
CPUMotherboardGraphicsGraphics
i5-3570k ASRock Z77 Extreme6 Gigabyte GTX 770 Superclocked Windforce Gigabyte GTX 770 Superclocked Windforce 
RAMRAMHard DriveHard Drive
Kingston HyperX T1 G-Skill Ripjaws Sandisk SSD Hitachi Desktar 
Hard DriveHard DriveOptical DriveCooling
Seagate Barracuda Green Western Digital Asus DVD-RW Corsair H100 
CoolingCoolingCoolingOS
Corsair SP 120 Quiet Edition (x2) Bitfenix Spectre Pro LED 140mm White/Red Bitfenix Spectre Pro LED 120mm White/Red (x2) Windows 8.1 Pro 
MonitorMonitorKeyboardPower
AOC I2757Fh 27" IPS LED 1080p monitor Dell E207WFP 20.5'' TFT LCD monitor CM Storm QuickFire TK Cooler Master V-750 Modular 80 Plus Gold 
CaseMouseMouse PadAudio
Cooler Master Storm Stryker Roccat Savu HyenaAgenda 18'' gaming mat JVC HA RX700 
AudioAudioAudioAudio
Logitech G930 Wireless Headset Sound Blaster Z JVC RX-6000V 500W receiver Bose Acoustimass 3 Series III 
OtherOtherOtherOther
SMK LINK Bluetooth 4.0 +EDR Adaptor Logysis Red 12" CCFL Belkin n52te speedpad Logitech Wireless Gamepad F710 
Other
Logitech Extreme 3D Pro 
CPUMotherboardGraphicsGraphics
Phenom II x6 1055T Gigabyte 990FXA-UD3 XFX R7770 Double Dissipation GHz Edition XFX R7770 Double Dissipation GHz Edition 
RAMHard DriveHard DriveHard Drive
Corsair Vengeance Sandisk SSD Seagate Barracuda Western Digital Caviar SE 
Optical DriveCoolingOSMonitor
Lite-On DVD-RW Corsair H60 in push/pull Windows 7 Pro Samsung SyncMaster 226BW 
KeyboardPowerCaseMouse
Corsair K70 Rosewill HIVE 550w Modular Antec LanBoy Air Black Microsoft Wheel Mouse Optical 
AudioOther
Sharper Image USB speakers TP-Link TL-WDN4800 5GHz 450mbps WLAN card 
CPUGraphicsGraphicsRAM
Intel i7 6820HK Intel(R) HD Graphics 530 Nvidia GeForce 980m Hynix DDR4 2133 
Hard DriveOSMonitorPower
1TB HGST 7K1000 7200RPM Windows 10 x64 Home Edition IGZO-IPS TrueLife 400 nits UHD display Dell 240W AC Adapter 
CaseMouseAudio
Alienware 17 R3 Logitech G502 Proteus Core Creative Sound Blaster Recon3Di 
  hide details  
Reply
post #2 of 6
Quote:
Originally Posted by raidmaxGuy View Post

So I have this project I am doing for my Comp. Science class and I have had no issues with the other two assignments. This program I am writing is designed to take orders (it doesnt record them, it just keeps a running total and outputs a total price at the end). The user has to input a valid size and a valid flavor (cant use radio buttons). If these conditions are met, the program prompts the user if they want to add another item to the order. If they then enter 'y', the while statement continues to run, compounding on the total price each time until it falls out of this loop and outputs the final total.

I think my issue lies entirely in nesting... Right now it doesnt work after adding the flavor validation
Code:

var price=0;
var another_order="y";
var size

while (another_order=="y") {
     var order=prompt("What flavor shave ice would you like?"){
          if (flavor=="cherry" || flavor=="lime" || flavor=="watermelon" || flavor=="grape" || flavor=="orange" );
                else  alert("Please enter a valid size, large or small, upper or lowercase abbreviations are     permitted")
  }
    size=prompt("What size is this order?") {
         if (size=="large" || size=="l" || size=="Large" || size=="L")
              price=price+3;
         else if (size=="small" || size=="s" || size=="Small" || size=="S")
              price=price+2;
   }
     another_order=prompt("Are there any more orders on this ticket?");
}
alert("Thank you! The total of the purchase is $" +price.toFixed(2))


Below is the last variant of the program that worked:
Code:

var price=0;
var another_order="y";
var size

while (another_order=="y") {
     var order=prompt("What flavor shave ice would you like?")
          size=prompt("What size is this order?")
               if (size=="large" || size=="l" || size=="Large" || size=="L")
                    price=price+3;
               else if (size=="small" || size=="s" || size=="Small" || size=="S")
                    price=price+2;
   
    another_order=prompt("Are there any more orders on this ticket?");
}
alert("Thank you! The total of the purchase is $" +price.toFixed(2))


In the first part, you have curly braces in the wrong spot (see below). To help with these and other problems specific to JS, I recommend following Douglas Crockford's formatting (http://javascript.crockford.com/code.html). Note that with JS, not following these specific conventions will create very hard to find bugs due to automatic semi-colon insertion.

Also never, NEVER use '=='. ALWAYS use '==='. If your instructor says to use '==' call him/her out for the idiot he/she is. In JS, type coercion is problematic, but occurs automatically with '=='. The "triple equals" was specifically added to the language to work around this well-known issue.
Code:
var order=prompt("What flavor shave ice would you like?"){
          if (flavor=="cherry" || flavor=="lime" || flavor=="watermelon" || flavor=="grape" || flavor=="orange" );
                else  alert("Please enter a valid size, large or small, upper or lowercase abbreviations are     permitted")
  }

I normally don't "give answers", but you seemed to have put in some effort, so let me walk you through this (note that I haven't tested the code):
Code:
//The outer 'function' ensures our code is contained and not in the global variable space.
(function () {
    //note: all the variable declarations are comma separated
    //and only the final one ends in a semi-colon
    var total = 0, //we'll be counting the total in cents (no decimal)
        order_temp = {}, //individual order
        i, //iterator
        len, //length of object
        order = [], //this holds their final order
        options = { //this object is the stuff they can choose from. Ideally, it would be better designed. I leave that to you.
            flavor: ["cherry", "lime", "watermelon", "grape", "orange"],
            size: ["small", "medium", "large"]
        };

    //this function returns true if an item is in an array
    //I've done this to reduce code later
    //this is necessary because the 'in' keyword is bugged for arrays
    //There's an OOP way that's a little better, but this is easier to understand
    var contains_p = function (item, list) {
        var len = list.length,
            i = 0;
            exists = false;
        for (i; i < len; i += 1) {
            if (item === list[i]) {
                exists = true;
                break;
            }
        }
        return exists;
    };

    //the true means that the loop will continue until 'break' is called
    while (true) {
        //the main idea here is to get the correct order stuff.
        order_temp.flavor = prompt("We offer: \nCherry\nLime\nWatermelon\nGrape\nOrange\nPlease enter your choice: ");
        order_temp.size = prompt("Pick your size (small, medium, or large): ");

        //check if both items are valid, if so, add the item to your list
        //if not, tell them and then start over.
        if (contains_p(order_temp.flavor, options.flavor) && contains_p(order_temp.size, options.size)) {
            alert("your item has been added");
            //you don't mention pricing, but it should be in the options object above and added here
            //to the order_temp.price variable
            order.push(order_temp);
        } else {
            alert("Part of your order could not be handled. Please try again.");
            continue; //forces the loop to jump to the top and go again.
        }

        if ("y" !== prompt("Add another item y/n? ")) {
            break;
        }
    }

    //get the total price
    len = order.length;
    for (i = 0; i < len; i += 1) {
        total += order[i].price;
    }
    //convert the total from cents to dollars and cents
    //floor is needed because floating point numbers round
    //the modulus gets the remainder (in this case, the cents)
    alert("Your total is $" + Math.floor(total / 100) + "." + (total % 100);
}());

Edited by hajile - 11/13/13 at 12:52pm
post #3 of 6
Thread Starter 
Quote:
Originally Posted by hajile View Post

In the first part, you have curly braces in the wrong spot (see below). To help with these and other problems specific to JS, I recommend following Douglas Crockford's formatting (http://javascript.crockford.com/code.html). Note that with JS, not following these specific conventions will create very hard to find bugs due to automatic semi-colon insertion.

Also never, NEVER use '=='. ALWAYS use '==='. If your instructor says to use '==' call him/her out for the idiot he/she is. In JS, type coercion is problematic, but occurs automatically with '=='. The "triple equals" was specifically added to the language to work around this well-known issue.
Code:
var order=prompt("What flavor shave ice would you like?"){
          if (flavor=="cherry" || flavor=="lime" || flavor=="watermelon" || flavor=="grape" || flavor=="orange" );
                else  alert("Please enter a valid size, large or small, upper or lowercase abbreviations are     permitted")
  }

I normally don't "give answers", but you seemed to have put in some effort, so let me walk you through this (note that I haven't tested the code):
Code:
//The outer 'function' ensures our code is contained and not in the global variable space.
(function () {
    //note: all the variable declarations are comma separated
    //and only the final one ends in a semi-colon
    var total = 0, //we'll be counting the total in cents (no decimal)
        order_temp = {}, //individual order
        i, //iterator
        len, //length of object
        order = [], //this holds their final order
        options = { //this object is the stuff they can choose from. Ideally, it would be better designed. I leave that to you.
            flavor: ["cherry", "lime", "watermelon", "grape", "orange"],
            size: ["small", "medium", "large"]
        };

    //this function returns true if an item is in an array
    //I've done this to reduce code later
    //this is necessary because the 'in' keyword is bugged for arrays
    //There's an OOP way that's a little better, but this is easier to understand
    var contains_p = function (item, list) {
        var len = list.length,
            i = 0;
            exists = false;
        for (i; i < len; i += 1) {
            if (item === list[i]) {
                exists = true;
                break;
            }
        }
        return exists;
    };

    //the true means that the loop will continue until 'break' is called
    while (true) {
        //the main idea here is to get the correct order stuff.
        order_temp.flavor = prompt("We offer: \nCherry\nLime\nWatermelon\nGrape\nOrange\nPlease enter your choice: ");
        order_temp.size = prompt("Pick your size (small, medium, or large): ");

        //check if both items are valid, if so, add the item to your list
        //if not, tell them and then start over.
        if (contains_p(order_temp.flavor, options.flavor) && contains_p(order_temp.size, options.size)) {
            alert("your item has been added");
            //you don't mention pricing, but it should be in the options object above and added here
            //to the order_temp.price variable
            order.push(order_temp);
        } else {
            alert("Part of your order could not be handled. Please try again.");
            continue; //forces the loop to jump to the top and go again.
        }

        if ("y" !== prompt("Add another item y/n? ")) {
            break;
        }
    }

    //get the total price
    len = order.length;
    for (i = 0; i < len; i += 1) {
        total += order[i].price;
    }
    //convert the total from cents to dollars and cents
    //floor is needed because floating point numbers round
    //the modulus gets the remainder (in this case, the cents)
    alert("Your total is $" + Math.floor(total / 100) + "." + (total % 100);
}());

Hajile,

While I appreciate the script youve provided, I dont believe my teacher wanted us to go into that level of detail. Could we perhaps analyze the 'broken' variant of my script and mitigate the problems?
Looking at the article you provided at the moment
K9 UN1T
(33 items)
 
Blackout
(18 items)
 
 
CPUMotherboardGraphicsGraphics
i5-3570k ASRock Z77 Extreme6 Gigabyte GTX 770 Superclocked Windforce Gigabyte GTX 770 Superclocked Windforce 
RAMRAMHard DriveHard Drive
Kingston HyperX T1 G-Skill Ripjaws Sandisk SSD Hitachi Desktar 
Hard DriveHard DriveOptical DriveCooling
Seagate Barracuda Green Western Digital Asus DVD-RW Corsair H100 
CoolingCoolingCoolingOS
Corsair SP 120 Quiet Edition (x2) Bitfenix Spectre Pro LED 140mm White/Red Bitfenix Spectre Pro LED 120mm White/Red (x2) Windows 8.1 Pro 
MonitorMonitorKeyboardPower
AOC I2757Fh 27" IPS LED 1080p monitor Dell E207WFP 20.5'' TFT LCD monitor CM Storm QuickFire TK Cooler Master V-750 Modular 80 Plus Gold 
CaseMouseMouse PadAudio
Cooler Master Storm Stryker Roccat Savu HyenaAgenda 18'' gaming mat JVC HA RX700 
AudioAudioAudioAudio
Logitech G930 Wireless Headset Sound Blaster Z JVC RX-6000V 500W receiver Bose Acoustimass 3 Series III 
OtherOtherOtherOther
SMK LINK Bluetooth 4.0 +EDR Adaptor Logysis Red 12" CCFL Belkin n52te speedpad Logitech Wireless Gamepad F710 
Other
Logitech Extreme 3D Pro 
CPUMotherboardGraphicsGraphics
Phenom II x6 1055T Gigabyte 990FXA-UD3 XFX R7770 Double Dissipation GHz Edition XFX R7770 Double Dissipation GHz Edition 
RAMHard DriveHard DriveHard Drive
Corsair Vengeance Sandisk SSD Seagate Barracuda Western Digital Caviar SE 
Optical DriveCoolingOSMonitor
Lite-On DVD-RW Corsair H60 in push/pull Windows 7 Pro Samsung SyncMaster 226BW 
KeyboardPowerCaseMouse
Corsair K70 Rosewill HIVE 550w Modular Antec LanBoy Air Black Microsoft Wheel Mouse Optical 
AudioOther
Sharper Image USB speakers TP-Link TL-WDN4800 5GHz 450mbps WLAN card 
CPUGraphicsGraphicsRAM
Intel i7 6820HK Intel(R) HD Graphics 530 Nvidia GeForce 980m Hynix DDR4 2133 
Hard DriveOSMonitorPower
1TB HGST 7K1000 7200RPM Windows 10 x64 Home Edition IGZO-IPS TrueLife 400 nits UHD display Dell 240W AC Adapter 
CaseMouseAudio
Alienware 17 R3 Logitech G502 Proteus Core Creative Sound Blaster Recon3Di 
  hide details  
Reply
K9 UN1T
(33 items)
 
Blackout
(18 items)
 
 
CPUMotherboardGraphicsGraphics
i5-3570k ASRock Z77 Extreme6 Gigabyte GTX 770 Superclocked Windforce Gigabyte GTX 770 Superclocked Windforce 
RAMRAMHard DriveHard Drive
Kingston HyperX T1 G-Skill Ripjaws Sandisk SSD Hitachi Desktar 
Hard DriveHard DriveOptical DriveCooling
Seagate Barracuda Green Western Digital Asus DVD-RW Corsair H100 
CoolingCoolingCoolingOS
Corsair SP 120 Quiet Edition (x2) Bitfenix Spectre Pro LED 140mm White/Red Bitfenix Spectre Pro LED 120mm White/Red (x2) Windows 8.1 Pro 
MonitorMonitorKeyboardPower
AOC I2757Fh 27" IPS LED 1080p monitor Dell E207WFP 20.5'' TFT LCD monitor CM Storm QuickFire TK Cooler Master V-750 Modular 80 Plus Gold 
CaseMouseMouse PadAudio
Cooler Master Storm Stryker Roccat Savu HyenaAgenda 18'' gaming mat JVC HA RX700 
AudioAudioAudioAudio
Logitech G930 Wireless Headset Sound Blaster Z JVC RX-6000V 500W receiver Bose Acoustimass 3 Series III 
OtherOtherOtherOther
SMK LINK Bluetooth 4.0 +EDR Adaptor Logysis Red 12" CCFL Belkin n52te speedpad Logitech Wireless Gamepad F710 
Other
Logitech Extreme 3D Pro 
CPUMotherboardGraphicsGraphics
Phenom II x6 1055T Gigabyte 990FXA-UD3 XFX R7770 Double Dissipation GHz Edition XFX R7770 Double Dissipation GHz Edition 
RAMHard DriveHard DriveHard Drive
Corsair Vengeance Sandisk SSD Seagate Barracuda Western Digital Caviar SE 
Optical DriveCoolingOSMonitor
Lite-On DVD-RW Corsair H60 in push/pull Windows 7 Pro Samsung SyncMaster 226BW 
KeyboardPowerCaseMouse
Corsair K70 Rosewill HIVE 550w Modular Antec LanBoy Air Black Microsoft Wheel Mouse Optical 
AudioOther
Sharper Image USB speakers TP-Link TL-WDN4800 5GHz 450mbps WLAN card 
CPUGraphicsGraphicsRAM
Intel i7 6820HK Intel(R) HD Graphics 530 Nvidia GeForce 980m Hynix DDR4 2133 
Hard DriveOSMonitorPower
1TB HGST 7K1000 7200RPM Windows 10 x64 Home Edition IGZO-IPS TrueLife 400 nits UHD display Dell 240W AC Adapter 
CaseMouseAudio
Alienware 17 R3 Logitech G502 Proteus Core Creative Sound Blaster Recon3Di 
  hide details  
Reply
post #4 of 6
My code isn't much bigger than your own (especially when yours is formatted correctly). A major difference is that mine is easy to change when the number of items, kind of items or price changes. Even if your teacher didn't demand that kind of detail, it is what's required in the real world of programming (that's what you're really studying for). Teach yourself to do that early and you won't have to get kicked so hard when you first start work on real projects.

I'll go over what's specifically broken in your code, but I think you should look over and understand what my code is doing.
Code:
var price = 0;
var another_order = "y";
var size //you forgot a semicolon

//I took the time to space out your assignment and equality operators
//in short, it looks like your broken if syntax is a major problem
while (another_order == "y") {//triple equals
    var order = prompt("What flavor shave ice would you like?"){ //this curly brace shouldn't even be here
        if (flavor == "cherry" || flavor == "lime" || flavor == "watermelon" || flavor == "grape" || flavor == "orange" );//if so, then do what? Also missing curly braces, ===
        else  alert("Please enter a valid size, large or small, upper or lowercase abbreviations are     permitted")//missing curly braces, missing semicolon
    }//what is this closing? The matching curly brace is already in the wrong spot
    size = rompt("What size is this order?") {//once again, the braces are in the wrong place
        if (size ==" large" || size == "l" || size == "Large" || size == "L")//missing curly braces, ===
            price = price + 3; //spacing your operators helps readability
        else if (size == "small" || size == "s" || size == "Small" || size == "S")//missing curly braces, ===
            price = price + 2;
    }
    another_order = prompt("Are there any more orders on this ticket?");
}
//NEVER use toFixed() with money. All JS numbers are floating point, so rounding errors can/will happen if you do
alert("Thank you! The total of the purchase is $" + price.toFixed(2))
Code:
var price = 0;
var another_order = "y";
var size //missing semicolon

while (another_order == "y") {
    var order = prompt("What flavor shave ice would you like?")//missing semicolon, move declaration to top where it belongs
        size = prompt("What size is this order?")//missing semicolon
            if (size == "large" || size == "l" || size == "Large" || size == "L") //ALWAYS add curly braces (and keep them on the same line as the if)
                price = price + 3;                                              //If you don't semi-colon insertion is very likely to kill your code (Unlike C where such things don't happen)
            else if (size == "small" || size ==="s" || size == "Small" || size == "S")
                price = price + 2;
   
    another_order = prompt("Are there any more orders on this ticket?");
}
//NEVER use toFixed() with money. All JS numbers are floating point, so rounding errors can/will happen if you do
alert("Thank you! The total of the purchase is $" + price.toFixed(2)) 

A fixed version of your working one. Once again, I haven't tested these.
Code:
var price = 0,
    another_order = "y",
    size,
    order;

while (another_order === "y") {
    order = prompt("What flavor shave ice would you like?");
    size = prompt("What size is this order?");

    if (size === "large" || size === "l" || size === "Large" || size === "L") {
        price = price + 3;
    } else if (size === "small" || size === "s" || size === "Small" || size === "S") {
        price = price + 2;
    }
   
    another_order = prompt("Are there any more orders on this ticket?");
}

alert("Thank you! The total of the purchase is $" + Math.floor(price / 100) + "." + (price % 100)) 

A word on your broken one. It's trying to check the user input and keep asking for input until it gets something acceptable. The answer here is a do..while loop. This loop acts like a while loop except that it does the first iteration before checking.
Code:
do {
    //stuff
    //more stuff
} while (<condition>); //note the semicolon that should be used in this form

A fixed top version
Code:
var price = 0,
    another_order = "y",
    size,
    order;

while (another_order === "y") {
    do {
        order = prompt("What flavor shave ice would you like?");

        if (flavor === "cherry" || flavor === "lime" || flavor === "watermelon" || flavor === "grape" || flavor === "orange" ) {
            break; //exit the loop
        } else {
            alert("Please enter a valid size, large or small, upper or lowercase abbreviations are permitted");
        }

    } while (true);// you could also work in your if statement here, but I'm keeping it similar to your original

    size = prompt("What size is this order?"); //you probably need another do..while loop to check this too

    if (size ===" large" || size === "l" || size === "Large" || size === "L") {
        price = price + 3;
    } else if (size === "small" || size === "s" || size === "Small" || size === "S") {
        price = price + 2;
    }

    another_order = prompt("Are there any more orders on this ticket?");
}

alert("Thank you! The total of the purchase is $" + Math.floor(price / 100) + "." + (price % 100)) 

Edited by hajile - 11/13/13 at 3:24pm
post #5 of 6
Thread Starter 
You brought up some interesting points Hajile, also, I really do appreciate the critique and revised version of the code. I will try the fixed version and let you know (of course I am going to manually edit my version so I get a better understanding of what needs to be happening.thumb.gif
Edited by raidmaxGuy - 11/14/13 at 8:44am
K9 UN1T
(33 items)
 
Blackout
(18 items)
 
 
CPUMotherboardGraphicsGraphics
i5-3570k ASRock Z77 Extreme6 Gigabyte GTX 770 Superclocked Windforce Gigabyte GTX 770 Superclocked Windforce 
RAMRAMHard DriveHard Drive
Kingston HyperX T1 G-Skill Ripjaws Sandisk SSD Hitachi Desktar 
Hard DriveHard DriveOptical DriveCooling
Seagate Barracuda Green Western Digital Asus DVD-RW Corsair H100 
CoolingCoolingCoolingOS
Corsair SP 120 Quiet Edition (x2) Bitfenix Spectre Pro LED 140mm White/Red Bitfenix Spectre Pro LED 120mm White/Red (x2) Windows 8.1 Pro 
MonitorMonitorKeyboardPower
AOC I2757Fh 27" IPS LED 1080p monitor Dell E207WFP 20.5'' TFT LCD monitor CM Storm QuickFire TK Cooler Master V-750 Modular 80 Plus Gold 
CaseMouseMouse PadAudio
Cooler Master Storm Stryker Roccat Savu HyenaAgenda 18'' gaming mat JVC HA RX700 
AudioAudioAudioAudio
Logitech G930 Wireless Headset Sound Blaster Z JVC RX-6000V 500W receiver Bose Acoustimass 3 Series III 
OtherOtherOtherOther
SMK LINK Bluetooth 4.0 +EDR Adaptor Logysis Red 12" CCFL Belkin n52te speedpad Logitech Wireless Gamepad F710 
Other
Logitech Extreme 3D Pro 
CPUMotherboardGraphicsGraphics
Phenom II x6 1055T Gigabyte 990FXA-UD3 XFX R7770 Double Dissipation GHz Edition XFX R7770 Double Dissipation GHz Edition 
RAMHard DriveHard DriveHard Drive
Corsair Vengeance Sandisk SSD Seagate Barracuda Western Digital Caviar SE 
Optical DriveCoolingOSMonitor
Lite-On DVD-RW Corsair H60 in push/pull Windows 7 Pro Samsung SyncMaster 226BW 
KeyboardPowerCaseMouse
Corsair K70 Rosewill HIVE 550w Modular Antec LanBoy Air Black Microsoft Wheel Mouse Optical 
AudioOther
Sharper Image USB speakers TP-Link TL-WDN4800 5GHz 450mbps WLAN card 
CPUGraphicsGraphicsRAM
Intel i7 6820HK Intel(R) HD Graphics 530 Nvidia GeForce 980m Hynix DDR4 2133 
Hard DriveOSMonitorPower
1TB HGST 7K1000 7200RPM Windows 10 x64 Home Edition IGZO-IPS TrueLife 400 nits UHD display Dell 240W AC Adapter 
CaseMouseAudio
Alienware 17 R3 Logitech G502 Proteus Core Creative Sound Blaster Recon3Di 
  hide details  
Reply
K9 UN1T
(33 items)
 
Blackout
(18 items)
 
 
CPUMotherboardGraphicsGraphics
i5-3570k ASRock Z77 Extreme6 Gigabyte GTX 770 Superclocked Windforce Gigabyte GTX 770 Superclocked Windforce 
RAMRAMHard DriveHard Drive
Kingston HyperX T1 G-Skill Ripjaws Sandisk SSD Hitachi Desktar 
Hard DriveHard DriveOptical DriveCooling
Seagate Barracuda Green Western Digital Asus DVD-RW Corsair H100 
CoolingCoolingCoolingOS
Corsair SP 120 Quiet Edition (x2) Bitfenix Spectre Pro LED 140mm White/Red Bitfenix Spectre Pro LED 120mm White/Red (x2) Windows 8.1 Pro 
MonitorMonitorKeyboardPower
AOC I2757Fh 27" IPS LED 1080p monitor Dell E207WFP 20.5'' TFT LCD monitor CM Storm QuickFire TK Cooler Master V-750 Modular 80 Plus Gold 
CaseMouseMouse PadAudio
Cooler Master Storm Stryker Roccat Savu HyenaAgenda 18'' gaming mat JVC HA RX700 
AudioAudioAudioAudio
Logitech G930 Wireless Headset Sound Blaster Z JVC RX-6000V 500W receiver Bose Acoustimass 3 Series III 
OtherOtherOtherOther
SMK LINK Bluetooth 4.0 +EDR Adaptor Logysis Red 12" CCFL Belkin n52te speedpad Logitech Wireless Gamepad F710 
Other
Logitech Extreme 3D Pro 
CPUMotherboardGraphicsGraphics
Phenom II x6 1055T Gigabyte 990FXA-UD3 XFX R7770 Double Dissipation GHz Edition XFX R7770 Double Dissipation GHz Edition 
RAMHard DriveHard DriveHard Drive
Corsair Vengeance Sandisk SSD Seagate Barracuda Western Digital Caviar SE 
Optical DriveCoolingOSMonitor
Lite-On DVD-RW Corsair H60 in push/pull Windows 7 Pro Samsung SyncMaster 226BW 
KeyboardPowerCaseMouse
Corsair K70 Rosewill HIVE 550w Modular Antec LanBoy Air Black Microsoft Wheel Mouse Optical 
AudioOther
Sharper Image USB speakers TP-Link TL-WDN4800 5GHz 450mbps WLAN card 
CPUGraphicsGraphicsRAM
Intel i7 6820HK Intel(R) HD Graphics 530 Nvidia GeForce 980m Hynix DDR4 2133 
Hard DriveOSMonitorPower
1TB HGST 7K1000 7200RPM Windows 10 x64 Home Edition IGZO-IPS TrueLife 400 nits UHD display Dell 240W AC Adapter 
CaseMouseAudio
Alienware 17 R3 Logitech G502 Proteus Core Creative Sound Blaster Recon3Di 
  hide details  
Reply
post #6 of 6
Just throwing in another reason not to use toFixed(): Its behaviour is not consistent across browsers. Try 0.045.toFixed(2) in IE and Firefox and you'll get different results. I know an insurance company that uses toFixed all over the place when calculating online premiums, and you can get a different premium in different browsers (only 1 or 2 cents, but it's still not good). I would have thought that the repeated use of parseFloat() (since toFixed returns a string) would have also raised a flag that they were probably using the wrong method, but apparently not.
    
CPUMotherboardGraphicsRAM
i7 920 D0 MSI X58 Pro-E GTX 560 Ti 448 3x2GB G.Skill DDR3-1333 9-9-9-24 
Hard DriveHard DriveOptical DriveOS
840 Pro Caviar Black LG BD-ROM Windows 8.1 Pro x64 
MonitorMonitorKeyboardPower
Dell U2713HM Dell U2311H Turbo-Trak (Google it :D) Corsair HX-520 
CaseMouseMouse PadAudio
CM690 Mionix Avior 7000 Everglide Titan AKG K 242 HD 
  hide details  
Reply
    
CPUMotherboardGraphicsRAM
i7 920 D0 MSI X58 Pro-E GTX 560 Ti 448 3x2GB G.Skill DDR3-1333 9-9-9-24 
Hard DriveHard DriveOptical DriveOS
840 Pro Caviar Black LG BD-ROM Windows 8.1 Pro x64 
MonitorMonitorKeyboardPower
Dell U2713HM Dell U2311H Turbo-Trak (Google it :D) Corsair HX-520 
CaseMouseMouse PadAudio
CM690 Mionix Avior 7000 Everglide Titan AKG K 242 HD 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Help an idiot with JavaScript?