• What Do You Need Help With? V6
    7,544 replies, posted
[QUOTE=WhiskeyTangoF;44485774]Not sure if it will be much help but fuck it I'll post anyway, forgive me for being a complete novice. I'm trying to create a gradebook program in java for my class, and I'm running into a lot of problems. I'm supposed to split it up into individual methods and just call all the methods in the main. I have to prompt the user for 5 separate inputs, with the first name, last name, and three scores (all in one string of comma separated values). Output is supposed to look something like this: [IMG]http://i.imgur.com/D1OrAYP.png[/IMG] I feel like I might be going down the wrong path, can someone offer a little guidance or at least tell me if I'm headed the right direction? This is what I have so far: [CODE]import java.util.Scanner; public class GradebookJM { public static void main(String [] args) { // Inputs, constant, data declaration, initialization double sc1=0; double sc2=0; double sc3=0; double avg; String headerStr; String init; String id; String bday; String first, last; String c1, c2, c3, c4; int scMin; int scMax; userInput(); // Computations, algorithms avg = averageScore(sc1, sc2, sc3); // Outputs, formatting, display printHeader("Gradebook program prototype (PRGM14)"); printGrades(init, id, bday, sc1, sc2, sc3, scMin, scMax); } public static void userInput() { // Show the input dialog boxes Scanner input = new Scanner(System.in); String str; System.out.println("Please enter student last name, first name, and 3 whole-number test scores [0-100] in comma-separated value (CSV) format for student 1"); str = input.nextLine(); // Recieve the user input, parse it, and trim it int c1 = str.indexOf(",",0); int c2 = str.indexOf(",",c1+1); int c3 = str.indexOf(",",c2+1); int c4 = str.indexOf(",",c3+1); String last = str.substring(0,c1); String first = str.substring(c1+1,c2); String sc1 = str.substring(c2+1,c3); String sc2 = str.substring(c3+1,c4); String sc3 = str.substring(c4+1,str.length()); } public static void initials() { // Convert the first and last names into the student's initials } public static double averageScore(double sc1, double sc2, double sc3) { // Find the average of the three student scores double average = (double)(sc1 + sc2 + sc3) / 3; return average; } public static void printHeader(String headerStr) { // Print the header for the gradebook System.out.println(headerStr); System.out.println(" "); System.out.println("inits\t ID\t birthday\t sc1\t sc2\t sc3\t min\t max\t avg"); System.out.println("-----\t --\t --------\t ---\t ---\t ---\t ---\t ---\t ---"); } public static void printGrades(String init, String id, String bday, double sc1, double sc2, double sc3, int scMin, int scMax) { // Print the lines for each student System.out.println(init + "\t" + id + "\t" + bday + "\t" + sc1 + "\t" + sc2 + "\t" + sc3 + "\t" + scMin + "\t" + scMax); } }[/CODE] Whenever I compile I get a new set of errors, and I fix them and get different ones. Any help would be greatly appreciated.[/QUOTE] I modified your code to do the basics of what I think your trying to do. I don't actually code in Java ever, but it's got a c-style syntax so easy to understand. Hope it helps: [code] public class Student { private String inits, bday, first, last; private double sc[], avg, scMin, scMax; private int id; private static int cur_id = 1; public Student() { sc = new double[3]; id = cur_id++; } public void GetInput() { Scanner input = new Scanner(System.in); String str; while(true) { System.out.println("Please enter student last name, first name, birthday, and 3 whole-number test scores [0-100] in comma-separated value (CSV) format for student " + id); str = input.nextLine(); String[] tokens = str.split(","); if(tokens.length == 6) { SetName(tokens[1].trim(),tokens[0].trim()); bday = tokens[2].trim(); for(int i=0; i<3; i++) sc[i] = Double.parseDouble( tokens[i+3].trim() ); Calculate(); return; } System.out.println("Invlaid input"); } } private void SetName(String f, String l) { first = f; last = l; inits = ""; if(!f.isEmpty()) inits += f.charAt(0); if(!l.isEmpty()) inits += l.charAt(0); inits = inits.toUpperCase(); } private void Calculate() { avg = 0; scMin = Double.MAX_VALUE; for(int i=0; i<3; i++) { avg += sc[i]; scMin = Math.min(scMin, sc[i]); scMax = Math.max(scMax, sc[i]); } avg /= 3; } public void printGrades() { // Print the lines for each student System.out.println(inits + "\t" + id + "\t" + bday + "\t" + sc[0] + "\t" + sc[1] + "\t" + sc[2] + "\t" + scMin + "\t" + scMax + "\t" + avg); } } public class JavaApplication1 { public static void main(String [] args) { Student stu = new Student(); stu.GetInput(); stu.printGrades(); } } [/code]
Hey guys, having a little trouble making a Winforms ImageButton class (C#). My ImageButton class implements the IButtonControl interface but when I add it to a form, and set the button's DialogResult to 'OK' , and then call ShowDialog() on the form, pressing the button does not close the form and return the DialogResult, as the normal Winforms Button control does. Here's my implementation of ImageButton, feel free to do whatever you like with it - C&C welcome. [code] /// <summary> /// A control that displays an image and responds to mouse clicks on the image. /// </summary> [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] [Designer(typeof(ImageButtonDesigner))] [ToolboxItem(typeof(ImageButtonToolboxItem))] public class ImageButton : PictureBox, IButtonControl, INotifyPropertyChanged { #region Constructors /// <summary> /// Initializes a new instance of the ImageButton class using the default initial values. /// </summary> public ImageButton() { DoubleBuffered = true; BackColor = Color.Transparent; SizeMode = PictureBoxSizeMode.AutoSize; } #endregion #region Properties /// <summary> /// Backing field for the DialogResult property. /// </summary> private DialogResult dialogResult; /// <summary> /// Gets or sets a value that is returned to the parent form when the button is clicked. /// </summary> [Category("Behavior")] [Description("The dialog-box result produced in a modal form by clicking the button")] public DialogResult DialogResult { get { return dialogResult; } set { if (Enum.IsDefined(typeof(DialogResult), value)) dialogResult = value; else throw new InvalidEnumArgumentException("value", (int)value, typeof(DialogResult)); } } /// <summary> /// Backing field for the Idle property. /// </summary> private Image idle; /// <summary> /// The image that will be displayed on the control when the mouse is not over a visible part of it. /// </summary> [Category("Appearance")] [Description("The image that will be displayed on the Control when the mouse is not over a visible part of it.")] public Image Idle { get { return idle; } set { idle = value; NotifyPropertyChanged(); } } /// <summary> /// Backing field for the Mouseover property /// </summary> private Image mouseover; /// <summary> /// The image that will be displayed on the control when the mouse is over a visible part of it. /// </summary> [Category("Appearance")] [Description("The image that will be displayed on the control when the mouse is over a visible part of it.")] public Image Mouseover { get { return mouseover; } set { mouseover = value; NotifyPropertyChanged(); } } /// <summary> /// Backing field for the Mousedown property /// </summary> private Image mousedown; /// <summary> /// The image that will be displayed on the control when the left mouse button is held down and the mouse is over a visible part of it. /// </summary> [Category("Appearance")] [Description("The image that will be displayed on the control when the left mouse button is held down and the mouse is over a visible part of it.")] public Image Mousedown { get { return mousedown; } set { mousedown = value; NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the text associated with the control. /// </summary> [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Category("Appearance")] [Description("The text associated with the control.")] public override string Text { get { return base.Text; } set { base.Text = value; } } /// <summary> /// Gets or sets the font of the text displayed by the control. /// </summary> [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Category("Appearance")] [Description("The font used to display text in the control.")] public override Font Font { get { return base.Font; } set { base.Font = value; } } /// <summary> /// Gets or sets the image that is displayed by the PictureBox. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] [Category("Appearance")] [Description("The image displayed in the PictureBox.")] new public Image Image { get { return base.Image; } set { base.Image = value; } } /// <summary> /// Backing field for the ButtonState property. /// </summary> private ButtonStates buttonState = ButtonStates.None; /// <summary> /// The current state of the button. /// </summary> private ButtonStates ButtonState { get { return buttonState; } set { buttonState = value; NotifyPropertyChanged(); } } /// <summary> /// Gets the default size of the control. /// </summary> protected override Size DefaultSize { get { return new Size(75, 23); } } #endregion #region Enums /// <summary> /// Specifies the current state of a button. /// </summary> [Flags] private enum ButtonStates : byte { /// <summary> /// /// </summary> [Description("")] None = 0, /// <summary> /// /// </summary> [Description("")] Default = 1 << 0, /// <summary> /// /// </summary> [Description("")] Mouseover = 1 << 1, /// <summary> /// /// </summary> [Description("")] Mousedown = 1 << 2 } #endregion #region Events /// <summary> /// Occurs when a property value changes. /// </summary> [Category("Property Changed")] [Description("Occurs when a property value changes.")] public event PropertyChangedEventHandler PropertyChanged; #endregion #region Methods /// <summary> /// Raises the System.ComponentModel.PropertyChanged event. /// </summary> /// <param name="propertyName">the name of the property that changed.</param> protected virtual void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } if (propertyName == "Idle") Image = Idle; } /// <summary> /// Notifies the button whether it is the default button so that it can adjust its appearance accordingly. /// </summary> /// <param name="value">true if the button is to have the appearance of the default button; otherwise, false.</param> public void NotifyDefault(bool value) { ButtonState = value ? ButtonState | ButtonStates.Default : ButtonState & ~ButtonStates.Default; } /// <summary> /// Generates a Click event for a button. /// </summary> public void PerformClick() { if (CanSelect) { OnClick(EventArgs.Empty); } } /// <summary> /// Raises the System.Windows.Control.TextChanged event. /// </summary> /// <param name="e">A System.EventArgs that contains the event data.</param> protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); Refresh(); } /// <summary> /// Raises the System.Windows.Forms.Paint event. /// </summary> /// <param name="pe">A PaintEventArgs that contains the event data.</param> protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); if ((!string.IsNullOrEmpty(Text)) && (pe != null) && (base.Font != null)) { SolidBrush drawBrush = new SolidBrush(base.ForeColor); // Calculate the size of the text that will be drawn onto the control. SizeF drawStringSize = pe.Graphics.MeasureString(base.Text, base.Font); // The registration point used to draw the text. PointF drawPoint; if (base.Image != null) drawPoint = new PointF(base.Image.Width / 2 - drawStringSize.Width / 2, base.Image.Height / 2 - drawStringSize.Height / 2); else drawPoint = new PointF(base.Width / 2 - drawStringSize.Width / 2, base.Height / 2 - drawStringSize.Height / 2); pe.Graphics.DrawString(base.Text, base.Font, drawBrush, drawPoint); } } /// <summary> /// Raises the System.Windows.Forms.MouseEnter event. /// </summary> /// <param name="e">A System.EventArgs that contains the event data.</param> protected override void OnMouseEnter(EventArgs e) { base.OnMouseEnter(e); ButtonState |= ButtonStates.Mouseover; Image = Mouseover; } /// <summary> /// Raises the System.Windows.Forms.MouseLeave event. /// </summary> /// <param name="e">A System.EventArgs that contains the event data.</param> protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); ButtonState &= ~ButtonStates.Mouseover; Image = Idle; } /// <summary> /// Raises the System.Windows.Forms.MouseDown event. /// </summary> /// <param name="e">A System.Windows.Forms.MouseEventArgs that contains the event data.</param> protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); ButtonState |= ButtonStates.Mousedown; Image = Mousedown; } /// <summary> /// Raises the System.Windows.Forms.MouseUp event. /// </summary> /// <param name="e">A System.Windows.Forms.MouseEventArgs that contains the event data.</param> protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); ButtonState &= ~ButtonStates.Mousedown; Image = ((ButtonState & ButtonStates.Mouseover) != 0) ? Mouseover : idle; } #endregion } [Serializable] internal class ImageButtonToolboxItem : ToolboxItem { public ImageButtonToolboxItem() : base(typeof(ImageButton)) { } protected ImageButtonToolboxItem(SerializationInfo info, StreamingContext context) { Deserialize(info, context); } protected override IComponent[] CreateComponentsCore(IDesignerHost host) { ImageButton imageButton = (ImageButton)host.CreateComponent(typeof(ImageButton)); Assembly assembly = Assembly.GetAssembly(typeof(ImageButton)); using (Stream streamMouseover = assembly.GetManifestResourceStream("Mvc.Mouseover.png")) using (Stream streamMousedown = assembly.GetManifestResourceStream("Mvc.Mousedown.png")) using (Stream streamIdle = assembly.GetManifestResourceStream("Mvc.Idle.png")) { imageButton.Idle = Image.FromStream(streamIdle); imageButton.Mouseover = Image.FromStream(streamMouseover); imageButton.Mousedown = Image.FromStream(streamMousedown); } return new IComponent[] { imageButton }; } } internal class ImageButtonDesigner : ControlDesigner { protected override void PostFilterAttributes(System.Collections.IDictionary attributes) { base.PostFilterAttributes(attributes); Attribute dockingBehaviour = new DockingAttribute(DockingBehavior.Never); attributes[typeof(DockingAttribute)] = dockingBehaviour; } public override SelectionRules SelectionRules { get { return SelectionRules.Moveable; } } } [/code] Sorry about the messy toolbox item and designer code.. My Question is, Does there need to be anything special implementation wise to get a button control to work on a modal form (in the same way the normal button does) (NB. The Form's BorderStyle property is set to None, don't know if thats important) Thanks, in advance!
[QUOTE=WTF Nuke;44481787]Why does this work? [cpp]glm::vec2 diff = glm::vec2(5,5) - (5,5);[/cpp] Or rather compile, since it doesn't really work.[/QUOTE] With "(5,5)" you are applying the comma operator to operands 5 and 5, which will do nothing and evaluate to 5. So you end up with[cpp]glm::vec2 diff = glm::vec2(5,5) - 5;[/cpp]
It appears to be impossible to find a serialization library for C++ that doesn't suck. I want something like Cereal in the sense that you need only write a member function to make a class (de)serializable, however I also need optional fields, something which cereal doesn't support. Any ideas? Boost isn't an option since Boost.Serialization apparently doesn't work with VC12. EDIT: Found [url]https://github.com/ascheglov/json-cpp[/url] which appears to work for my needs.
[QUOTE=WhiskeyTangoF;44485774]Not sure if it will be much help but fuck it I'll post anyway, forgive me for being a complete novice. I'm trying to create a gradebook program in java for my class, and I'm running into a lot of problems. I'm supposed to split it up into individual methods and just call all the methods in the main. I have to prompt the user for 5 separate inputs, with the first name, last name, and three scores (all in one string of comma separated values). Output is supposed to look something like this: [IMG]http://i.imgur.com/D1OrAYP.png[/IMG] I feel like I might be going down the wrong path, can someone offer a little guidance or at least tell me if I'm headed the right direction? This is what I have so far: [CODE]import java.util.Scanner; public class GradebookJM { public static void main(String [] args) { // Inputs, constant, data declaration, initialization double sc1=0; double sc2=0; double sc3=0; double avg; String headerStr; String init; String id; String bday; String first, last; String c1, c2, c3, c4; int scMin; int scMax; userInput(); // Computations, algorithms avg = averageScore(sc1, sc2, sc3); // Outputs, formatting, display printHeader("Gradebook program prototype (PRGM14)"); printGrades(init, id, bday, sc1, sc2, sc3, scMin, scMax); } public static void userInput() { // Show the input dialog boxes Scanner input = new Scanner(System.in); String str; System.out.println("Please enter student last name, first name, and 3 whole-number test scores [0-100] in comma-separated value (CSV) format for student 1"); str = input.nextLine(); // Recieve the user input, parse it, and trim it int c1 = str.indexOf(",",0); int c2 = str.indexOf(",",c1+1); int c3 = str.indexOf(",",c2+1); int c4 = str.indexOf(",",c3+1); String last = str.substring(0,c1); String first = str.substring(c1+1,c2); String sc1 = str.substring(c2+1,c3); String sc2 = str.substring(c3+1,c4); String sc3 = str.substring(c4+1,str.length()); } public static void initials() { // Convert the first and last names into the student's initials } public static double averageScore(double sc1, double sc2, double sc3) { // Find the average of the three student scores double average = (double)(sc1 + sc2 + sc3) / 3; return average; } public static void printHeader(String headerStr) { // Print the header for the gradebook System.out.println(headerStr); System.out.println(" "); System.out.println("inits\t ID\t birthday\t sc1\t sc2\t sc3\t min\t max\t avg"); System.out.println("-----\t --\t --------\t ---\t ---\t ---\t ---\t ---\t ---"); } public static void printGrades(String init, String id, String bday, double sc1, double sc2, double sc3, int scMin, int scMax) { // Print the lines for each student System.out.println(init + "\t" + id + "\t" + bday + "\t" + sc1 + "\t" + sc2 + "\t" + sc3 + "\t" + scMin + "\t" + scMax); } }[/CODE] Whenever I compile I get a new set of errors, and I fix them and get different ones. Any help would be greatly appreciated.[/QUOTE] You might be getting errors because you're not actually prompting bday. I assume java defaults strings to null if you declare them but don't initialize, but i'm not sure. if it does, nevermind. i'm terrible at java.
So I'm beating my head against a wall trying to figure out how to get this ByteBuffer to work properly on the server end. Using Java 7, I am using non-blocking datagrams (UDP) for my networking, because I feel that the overhead of a stream like TCP/IP is unnecessary for the sporadic and small packets I intend to send (and because I want some practice with datagrams / UDP). I am starting basic, with just sending two char packets to the server and catching them on the server. I've got the set-up all done and the client working, but the server isn't working correctly. It just keeps catching the first one. Here is what my debug is stating: [code]CLIENT: Buffer = "Hello server!". CLIENT: Buffer = "Test 2!". CLIENT: Buffer = "Test 3!". SERVER: Received packet from "/127.0.0.1" -> "Hello server!". SERVER: Received packet from "/127.0.0.1" -> "Hello server!". SERVER: Received packet from "/127.0.0.1" -> "Hello server!". [/code] As you can see, every time it is catching the first message, rather than the later ones. Here is the code, in full: [code]package main; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.DatagramChannel; public class Core { public static void main(String[] args) throws IOException { // Datagram / UDP testing ByteBuffer clientBuffer = ByteBuffer.allocate(64); CharBuffer clientBufferView = clientBuffer.asCharBuffer(); InetSocketAddress serverAddr = new InetSocketAddress("127.0.0.1",36797); clientBuffer.clear(); clientBufferView.clear(); DatagramChannel server = DatagramChannel.open(); server.setOption(StandardSocketOptions.SO_REUSEADDR, true); server.configureBlocking(false); server.bind(new InetSocketAddress(36797)); DatagramChannel client = DatagramChannel.open(); client.configureBlocking(false); clientBufferView.clear(); clientBufferView.append("Hello server!"); clientBufferView.flip(); System.out.printf("CLIENT: Buffer = \"%s\".\n",clientBufferView.toString()); client.send(clientBuffer, serverAddr); clientBufferView.clear(); clientBufferView.append("Test 2!"); clientBufferView.flip(); System.out.printf("CLIENT: Buffer = \"%s\".\n",clientBufferView.toString()); client.send(clientBuffer, serverAddr); clientBufferView.clear(); clientBufferView.append("Test 3!"); clientBufferView.flip(); System.out.printf("CLIENT: Buffer = \"%s\".\n",clientBufferView.toString()); client.send(clientBuffer, serverAddr); ByteBuffer serverBuffer = ByteBuffer.allocate(64); SocketAddress packetSender; // Server read boolean alive = true; char c; while (alive) { if ((packetSender = server.receive(serverBuffer)) != null) { serverBuffer.flip(); System.out.printf("SERVER: Received packet from \"%s\" -> \"",((InetSocketAddress)packetSender).getAddress().toString()); while ((c = serverBuffer.getChar()) != '\0') { System.out.printf("%s",c); } System.out.printf("\".\n"); } } } }[/code] I've tried doing things like mark() on serverBuffer on creation, rewind() inside the conditional before printing, and mark() on the conditional after reading, but all that does is negate the need for the flip(); it doesn't actually do what I want. Note that if I do not have the flip() on the server's side, I get a buffer underflow error. I won't lie when I say I only have a rudimentary grasp on the operation of buffers in Java; I am confident that I am just making an idiot mistake that is easily rectified. If that is the case, please point it out, and point it out as such. :v:
I can't for the life of me get visual studio to work on my new pc. When I try to compile anything I get errors about not being able to find .NET 4.5, when 4.51 is installed. If I try to change the target, only 2 and 3 come up in the list. I've tried out visual studio c# 2010, too, with the same issue. I think it may be to do with the fact I have windows installed on an ssd, and set the registry to default the install location to my main hard drive, but I'm not entirely sure why and how I could fix this.
One thing that's really annoying me about simulating player movement on the server is that the client may send input packets but the server could receive one but be waiting on the next due to latency. The problem with that is that the player movement still needs to be simulated but it hasn't got the next input from the client, it's either use the last input or use no input, either results in the player going out of sync and needing to be corrected (which I'm doing but it would be nice for the player to go out of sync only when I can't properly predict what's happening) It looks like it's something I just have to accept, the only other solution is to simulate whenever input comes in at the time but that can be abused, either by sending no input packets or sending incorrect duration.
I'm trying to make an online shopping cart simulator in Java for an assignment, I've started the project but can't figure out what to do. [code] import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; import java.text.DecimalFormat; import java.text.NumberFormat; public class Shopping { /** * In this program you will replicate an online shopping * cart. * You will use the Item class to represent items in * your shopping cart. * You will use the Shop class to discover Products that may be * added to your shopping cart. */ public static void main(String[] args) throws IOException { // create shopping cart using an ArrayList ArrayList<Item> shoppingCart = new ArrayList<Item>(); // create and instance of the shop inventory Shop shop = new Shop(); Scanner scan = new Scanner(System.in); NumberFormat money = NumberFormat.getCurrencyInstance(); final int MAXOPTS = 7; boolean working = true; int choice = 0; int input = 0; double total = 0; Item item; Product product; //final String intList = "Inventory.txt"; while (working) { System.out.println("\nMenu options:"); System.out.println("0 Exit"); System.out.println("1 Add an item to your cart"); System.out.println("2 Remove an item from your cart"); System.out.println("3 Change item quantity"); System.out.println("4 View the items in your cart"); System.out.println("5 Add up the total and exit"); System.out.println("6 Empty your cart"); System.out.println("7 List inventory"); System.out.println("Select an option:"); choice = scan.nextInt(); if (choice < 0 || choice > MAXOPTS) { System.out.println("Enter a value between 0 and " + MAXOPTS); } else { switch (choice) { case 0: //exit working = false; System.out.println("Goodbye"); break; case 1: // Add an item System.out.println("Enter a product ID to add:"); input = scan.nextInt(); product = shop.lookup(input); if (product != null) { item = new Item(product); shoppingCart.add(item); } break; case 2: //remove from the list System.out.println("Enter an item to remove:"); input = scan.nextInt(); item = new Integer(input); if (intList.contains(item)) { intList.remove(item); System.out.println(item + " has been removed."); } else { System.out.println(item + " was not found in your shopping cart."); } break; case 3: System.out.println("Enter the new quantity:"); input = scan.nextInt(); delta = new Integer(input); System.out.println("Changed"); break; case 4: //view the items in your cart System.out.println(intList); break; case 5: //Exit and add up the total for (int i = 0; i<intList.size(); i++) { item = intList.get(i); total = total + item.intValue(); } System.out.println("Total is "+ total); System.out.println("Goodbye"); working = false; break; case 6: //Empty the list intList.clear(); System.out.println("Empty"); break; case 7: // list the items for sale in the shop // **************************** // *** Add code to complete *** // **************************** break; } } } } } [/code] [code] import java.text.DecimalFormat; import java.text.NumberFormat; /** * The Item class implements the shopping cart items. */ public class Item { private int itemID; private Product product; private int quantityOrdered; private static int nextID = 1; private double price; // used to create a new ID for an item //constructor public Item() { itemID = nextID++; product = null; quantityOrdered = 0; double price = 0.0; } //constructor with parameters public Item(Product inProduct, int inQuant, double inPrice) { product = inProduct; quantityOrdered = inQuant; price = inPrice; } //constructor with parameters public Item(Product inProduct, int inQuant) { // **************************** // *** Add code to complete *** // **************************** } //getter setter public methods for each instance data /** * Gets the product name for this Item. * * @return name */ public String getproductName() { // **************************** // *** Add code to complete *** // **************************** } /** * Gets the product price for this Item. * * @return price */ public double getPrice() { return price; } /** * Gets the quantity in cart for this Item. * * @return quantity */ public int getQuantity() { return quantityOrdered; } /** * Sets the quantity ordered for this item * * @param inQuan the quantity on hand */ public void setquantityOrdered(int inQuan) { this.quantityOrdered = inQuan; } /** * Adjusts the quantity ordered for this item * * @param delta for adjustment (+/-) */ public void adjustquantityOrdered(int delta) { // **************************** // *** Add code to complete *** // **************************** } /** * Compare two items being equal * * @return result */ public boolean equals(Item item) { boolean result = false; if (this.getproductName().equals(item.getproductName()) && this.getPrice() == item.getPrice()) result = true; else result = false; return result; } public String toString() { String result=""; return result; } } [/code]
Okay, amazingly, this isn't related to my previous problem. For a program I am working on for my networking course, I am using Java (language is of our choice), and one of the command parameters the server has to be able to utilize is: [quote] -lacctport value This indicates what source port will be accepted on the left side connection. Value is a valid port address which in the case is any 16-bit unsigned integer value, i.e. "..65535. It may also be the wild-card *, indicating any port is acceptable. The default is to accept any valid source port address. Once again the * should be quoted to prevent the shell from attempting to perform file name expansion.[/quote] In a language like C, this would be easy to implement - do a listen, check the port of the socket you listened into, and if it's a port you want to accept, then you accept it. But in Java, there is no (to my knowledge, and I just spent the past 40 minutes searching online about this...) way to split listen() from accept(). I've seen mention of the (apparently) mythical and elusive "SecurityManager" and "SocketPermissions" and such, but I can't find anything at all on how to actually [B]implement[/B] these things to do what I want. Can someone please help me? Thanks. :v:
This is more a theory question than anything else. In my basic path tracer I only trace from the eye, to an object, calculate a new ray and continue, I don't do importance sampling or bidirectional tracing. I am not sure if I am correct in saying that this makes it difficult, if not impossible to implement a BDRF since that is by definition a bidirectional model. If I wanted however to implement something like the Beckmann distribution to model microfacets would there be a way I could approximate the light direction and thus half vector to get a reasonable result? I did have an idea to randomly offset the normal within a cone when calculating the reflected/refracted ray based upon a microfacet distribution constant for the material, as this is what you are modelling, however would this be physically accurate?
[QUOTE=Rifle;44497625]I'm trying to make an online shopping cart simulator in Java for an assignment, I've started the project but can't figure out what to do. [/QUOTE] It looks mostly done to me, what did they ask you to do. im assuming they need you to do more than number 7. The simplest way to do what i think they need you to do: when the program is started read inventory.txt for items, if you dont know how to read files and parse just google it. java is p forgiving for beginners. use a container like a linked list to store whats defined inventory.txt. create a linkedlist of class shop. doesn't have to be a linked list, but its the easiest to implement. start an empty linked list (or a tree or whatever) of class item start reading user input whenever they add an item to cart just check to make sure its not already in the cart, otherwise add a new node to the linked list of class item. when they remove an item just remove the node, etc. linked list has all these methods done for you, so you barely have to do anything. [editline]9th April 2014[/editline] did they give you an assignment sheet?
how do i sort an array -pitts
That may sound stupid, but here it goes... How the hell does one convert a sequence ("\n", "A", etc) into their actual int counterpart?
[QUOTE=JohnnyOnFlame;44511095]That may sound stupid, but here it goes... How the hell does one convert a sequence ("\n", "A", etc) into their actual int counterpart?[/QUOTE] What language are we talking about here? I know for Java that you can simply cast them to integers when you want to see the ASCII equivalent: [code] System.out.println((int) 'A'); [/code]
[QUOTE=Contron;44511474]What language are we talking about here? I know for Java that you can simply cast them to integers when you want to see the ASCII equivalent: [code] System.out.println((int) 'A'); [/code][/QUOTE] It's user input, like reading from stdin.
Trying to use lua for the configuration files for my path tracer as using json makes things that should be simple such as a circle of spheres too difficult for my liking. I have found luatable++ and whilst it's nice I'd like to try and simplify the bindings for a class. I've currently got it down to the following however would there be any way to remove the duplication as both cases are more or less the same. The only way I can think of doing it is setting up the defines for the getter, including a file, for the setter, including the same file, but that seems horrible. [CODE]LUA_TABLE_GETTER(Camera) LUA_TABLE_GETTER_MEMBER(Origin) LUA_TABLE_GETTER_MEMBER(Pitch) LUA_TABLE_GETTER_MEMBER(Yaw) LUA_TABLE_GETTER_MEMBER(Fov) LUA_TABLE_GETTER_MEMBER(FocalPoint) LUA_TABLE_GETTER_MEMBER(Aperture) LUA_TABLE_GETTER_END LUA_TABLE_SETTER(Camera) LUA_TABLE_SETTER_MEMBER(Origin) LUA_TABLE_SETTER_MEMBER(Pitch) LUA_TABLE_SETTER_MEMBER(Yaw) LUA_TABLE_SETTER_MEMBER(Fov) LUA_TABLE_SETTER_MEMBER(FocalPoint) LUA_TABLE_SETTER_MEMBER(Aperture) LUA_TABLE_SETTER_END[/CODE]
[QUOTE=JohnnyOnFlame;44511502]It's user input, like reading from stdin.[/QUOTE] If you're using C and you're getting characters from the user, you don't even need a cast to convert it to an int. [code]char letter = 'A'; int value = letter; //value will be 65[/code] If the user input is in a char* buffer, you can access it like this: [code]char buffer[10]; //Get input here int value = buffer[0]; //Get value of first character[/code] For other languages it's generally the same concept, though some may require casting - an explicit '(int)' before the character.
[QUOTE=Fredo;44513114]If you're using C and you're getting characters from the user, you don't even need a cast to convert it to an int. [code]char letter = 'A'; int value = letter; //value will be 65[/code] If the user input is in a char* buffer, you can access it like this: [code]char buffer[10]; //Get input here int value = buffer[0]; //Get value of first character[/code] For other languages it's generally the same concept, though some may require casting - an explicit '(int)' before the character.[/QUOTE] You got it all wrong, mostly because the question was awfully worded. Let me provide proper context like I should've done already. I'm extending the functionality of a certain parser, one of the tasks that is currently not done is reading '\n' (single-quote sequences). I was wondering if there was any pre-defined function that would do (char*)"\\n" -> (int)'\n', or if I would have to write my own and abuse of some switch cases and stuff.
[QUOTE=JohnnyOnFlame;44513351]You got it all wrong, mostly because the question was awfully worded. Let me provide proper context like I should've done already. I'm extending the functionality of a certain parser, one of the tasks that is currently not done is reading '\n' (single-quote sequences). I was wondering if there was any pre-defined function that would do (char*)"\\n" -> (int)'\n', or if I would have to write my own and abuse of some switch cases and stuff.[/QUOTE] If you know that the input (a char*) will be exactly 1 character long couldn't you just return that character? [code]int to_int(char* str) { return str[0]; }[/code] You could also dereference the pointer by doing *str and it would do the same thing Or am I missing something else?
Are you trying to convert strings to numbers?
Forget it. It's better to just write a simple function with a huge switch case to deal w. it.
Could you give some more examples of input and expected output? Are you trying to get "\n" (as in a backslash followed by the letter n) to convert to the newline character? For that I would use a switch statement, though it wouldn't be huge. The only useful ones I can think of are \n (newline), \t (tab), and \\ (backslash), though there are a few others.
[QUOTE=JohnnyOnFlame;44514054]Forget it. It's better to just write a simple function with a huge switch case to deal w. it.[/QUOTE] I think what you're trying to do is incredibly easy but you need to show us some expected input and output like Fredo said, since you really haven't explained your problem very well.
[QUOTE=BackwardSpy;44514162]I think what you're trying to do is incredibly easy but you need to show us some expected input and output like Fredo said, since you really haven't explained your problem very well.[/QUOTE] What I'm trying to do -is- easy, I was just wondering if there was a standard way of doing it so I wouldn't have useless crap in the codebase. Input: [code] se (char = '\n') entao //---> if (char = '\n') then [/code] which the lexer should translate into these tokens: [code] KEYWORD se, OPEN PAREN, IDENTIFIER char, EQ =, NUMBER 10, <-------- that is '\n' CLOSE PAREN KEYWORD entao [/code] During the code chewing, the lexer will be decoding the sequence enclosed by apostrophes into a number for later use. Anyways, once I'm done with compound variables (c structs?) I'll be back at this. Sorry for the terrible wording of it, there's already quite a bit in my head right now.
[QUOTE=JohnnyOnFlame;44514309]What I'm trying to do -is- easy, I was just wondering if there was a standard way of doing it so I wouldn't have useless crap in the codebase. Input: [code] se (char = '\n') entao //---> if (char = '\n') then [/code] which the lexer should translate into these tokens: [code] KEYWORD se, OPEN PAREN, IDENTIFIER char, EQ =, NUMBER 10, <-------- that is '\n' CLOSE PAREN KEYWORD entao [/code] During the code chewing, the lexer will be decoding the sequence enclosed by apostrophes into a number for later use. Anyways, once I'm done with compound variables (c structs?) I'll be back at this. Sorry for the terrible wording of it, there's already quite a bit in my head right now.[/QUOTE] I'm probably still misunderstanding this but surely it's kind of implicitly done? A char is just a byte, and a char representing the '\n' character [I]is[/I] also containing a value of 10. There's no magic that needs to be done here, '\n' and 10 are both equal and the same. If anything you just need to cast it to an integer. But, like I said, I'm probably misunderstanding you because I'm pretty sure you already know all that.
I was confused until he mentioned a lexer, suggesting he want's to know how best to handle escape sequences while parsing text. A switch is fine and will only have like ~6 statements which only needs to be run when you reach a \.
Greetings, Is there a cross-compiler to compile something to Linux-ARM from Windows ? And, does it really works ? Thanks.
programming beginner here but can anyone explain the following logic in perl? If you have a text file with more than one line and you use split on it, printing $array[0] will print the entire first column, $array[1] second column etc. If you use a foreach loop it will properly print everything. I tried treating it as a two dimensional array but $array[0][0] will only print blank space.
[QUOTE=ashxu;44516659]programming beginner here but can anyone explain the following logic in perl? If you have a text file with more than one line and you use split on it, printing $array[0] will print the entire first column, $array[1] second column etc. If you use a foreach loop it will properly print everything. I tried treating it as a two dimensional array but $array[0][0] will only print blank space.[/QUOTE] Why... are you learning Perl as a beginner?
Sorry, you need to Log In to post a reply to this thread.