Search Results

Search found 39440 results on 1578 pages for 'possible homework'.

Page 10/1578 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • question about partition

    - by davit-datuashvili
    i have question about hoare partition method here is code and also pseudo code please if something is wrong correct pseudo code HOARE-PARTITION ( A, p, r) 1 x ? A[ p] 2 i ? p-1 3 j ? r +1 4 while TRUE 5 do repeat j ? j - 1 6 until A[ j ] = x 7 do repeat i ? i + 1 8 until A[i] = x 9 if i < j 10 then exchange A[i] ? A[ j ] 11 else return j and my code public class Hoare { public static int partition(int a[],int p,int r) { int x=a[p]; int i=p-1; int j=r+1; while (true) { do { j=j-1; } while(a[j]>=x); do { i=i+1; } while(a[i]<=x); if (i<j) { int t=a[i]; a[i]=a[j]; a[j]=t; } else { return j; } } } public static void main(String[]args){ int a[]=new int[]{13,19,9,5,12,8,7,4,11,2,6,21}; partition(a,0,a.length-1); } } and mistake is this error: Class names, 'Hoare', are only accepted if annotation processing is explicitly requested 1 error any ideas

    Read the article

  • string reverse without new array

    - by Codeguru
    hi can anybody tell me the error in this? #include<stdio.h> int main() { char a[]="abcdefgh"; int i=0; int n=strlen(a); char *first; char *second; char *c; *first=a[0]; *second=a[7]; for(i=0;i<=n/2;i++) { *c=*first; *first=*second; *second=*c; first++; second--; } for(i=0;i<=7;i++) { printf("%c",a[i]); } }

    Read the article

  • Why does this program stop running?

    - by designloper
    Hi everyone....I am developing a card making system...nothing fancy. Right got this far but program now stops running with no error when running after the first card sample i.e. " Enter 'OK' if this card is OK, otherwise enter an alternative border character: + ". Any suggestions Java Masters? //Ask user for input //makes use of print line method System.out.println("Enter name: "); //took the variables //called the object of the scanner 'cardOrder' //and use the Scanner objects method '.nextLine' //to read the next line of the input firstName = cardOrder.nextLine(); mInitial = cardOrder.nextLine(); lastName = cardOrder.nextLine(); //Print out the "Here is a sample card" + the first name, middle initial and last name System.out.println("Here is a sample card: \n\n" + firstName + mInitial + lastName + "**************" + "**************" + firstName + mInitial + lastName + "\n* *" + "\n*" + " " + firstName + mInitial + lastName + " *" + "\n* *\n" + firstName + mInitial + lastName +"**************" + "**************" + firstName + mInitial + lastName + "\n"); //Ask user is the card is OK to proceed to order query or if they want an alternative border character: + System.out.println("Enter 'OK' if this card is OK, otherwise enter an alternative border character: + "); //Check if user entered "OK" and store it in var optionA optionA = cardOrder.nextLine(); //test if (a == optionA){ System.out.println("\nHow many cards would you like? "); cardsOrdered = cardOrder.nextInt(); equals = (int) (cardPriceA * cardsOrdered); System.out.println("The price of " + cardsOrdered + " cards"+ " is £" + equals + ".\n"); System.out.println("No Discount given."); } else if(b == optionA) { //Print out the "Here is a sample card" + the first name, middle initial and last name System.out.println("Here is a sample card: \n\n" + firstName + mInitial + lastName + "++++++++++++++" + "++++++++++++++" + firstName + mInitial + lastName + "\n+ +" + "\n+" + " " + firstName + mInitial + lastName + " +" + "\n+ +\n" + firstName + mInitial + lastName +"++++++++++++++" + "++++++++++++++" + firstName + mInitial + lastName + "\n"); //Ask user is the card is OK to proceed to order query or if they want an alternative border character: + System.out.println("Enter 'OK' if this card is OK, otherwise enter an alternative border character: OK "); //Check if user entered "OK" and store it in var optionA optionA = cardOrder.nextLine(); if (a == optionA){ System.out.println("\nHow many cards would you like? "); cardsOrdered = cardOrder.nextInt(); equals = (int) (cardPriceA * cardsOrdered); System.out.println("The price of " + cardsOrdered + " cards"+ " is £" + equals + ".\n"); System.out.println("No Discount given."); } } else if (c == optionA) {//Print out the "Here is a sample card" + the first name, middle initial and last name System.out.println("Here is a sample card: \n\n" + firstName + mInitial + lastName + "**************" + "**************" + firstName + mInitial + lastName + "\n* *" + "\n*" + " " + firstName + mInitial + lastName + " *" + "\n* *\n" + firstName + mInitial + lastName +"**************" + "**************" + firstName + mInitial + lastName + "\n"); //Ask user is the card is OK to proceed to order query or if they want an alternative border character: + System.out.println("Enter 'OK' if this card is OK, otherwise enter an alternative border character: + "); //Check if user entered "OK" and store it in var optionA optionA = cardOrder.nextLine(); if (a == optionA){ System.out.println("\nHow many cards would you like? "); cardsOrdered = cardOrder.nextInt(); equals = (int) (cardPriceA * cardsOrdered); System.out.println("The price of " + cardsOrdered + " cards"+ " is £" + equals + ".\n"); System.out.println("No Discount given."); } }

    Read the article

  • 5x5 matrix multiplication in C

    - by Rick
    I am stuck on this problem in my homework. I've made it this far and am sure the problem is in my three for loops. The question directly says to use 3 for loops so I know this is probably just a logic error. #include<stdio.h> void matMult(int A[][5],int B[][5],int C[][5]); int printMat_5x5(int A[5][5]); int main() { int A[5][5] = {{1,2,3,4,6}, {6,1,5,3,8}, {2,6,4,9,9}, {1,3,8,3,4}, {5,7,8,2,5}}; int B[5][5] = {{3,5,0,8,7}, {2,2,4,8,3}, {0,2,5,1,2}, {1,4,0,5,1}, {3,4,8,2,3}}; int C[5][5] = {0}; matMult(A,B,C); printMat_5x5(A); printf("\n"); printMat_5x5(B); printf("\n"); printMat_5x5(C); return 0; } void matMult(int A[][5], int B[][5], int C[][5]) { int i; int j; int k; for(i = 0; i <= 2; i++) { for(j = 0; j <= 4; j++) { for(k = 0; k <= 3; k++) { C[i][j] += A[i][k] * B[k][j]; } } } } int printMat_5x5(int A[5][5]){ int i; int j; for (i = 0;i < 5;i++) { for(j = 0;j < 5;j++) { printf("%2d",A[i][j]); } printf("\n"); } } EDIT: Here is the question, sorry for not posting it the first time. (2) Write a C function to multiply two five by five matrices. The prototype should read void matMult(int a[][5],int b[][5],int c[][5]); The resulting matrix product (a times b) is returned in the two dimensional array c (the third parameter of the function). Program your solution using three nested for loops (each generating the counter values 0, 1, 2, 3, 4) That is, DO NOT code specific formulas for the 5 by 5 case in the problem, but make your code general so it can be easily changed to compute the product of larger square matrices. Write a main program to test your function using the arrays a: 1 2 3 4 6 6 1 5 3 8 2 6 4 9 9 1 3 8 3 4 5 7 8 2 5 b: 3 5 0 8 7 2 2 4 8 3 0 2 5 1 2 1 4 0 5 1 3 4 8 2 3 Print your matrices in a neat format using a C function created for printing five by five matrices. Print all three matrices. Generate your test arrays in your main program using the C array initialization feature. enter code here

    Read the article

  • Broken corba object references

    - by cube
    I'm working on a homework and got stuck. The task is to serve objects using a default servant. But when I try to use the reference, weird things happen. Some part of corba prints a stack trace, but no exception is thrown. The problem happens when the server receives the reference and should call some method on it. The reference is then shortened and doesn't contain the object ID (which means that my servant implementation can't do anything reasonable). This is the implementation of the servant, where the problem appears: public class ModelFileImpl extends ModelFilePOA{ @Override public String getName() { try { return new String(_poa().reference_to_id(_this_object())); } catch (Throwable e) {} assert false; return null; } } If I take _this_object().toString() inside the try block and put it into dior -i i get this: ------IOR components----- TypeId : IDL:termproject/idl/ModelFile:1.0 TAG_INTERNET_IOP Profiles: Profile Id: 0 IIOP Version: 1.2 Host: 127.0.0.1 Port: 45954 Object key (URL): %AF%AB%CB%00%00%00%00%20Q%BA%F4%FF%00%00%00%01%00%00%00%00%00%00%00%01%0000%00%08RootPOA%00%00%00%00%08%00%00%00%02%00%00%00%00%14 Object key (hex): 0xAF AB CB 00 00 00 00 20 51 BA F4 FF 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 08 52 6F 6F 74 50 4F 41 00 00 00 00 08 00 00 00 02 00 00 00 00 14 -- Found 2 Tagged Components-- #0: TAG_CODE_SETS ForChar native code set Id: ISO8859_1 Char Conversion Code Sets: UTF8 , Unknown TCS: 10020 ForWChar native code set Id: UTF16 WChar Conversion Code Sets: Unknown TCS: 10100 Unknown tag : 38 however the part of server that makes the reference and the client see the reference as ------IOR components----- TypeId : IDL:termproject/idl/ModelFile:1.0 TAG_INTERNET_IOP Profiles: Profile Id: 0 IIOP Version: 1.2 Host: 127.0.0.1 Port: 45954 Object key (URL): %AF%AB%CB%00%00%00%00%20Q%BA%F4%FF%00%00%00%01%00%00%00%00%00%00%00%02%00%00%00%08RootPOA%00%00%00%00%09modelPoa%00%00%00%00%00%00%00%10testModel1.MyIDL%14 Object key (hex): 0xAF AB CB 00 00 00 00 20 51 BA F4 FF 00 00 00 01 00 00 00 00 00 00 00 02 00 00 00 08 52 6F 6F 74 50 4F 41 00 00 00 00 09 6D 6F 64 65 6C 50 6F 61 00 00 00 00 00 00 00 10 74 65 73 74 4D 6F 64 65 6C 31 2E 4D 79 49 44 4C 14 -- Found 2 Tagged Components-- #0: TAG_CODE_SETS ForChar native code set Id: ISO8859_1 Char Conversion Code Sets: UTF8 , Unknown TCS: 10020 ForWChar native code set Id: UTF16 WChar Conversion Code Sets: Unknown TCS: 10100 Unknown tag : 38 ("modelPoa" (the name of the poa working with default clients) and "testModel1.MyIDL" (the identifier of the object) in the object key are missing in the first one) I've tried sniffing the traffic and found out that the client still sends the correct reference. This is how i create the references: ret[i] = ModelFileHelper.narrow(modelFilePoa.create_reference_with_id(files[i].getBytes(), ModelFileHelper.id())); And this is how i set up the server: // init ORB ORB orb = ORB.init(args, null); // init POA POA poa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); // create the POA for the models. Policy[] policies = { poa.create_request_processing_policy(RequestProcessingPolicyValue.USE_DEFAULT_SERVANT), poa.create_servant_retention_policy(ServantRetentionPolicyValue.NON_RETAIN), poa.create_id_assignment_policy(IdAssignmentPolicyValue.USER_ID) }; POA modelPoa = poa.create_POA("modelPoa", poa.the_POAManager(), policies); modelPoa.the_POAManager().activate(); modelPoa.set_servant(new ModelFileImpl()); modelPoa.the_POAManager().activate(); ModelStoreImpl impl = new ModelStoreImpl(modelPoa); // create the object reference org.omg.CORBA.Object obj = poa.servant_to_reference(impl); // ... store the IOR file ... orb.run(); I'd be really grateful for any pointers (or references :-) )

    Read the article

  • a pdf reader - please guide - a step by step guidence - reference to guidence-

    - by user287745
    have to make a hardware project using micro controller, memory, screens, etc. is it possible to make an independent .dpf / documents reader, which is capable of running on battery power.? please note dont want to use any technology which needs licensing all free wares readers etc and programing say assembly and c or flash or any. please help, have submitted proposal of pdf reader project (independent hardware), many say its impossible, wht should i do??

    Read the article

  • HttpURLConnection timeout question

    - by Malachi
    I want to return false if the URL takes more then 5 seconds to connect - how is this possible using java? Here is the code I am using to check if the URL is valid HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); return (con.getResponseCode() == HttpURLConnection.HTTP_OK);

    Read the article

  • regular expression of 0's and 1's

    - by Lopa
    Hello all I got this question which asks me to figure out why is it foolish to write a regular expression for the language that consists of strings of 0's and 1's that are palindromes( they read the same backwards and forwards). part 2 of the question says using any formal mechanism of your choice, show how it is possible to express the language that consists of strings of 0's and 1's that are palindromes?

    Read the article

  • How can I match a phone number with a regex? [closed]

    - by Zerobu
    Possible Duplicate: A comprehensive regex for phone number validation I would like a regular expression in this format. It Must match one of the following formats: (###)###-#### ###-###-#### ###.###.#### ########## Strip all whitespace. Make sure it's a valid phone number, then (if necessary) translate it to the first format listed above.

    Read the article

  • def constrainedMatchPair(firstMatch,secondMatch,length):

    - by smart
    matches of a key string in a target string, where one of the elements of the key string is replaced by a different element. For example, if we want to match ATGC against ATGACATGCACAAGTATGCAT, we know there is an exact match starting at 5 and a second one starting at 15. However, there is another match starting at 0, in which the element A is substituted for C in the key, that is we match ATGC against the target. Similarly, the key ATTA matches this target starting at 0, if we allow a substitution of G for the second T in the key string. consider the following steps. First, break the key string into two parts (where one of the parts could be an empty string). Let's call them key1 and key2. For each part, use your function from Problem 2 to find the starting points of possible matches, that is, invoke starts1 = subStringMatchExact(target,key1) and starts2 = subStringMatchExact(target,key2) The result of these two invocations should be two tuples, each indicating the starting points of matches of the two parts (key1 and key2) of the key string in the target. For example, if we consider the key ATGC, we could consider matching A and GC against a target, like ATGACATGCA (in which case we would get as locations of matches for A the tuple (0, 3, 5, 9) and as locations of matches for GC the tuple (7,). Of course, we would want to search over all possible choices of substrings with a missing element: the empty string and TGC; A and GC; AT and C; and ATG and the empty string. Note that we can use your solution for Problem 2 to find these values. Once we have the locations of starting points for matches of the two substrings, we need to decide which combinations of a match from the first substring and a match of the second substring are correct. There is an easy test for this. Suppose that the index for the starting point of the match of the first substring is n (which would be an element of starts1), and that the length of the first substring is m. Then if k is an element of starts2, denoting the index of the starting point of a match of the second substring, there is a valid match with one substitution starting at n, if n+m+1 = k, since this means that the second substring match starts one element beyond the end of the first substring. finally the question is Write a function, called constrainedMatchPair which takes three arguments: a tuple representing starting points for the first substring, a tuple representing starting points for the second substring, and the length of the first substring. The function should return a tuple of all members (call it n) of the first tuple for which there is an element in the second tuple (call it k) such that n+m+1 = k, where m is the length of the first substring.

    Read the article

  • circular shift c

    - by simion
    I am doing some past papers and noticed a question where i have to shift the int one place to the right and return it i no in java i can just return n 1; is this possible in c? or is there a typically more compelx way of doing it :D. The method we were given is as follows // Return n after a right circular 1-bit shift unsigned int right_circular_shift_1(unsigned int n) {

    Read the article

  • Sorting a list of numbers with modified cost

    - by David
    First, this was one of the four problems we had to solve in a project last year and I couldn’t find a suitable algorithm so we handle in a brute force solution. Problem: The numbers are in a list that is not sorted and supports only one type of operation. The operation is defined as follows: Given a position i and a position j the operation moves the number at position i to position j without altering the relative order of the other numbers. If i j, the positions of the numbers between positions j and i - 1 increment by 1, otherwise if i < j the positions of the numbers between positions i+1 and j decreases by 1. This operation requires i steps to find a number to move and j steps to locate the position to which you want to move it. Then the number of steps required to move a number of position i to position j is i+j. We need to design an algorithm that given a list of numbers, determine the optimal (in terms of cost) sequence of moves to rearrange the sequence. Attempts: Part of our investigation was around NP-Completeness, we make it a decision problem and try to find a suitable transformation to any of the problems listed in Garey and Johnson’s book: Computers and Intractability with no results. There is also no direct reference (from our point of view) to this kind of variation in Donald E. Knuth’s book: The art of Computer Programing Vol. 3 Sorting and Searching. We also analyzed algorithms to sort linked lists but none of them gives a good idea to find de optimal sequence of movements. Note that the idea is not to find an algorithm that orders the sequence, but one to tell me the optimal sequence of movements in terms of cost that organizes the sequence, you can make a copy and sort it to analyze the final position of the elements if you want, in fact we may assume that the list contains the numbers from 1 to n, so we know where we want to put each number, we are just concerned with minimizing the total cost of the steps. We tested several greedy approaches but all of them failed, divide and conquer sorting algorithms can’t be used because they swap with no cost portions of the list and our dynamic programing approaches had to consider many cases. The brute force recursive algorithm takes all the possible combinations of movements from i to j and then again all the possible moments of the rest of the element’s, at the end it returns the sequence with less total cost that sorted the list, as you can imagine the cost of this algorithm is brutal and makes it impracticable for more than 8 elements. Our observations: n movements is not necessarily cheaper than n+1 movements (unlike swaps in arrays that are O(1)). There are basically two ways of moving one element from position i to j: one is to move it directly and the other is to move other elements around i in a way that it reaches the position j. At most you make n-1 movements (the untouched element reaches its position alone). If it is the optimal sequence of movements then you didn’t move the same element twice.

    Read the article

  • Is there a way to read a c-string and then an int with a single scanf in C?

    - by Aux
    Hey, I'm trying to get this function to get the following output with the listed input, the "..." is where I'm not sure what to write: void Question8(void) { char sentence[100]; int grade; scanf(….); printf("%s %d", sentence, grade); } Input: My CS Grade is 1000 Output: My CS Grade is 100 However, the kicker is that I need the scanf to read a c-string and then an int with a single scanf command, is this even possible?

    Read the article

  • Problem setting output flags for ALU in "Nand to Tetris" course

    - by MahlerFive
    Although I tagged this homework, it is actually for a course which I am doing on my own for free. Anyway, the course is called "From Nand to Tetris" and I'm hoping someone here has seen or taken the course so I can get some help. I am at the stage where I am building the ALU with the supplied hdl language. My problem is that I can't get my chip to compile properly. I am getting errors when I try to set the output flags for the ALU. I believe the problem is that I can't subscript any intermediate variable, since when I just try setting the flags to true or false based on some random variable (say an input flag), I do not get the errors. I know the problem is not with the chips I am trying to use since I am using all builtin chips. Here is my ALU chip so far: /** * The ALU. Computes a pre-defined set of functions out = f(x,y) * where x and y are two 16-bit inputs. The function f is selected * by a set of 6 control bits denoted zx, nx, zy, ny, f, no. * The ALU operation can be described using the following pseudocode: * if zx=1 set x = 0 // 16-bit zero constant * if nx=1 set x = !x // Bit-wise negation * if zy=1 set y = 0 // 16-bit zero constant * if ny=1 set y = !y // Bit-wise negation * if f=1 set out = x + y // Integer 2's complement addition * else set out = x & y // Bit-wise And * if no=1 set out = !out // Bit-wise negation * * In addition to computing out, the ALU computes two 1-bit outputs: * if out=0 set zr = 1 else zr = 0 // 16-bit equality comparison * if out<0 set ng = 1 else ng = 0 // 2's complement comparison */ CHIP ALU { IN // 16-bit inputs: x[16], y[16], // Control bits: zx, // Zero the x input nx, // Negate the x input zy, // Zero the y input ny, // Negate the y input f, // Function code: 1 for add, 0 for and no; // Negate the out output OUT // 16-bit output out[16], // ALU output flags zr, // 1 if out=0, 0 otherwise ng; // 1 if out<0, 0 otherwise PARTS: // Zero the x input Mux16( a=x, b=false, sel=zx, out=x2 ); // Zero the y input Mux16( a=y, b=false, sel=zy, out=y2 ); // Negate the x input Not16( in=x, out=notx ); Mux16( a=x, b=notx, sel=nx, out=x3 ); // Negate the y input Not16( in=y, out=noty ); Mux16( a=y, b=noty, sel=ny, out=y3 ); // Perform f Add16( a=x3, b=y3, out=addout ); And16( a=x3, b=y3, out=andout ); Mux16( a=andout, b=addout, sel=f, out=preout ); // Negate the output Not16( in=preout, out=notpreout ); Mux16( a=preout, b=notpreout, sel=no, out=out ); // zr flag Or8way( in=out[0..7], out=zr1 ); // PROBLEM SHOWS UP HERE Or8way( in=out[8..15], out=zr2 ); Or( a=zr1, b=zr2, out=zr ); // ng flag Not( in=out[15], out=ng ); } So the problem shows up when I am trying to send a subscripted version of 'out' to the Or8Way chip. I've tried using a different variable than 'out', but with the same problem. Then I read that you are not able to subscript intermediate variables. I thought maybe if I sent the intermediate variable to some other chip, and that chip subscripted it, it would solve the problem, but it has the same error. Unfortunately I just can't think of a way to set the zr and ng flags without subscripting some intermediate variable, so I'm really stuck! Just so you know, if I replace the problematic lines with the following, it will compile (but not give the right results since I'm just using some random input): // zr flag Not( in=zx, out=zr ); // ng flag Not( in=zx, out=ng ); Anyone have any ideas? Edit: Here is the appendix of the book for the course which specifies how the hdl works. Specifically look at section 5 which talks about buses and says: "An internal pin (like v above) may not be subscripted". Edit: Here is the exact error I get: "Line 68, Can't connect gate's output pin to part". The error message is sort of confusing though, since that does not seem to be the actual problem. If I just replace "Or8way( in=out[0..7], out=zr1 );" with "Or8way( in=false, out=zr1 );" it will not generate this error, which is what lead me to look up in the appendix and find that the out variable, since it was derived as intermediate, could not be subscripted.

    Read the article

  • Why can't my main class see the array in my calender class

    - by Rocky Celltick Eadie
    This is a homework problem. I'm already 5 days late and can't figure out what I'm doing wrong.. this is my 1st semester in Java and my first post on this site Here is the assignment.. Create a class called Calendar. The class should contain a variable called events that is a String array. The array should be created to hold 5 elements. Use a constant value to specify the array size. Do not hard code the array size. Initialize the array in the class constructor so that each element contains the string “ – No event planned – “. The class should contain a method called CreateEvent. This method should accept a String argument that contains a one-word user event and an integer argument that represents the day of the week. Monday should be represented by the number 1 and Friday should be represented by the number 5. Populate the events array with the event info passed into the method. Although the user will input one-word events, each event string should prepend the following string to each event: event_dayAppoinment: (where event_day is the day of the week) For example, if the user enters 1 and “doctor” , the first array element should read: Monday Appointment: doctor If the user enters 2 and “PTA” , the second array element should read: Tuesday Appointment: PTA Write a driver program (in a separate class) that creates and calls your Calendar class. Then use a loop to gather user input. Ask for the day (as an integer) and then ask for the event (as a one word string). Pass the integer and string to the Calendar object’s CreateEvent method. The user should be able enter 0 – 5 events. If the user enters -1, the loop should exit and your application should print out all the events in a tabular format. Your program should not allow the user to enter invalid values for the day of the week. Any input other than 1 – 5 or -1 for the day of the week would be considered invalid. Notes: When obtaining an integer from the user, you will need to use the nextInt() method on your Scanner object. When obtaining a string from a user, you will need to use the next() method on your Scanner object. Here is my code so far.. //DRIVER CLASS /** * * @author Rocky */ //imports scanner import java.util.Scanner; //begin class driver public class driver { /** * @paramargs the command line arguments */ //begin main method public static void main(String[] args) { //initiates scanner Scanner userInput = new Scanner (System.in); //declare variables int dayOfWeek; String userEvent; //creates object for calender class calendercalenderObject = new calender(); //user prompt System.out.println("Enter day of week for your event in the following format:"); System.out.println("Enter 1 for Monday"); System.out.println("Enter 2 for Tuesday"); System.out.println("Enter 3 for Wednsday"); System.out.println("Enter 4 for Thursday"); System.out.println("Enter 5 for Friday"); System.out.println("Enter -1 to quit"); //collect user input dayOfWeek = userInput.nextInt(); //user prompt System.out.println("Please type in the name of your event"); //collect user input userEvent = userInput.next(); //begin while loop while (dayOfWeek != -1) { //test for valid day of week if ((dayOfWeek>=1) && (dayOfWeek<=5)){ //calls createEvent method in calender class and passes 2 variables calenderObject.createEvent(userEvent,dayOfWeek); } else { //error message System.out.println("You have entered an invalid number"); //user prompts System.out.println("Press -1 to quit or enter another day"); System.out.println("Enter 1 for Monday"); System.out.println("Enter 2 for Tuesday"); System.out.println("Enter 3 for Wednsday"); System.out.println("Enter 4 for Thursday"); System.out.println("Enter 5 for Friday"); System.out.println("Enter -1 to quit"); //collect user input dayOfWeek = userInput.nextInt(); //end data validity test } //end while loop } //prints array to screen int i=0; for (i=0;i<events.length;i++){ System.out.println(events[i]); } //end main method } } /** * * @author Rocky */ //imports scanner import java.util.Scanner; //begin calender class public class calender { //creates events array String[] events = new String[5]; //begin calender class constructor public calender() { //Initializes array String[] events = {"-No event planned-","-No event planned-","-No event planned-","-No event planned-","-No event planned-"}; //end calender class constructor } //begin createEvent method public String[] createEvent (String userEvent, int dayOfWeek){ //Start switch test switch (dayOfWeek){ case 1: events[0] = ("Monday Appoinment:") + userEvent; break; case 2: events[1] = ("Tuesday Appoinment:") + userEvent; break; case 3: events[2] = ("WednsdayAppoinment:") + userEvent; break; case 4: events[3] = ("Thursday Appoinment:") + userEvent; break; case 5: events[4] = ("Friday Appoinment:") + userEvent; break; default: break; //End switch test } //returns events array return events; //end create event method } //end calender class }

    Read the article

  • I asked this yesterday, after the input given I'm still having trouble implementing..

    - by Josh
    I'm not sure how to fix this or what I did wrong, but whenever I enter in a value it just closes out the run prompt. So, seems I do have a problem somewhere in my coding. Whenever I run the program and input a variable, it always returns the same answer.."The content at location 76 is 0." On that note, someone told me that "I don't know, but I suspect that Program A incorrectly has a fixed address being branched to on instructions 10 and 11." - mctylr but I'm not sure how to fix that.. I'm trying to figure out how to incorporate this idea from R Samuel Klatchko.. I'm still not sure what I'm missing but I can't get it to work.. const int OP_LOAD = 3; const int OP_STORE = 4; const int OP_ADD = 5; ... const int OP_LOCATION_MULTIPLIER = 100; mem[0] = OP_LOAD * OP_LOCATION_MULTIPLIER + ...; mem[1] = OP_ADD * OP_LOCATION_MULTIPLIER + ...; operand = memory[ j ] % OP_LOCATION_MULTIPLIER; operation = memory[ j ] / OP_LOCATION_MULTIPLIER; I'm new to programming, I'm not the best, so I'm going for simplicity. Also this is an SML program. Anyway, this IS a homework assignment and I'm wanting a good grade on this. So I was looking for input and making sure this program will do what I'm hoping they are looking for. Anyway, here are the instructions: Write SML (Simpletron Machine language) programs to accomplish each of the following task: A) Use a sentinel-controlled loop to read positive number s and compute and print their sum. Terminate input when a neg number is entered. B) Use a counter-controlled loop to read seven numbers, some positive and some negative, and compute + print the avg. C) Read a series of numbers, and determine and print the largest number. The first number read indicates how many numbers should be processed. Without further a due, here is my program. All together. int main() { const int READ = 10; const int WRITE = 11; const int LOAD = 20; const int STORE = 21; const int ADD = 30; const int SUBTRACT = 31; const int DIVIDE = 32; const int MULTIPLY = 33; const int BRANCH = 40; const int BRANCHNEG = 41; const int BRANCHZERO = 41; const int HALT = 43; int mem[100] = {0}; //Making it 100, since simpletron contains a 100 word mem. int operation; //taking the rest of these variables straight out of the book seeing as how they were italisized. int operand; int accum = 0; // the special register is starting at 0 int j; // This is for part a, it will take in positive variables in a sent-controlled loop and compute + print their sum. Variables from example in text. memory [0] = 1010; memory [01] = 2009; memory [02] = 3008; memory [03] = 2109; memory [04] = 1109; memory [05] = 4300; memory [06] = 1009; j = 0; //Makes the variable j start at 0. while ( true ) { operand = memory[ j ]%100; // Finds the op codes from the limit on the memory (100) operation = memory[ j ]/100; //using a switch loop to set up the loops for the cases switch ( operation ){ case 10: //reads a variable into a word from loc. Enter in -1 to exit cout <<"\n Input a positive variable: "; cin >> memory[ operand ]; break; case 11: // takes a word from location cout << "\n\nThe content at location " << operand << "is " << memory[operand]; break; case 20:// loads accum = memory[ operand ]; break; case 21: //stores memory[ operand ] = accum; break; case 30: //adds accum += mem[operand]; break; case 31: // subtracts accum-= memory[ operand ]; break; case 32: //divides accum /=(memory[ operand ]); break; case 33: // multiplies accum*= memory [ operand ]; break; case 40: // Branches to location j = -1; break; case 41: //branches if acc. is < 0 if (accum < 0) j = 5; break; case 42: //branches if acc = 0 if (accum == 0) j = 5; break; case 43: // Program ends exit(0); break; } j++; } return 0; }

    Read the article

  • C++ Sentinel/Count Controlled Loop beginning programming

    - by Bryan Hendricks
    Hello all this is my first post. I'm working on a homework assignment with the following parameters. Piecework Workers are paid by the piece. Often worker who produce a greater quantity of output are paid at a higher rate. 1 - 199 pieces completed $0.50 each 200 - 399 $0.55 each (for all pieces) 400 - 599 $0.60 each 600 or more $0.65 each Input: For each worker, input the name and number of pieces completed. Name Pieces Johnny Begood 265 Sally Great 650 Sam Klutz 177 Pete Precise 400 Fannie Fantastic 399 Morrie Mellow 200 Output: Print an appropriate title and column headings. There should be one detail line for each worker, which shows the name, number of pieces, and the amount earned. Compute and print totals of the number of pieces and the dollar amount earned. Processing: For each person, compute the pay earned by multiplying the number of pieces by the appropriate price. Accumulate the total number of pieces and the total dollar amount paid. Sample Program Output: Piecework Weekly Report Name Pieces Pay Johnny Begood 265 145.75 Sally Great 650 422.50 Sam Klutz 177 88.5 Pete Precise 400 240.00 Fannie Fantastic 399 219.45 Morrie Mellow 200 110.00 Totals 2091 1226.20 You are required to code, compile, link, and run a sentinel-controlled loop program that transforms the input to the output specifications as shown in the above attachment. The input items should be entered into a text file named piecework1.dat and the ouput file stored in piecework1.out . The program filename is piecework1.cpp. Copies of these three files should be e-mailed to me in their original form. Read the name using a single variable as opposed to two different variables. To accomplish this, you must use the getline(stream, variable) function as discussed in class, except that you will replace the cin with your textfile stream variable name. Do not forget to code the compiler directive #include < string at the top of your program to acknowledge the utilization of the string variable, name . Your nested if-else statement, accumulators, count-controlled loop, should be properly designed to process the data correctly. The code below will run, but does not produce any output. I think it needs something around line 57 like a count control to stop the loop. something like (and this is just an example....which is why it is not in the code.) count = 1; while (count <=4) Can someone review the code and tell me what kind of count I need to introduce, and if there are any other changes that need to be made. Thanks. [code] //COS 502-90 //November 2, 2012 //This program uses a sentinel-controlled loop that transforms input to output. #include <iostream> #include <fstream> #include <iomanip> //output formatting #include <string> //string variables using namespace std; int main() { double pieces; //number of pieces made double rate; //amout paid per amount produced double pay; //amount earned string name; //name of worker ifstream inFile; ofstream outFile; //***********input statements**************************** inFile.open("Piecework1.txt"); //opens the input text file outFile.open("piecework1.out"); //opens the output text file outFile << setprecision(2) << showpoint; outFile << name << setw(6) << "Pieces" << setw(12) << "Pay" << endl; outFile << "_____" << setw(6) << "_____" << setw(12) << "_____" << endl; getline(inFile, name, '*'); //priming read inFile >> pieces >> pay >> rate; // ,, while (name != "End of File") //while condition test { //begining of loop pay = pieces * rate; getline(inFile, name, '*'); //get next name inFile >> pieces; //get next pieces } //end of loop inFile.close(); outFile.close(); return 0; }[/code]

    Read the article

  • Vector of Object Pointers, general help and confusion

    - by Staypuft
    Have a homework assignment in which I'm supposed to create a vector of pointers to objects Later on down the load, I'll be using inheritance/polymorphism to extend the class to include fees for two-day delivery, next day air, etc. However, that is not my concern right now. The final goal of the current program is to just print out every object's content in the vector (name & address) and find it's shipping cost (weight*cost). My Trouble is not with the logic, I'm just confused on few points related to objects/pointers/vectors in general. But first my code. I basically cut out everything that does not mater right now, int main, will have user input, but right now I hard-coded two examples. #include <iostream> #include <string> #include <vector> using namespace std; class Package { public: Package(); //default constructor Package(string d_name, string d_add, string d_zip, string d_city, string d_state, double c, double w); double calculateCost(double, double); void Print(); ~Package(); private: string dest_name; string dest_address; string dest_zip; string dest_city; string dest_state; double weight; double cost; }; Package::Package() { cout<<"Constucting Package Object with default values: "<<endl; string dest_name=""; string dest_address=""; string dest_zip=""; string dest_city=""; string dest_state=""; double weight=0; double cost=0; } Package::Package(string d_name, string d_add, string d_zip, string d_city, string d_state, string r_name, string r_add, string r_zip, string r_city, string r_state, double w, double c){ cout<<"Constucting Package Object with user defined values: "<<endl; string dest_name=d_name; string dest_address=d_add; string dest_zip=d_zip; string dest_city=d_city; string dest_state=d_state; double weight=w; double cost=c; } Package::~Package() { cout<<"Deconstructing Package Object!"<<endl; delete Package; } double Package::calculateCost(double x, double y){ return x+y; } int main(){ double cost=0; vector<Package*> shipment; cout<<"Enter Shipping Cost: "<<endl; cin>>cost; shipment.push_back(new Package("tom r","123 thunder road", "90210", "Red Bank", "NJ", cost, 10.5)); shipment.push_back(new Package ("Harry Potter","10 Madison Avenue", "55555", "New York", "NY", cost, 32.3)); return 0; } So my questions are: I'm told I have to use a vector of Object Pointers, not Objects. Why? My assignment calls for it specifically, but I'm also told it won't work otherwise. Where should I be creating this vector? Should it be part of my Package Class? How do I go about adding objects into it then? Do I need a copy constructor? Why? What's the proper way to deconstruct my vector of object pointers? Any help would be appreciated. I've searched for a lot of related articles on here and I realize that my program will have memory leaks. Using one of the specialized ptrs from boost:: will not be available for me to use. Right now, I'm more concerned with getting the foundation of my program built. That way I can actually get down to the functionality I need to create. Thanks.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >