c# - Inputting a number beyond a range set by an array, index out of range error -
i want make program wherein user inputs number, in case number of items. number of items compared value in array, , corresponding discount displayed.
using system; using system.collections.generic; using system.linq; using system.text; namespace consoleapplication11 { class program { const int size = 4; static void main(string[] args) { int itemsbought = 0; int discountitem = 0; int[] items = new int[size] { 0, 10, 26, 61 }; int[] discount = new int[size] { 0, 5, 10,15 }; inputitems(ref itemsbought); getdiscount(items, discount, ref itemsbought, ref discountitem); console.writeline("your discount {0}", discountitem); } private static void getdiscount(int[] items, int[] discount, ref int itemsbought, ref int discountitem) { int idx = 0; (idx = 0; itemsbought > items[idx] || idx > items.length; idx++) { discountitem = discount[idx]; } } private static void inputitems(ref int itemsbought) { console.writeline("enter amount of items bought"); while (!int.tryparse(console.readline(), out itemsbought)) if (itemsbought < 0) { console.writeline("error, whole numbers on 0 only"); } console.writeline("error, whole numbers on 0 only"); } } }
when number above 61 entered "index out of range" error. how can make if number above 61 entered, displays 15? how can boundary includes 61 , on instead of 61 giving output of 10?
also everytime enter gives error message shown displays when number less 0 or double.
to show small error made, see corrected version:
for (idx = 0; idx < items.length && itemsbought > items[idx]; idx++)
there 3 important changes:
- idx > items.length false. , idx= items.length out-of-range.
- use && instead of || remember if condition true, loop continued execution, false once, execution stopped.
- exchanged order. must check idx < items.length before accessing items[idx]. shortcircuit && evaluates left right , stops if result determined.
so corrected code this:
private static void getdiscount(int[] items, int[] discount, int itemsbought, ref int discountitem) { int idx = 0; (idx = 0; idx < items.length && itemsbought > items[idx]; idx++) discountitem = discount[idx]; }
but i'd prefer put condition inside loop make more readable:
private static void getdiscount(int[] items, int[] discount, int itemsbought, ref int discountitem) { (int = 0; < items.length; i++) { if(itemsbought > items[i]) discountitem = discount[i]; else break; } }
to address other issue
also everytime enter gives error message shown displays when number less 0 or double.
reformat code properly, 1 message output in right place, other 1 executed.
Comments
Post a Comment