My program outputs nothing at all and I am stuck on this, also it says that I need to update variable in the loop - nested

Scanner c = new Scanner(System.in);
char choice = c.next().charAt(0);
char c_choice = c.next().charAt(0);
do { // start menu
System.out.println("Welcome to Dripp!");
System.out.println("Please choose from one of our signature creations or create your own!");
System.out.println("1. Oreo Overload $6.99");
System.out.println("2. Birthday Cake Remix $6.99");
System.out.println("3. Chocolate Devotion $6.99");
System.out.println("4. Strawberry Blonde $6.99");
System.out.println("5. Founders Favorite $6.99");
System.out.println("6. Create Your Own!");
} while (choice < '1' | choice > '6');
System.out.println();
switch (choice) {
case '1':
System.out.println("Ingredients: Sweet Cream Ice Cream with Chocolate Chips, double the OREO® Cookies and Fudge");
I am writing a code for a restuarnt and where the user can select something then it nests into another switch but for some reason the code is blank when i run it.

You are taking the choice before the do-while loop. To fix your code change it to this:
Scanner c = new Scanner(System.in);
do {
System.out.println("Welcome to Dripp!");
System.out.println("Please choose from one of our signature creations or create your own!");
System.out.println("1. Oreo Overload $6.99");
System.out.println("2. Birthday Cake Remix $6.99");
System.out.println("3. Chocolate Devotion $6.99");
System.out.println("4. Strawberry Blonde $6.99");
System.out.println("5. Founders Favorite $6.99");
System.out.println("6. Create Your Own!");
char choice = c.next().charAt(0);
} while (choice < '1' | choice > '6');
//yadayada
This takes an input after you output the choices.

Related

One lane bridge using monitor

In the University I'm given this canonical parallel programming problem from "Gregory R. Andrews-Foundations of Multithreaded .... programming": (though I have a newer and Russian edition of the book I found an old English variant and try to convey everything properly)
I was also given task to solve this problem but with m consequently moving cars possible using semaphores To solve that task I was told by the tutor to mimic Reader's behavior from readers-writers task
The One-Lane Bridge. Cars coming from the north and the south arrive at a one-
lane bridge. Cars heading in the same direction can cross the bridge at the same
time, but cars heading in opposite directions cannot.
Develop a solution to this problem. Model the cars as processes, and use a
monitor for synchronization. First specify the monitor invariant, then develop the
body of the monitor.Ensure fairness. (Have cars take tums)
I googled and found solution for analogous task (http://www.cs.cornell.edu/courses/cs4410/2008fa/homework/hw3_soln.pdf) but lecturer said most of it is useless and incorrect I ended up with the following solution:
monitor onelanebridge{
int nb=0,sb=0; //Invar:(nb==0 and sb<=1)or(sb=0 and nb<=1)
cond nbfreetogo,sbfreetogo; //conditional variables
procedure enter_n(){
if(sb!=0andnb==0) wait(nbfreetogo);
nb++;
}
procedure enter_s(){
if(nb!=0andsb==0) wait(sbfreetogo);
sb++;
}
procedure leave_n(){
nb--;
if(nb==0) signal(sbfreetogo);
}
procedure leave_s(){
sb--;
if(sb==0) signal(nbfreetogo);
}
}
I was asked the question "What ensures that no more than one car at a time can cross the bridge?".. And am not even sure whether it's even so... Please help me solve the task correctly. I must use only constructions from the above mentioned book...
Example of readers-writers problem solution from the book:
monitor RW_Controller {
int nr = 0, nw =0; //Invar: (nr == 0 or nw == 0) and nw <= 1
cond oktoread; # recieves signal, when nw == 0
cond oktowrite; # recieves signal, when nr == 0 и nw == 0
procedure request_read() {
while (nw > 0) wait(oktoread);
nr = nr + 1;
}
procedure release_read() {
nr = nr - 1;
if (nr == 0) signal(oktowrite);
# run one writer-process
}
procedure request_write() {
while (nr > 0 || nw > 0) wait(oktowrite);
nw = nw + 1 ;
}
procedure release_ write() {
nw = nw - 1;
signal(oktowrite); # run one writer-process and
signal_all(oktoread); # all reader-processes
}
}
Of course my solution is just a random try. Halp me please to solve the task properly
Note: A variable of "conditional variable" type according to the book is a "wait queue" which has these methods:
wait(cv)//wait at end of queue
wait(cv,rank)//wait in order of increasing value of rank
signal(cv)//awaken process at end of queue then continue
signal_all(cv)//awaken all processes at end of queue then continue
empty(cv) //true if wait queue is empty; false otherwise
minrank(cv) //value of rank of process at front of wait queue
And so I should solve the task probably using some of these
Your monitor onelanebridge is not far off the mark, but it has no notion of fairness. If there was a steady stream of northbound traffic, nothing would trigger a switch to southbound. You need to separate the count of waiting and ‘active’.
A simple fairness would be to alternate, so you could limit the ‘active’ counter at 1; and check whether to switch when it becomes zero.
To avoid inciting road rage, you might choose a limit based on the transit time of the single lane section.
You would now have vehicles waiting in enter_[ns] which had the right direction, but have to wait because of the limit, so your if (cond) wait needs to become while (more complex cond) wait.
Concurrent programming is not natural, but with practise can become ingrained. Try and think of the problem at hand rather than how can I employ these mechanisms.

Concurrent programming, how do i construct a semaphore?

i have a project where i have to write pseudocode for a semaphore, from the following text:
"Consider a scenario where a single taxi is taking Manchester United and Liverpool supporters from the city centre to the Saturday football game. The taxi can take four supporters at a time and it is always filled to capacity when carrying supporters. However the situation is never allowed to arise where the taxi contains one supporter of either team isolated on their own. The taxi carries out a number of trips and when it first arrives it randomly signals to one of the two waiting supporters’ queues. You can assume that there are always one or more supporters waiting in each queue when it is signaled. When a supporter enters the taxi and there is still some room for more supporters in the taxi the supporter (who has just joined the taxi) signal to another waiting supporter in one of the queues for them to also enter the taxi. Where possible the supporter will randomly select the queue to signal, however if necessary they will select a particular queue so as to ensure that no single supporter will be isolated in the taxi with opposing supporters.
The last supporter entering the taxi to complete a full cohort of four supporters in the taxi signals the taxi (driver) to take them to the football ground. The taxi takes them to their destination and then returns to repeat the cycle. Note that only the supporters (not the taxi driver) are able to differentiate between who is a Manchester United supporter and who is a Liverpool supporter."
I'm having trouble applying what notes i have, and what help there is online to this scenario.
Heres what ive done so far:
int numManInTaxi = 0; //current no. of ManU supporters in taxi
int numLivInTaxi = 0;
sem MaxUnitedFans = 4; // // max no. of supporters that can fit in taxi
sem MaxLivFans = 4;
sem MMutexSem = 1;
sem LMutexSem = 1;
CO
for (count = 1 to ManUSupporter){
ManUProcess[count];
//
for (count = 1 to LivSupporter){
LivProcess[count];
OC
} /*end main process
process ManUProcess [i = 1 to N]{
P(MMutexSem); // mutually exclusice access for United supporter
numManUInTaxi++;
if ((numManInTaxi+numLivInTaxi) < 4)
{
if (numManuInTaxi == 3) { // signal the Man queue
numManUInTaxi++;
} else if ((numManUInTaxi ==1) && (numLivInTaxi==2)){
numManUInTaxi++;
} else if ( (numManInTaxi == 2) &&(numLivInTaxi==1)) {
V(MMutexSem);
NumLivInTaxi++;}
//end ManU supporter semaphore
Here is what I could make-
int numManInTaxi = 0; //current no. of ManU supporters in taxi
int numLivInTaxi = 0;
int seats=4; //no of seats available empty
sem taxi=1; //to wait for taxi to send signal
sem seats=0; //signal generated by taxi or passenger for next passenger
wait(taxi); //taxi is available
{
signal(seat); //taxi generates signal
while(wait(seats)) //check if there are seats available
{
int i=rand()%2; //random number 0 or 1 used to select between 2 queues
if(i==0)
numManInTaxi++; //passenger supports ManU
else
numLivInTaxi++; //passenger supports Liv
seats--;
if(seats>1) //passenger generates signal for next passenger to enter
signal(seat);
}
/*Now three seats are filled and we have one empty seat left which is to
be filled such that there is no lone supporter of a team in taxi*/
signal(seat); //signal for last seat
wait(seat); //last passenger recieves the signal
seats--;
if(numManInTaxi==1) //if only one supporter belongs to ManU
numManInTaxi++;
else
numManInTaxi++;
}
//taxi drops passengers
numManInTaxi=0;
numManInTaxi=0;
seats=4;
signal(taxi); //taxi is ready for next trip

Read a String with spaces till a new line in C

I am in a pickle right now. I'm having trouble taking in an input of example
1994 The Shawshank Redemption
1994 Pulp Fiction
2008 The Dark Knight
1957 12 Angry Men
I first take in the number into an integer, then I need to take in the name of the Movie into a string using a character array, however i have not been able to get this done.
here is the code atm
while(scanf("%d", &myear) != EOF)
{
i = 0;
while(scanf("%[^\n]", &ch))
{
title[i] = ch;
i++;
}
addNode(makeData(title,myear));
}
The title array is arbitrarily large and the function is to add the data as a node to a linked list. right now the output I keep getting for each node is as follows
" hank Redemption"
" ion"
" Knight"
" Men"
Yes, it oddly prints a space in front of the cut-off title. I checked the variables and it adds the space in the data. (I am not printing the year as that is taken in correctly)
How can I fix this?
You are using the wrong type of argument passed to scanf() -- instead of scanning a character, try scanning to the string buffer immediately. %[^\n] scans an entire string up to (but not including) the newline. It does not scan only one character.
(Marginal secondary problem: I don't know from where you people are getting the idea that scanf() returns EOF at end of input, but it doesn't - you'd be better off reading the documentation instead of making incorrect assumptions.)
I hope you see now: scanf() is hard to get right. It's evil. Why not input the whole line at once then parse it using sane functions?
char buf[LINE_MAX];
while (fgets(buf, sizeof buf, stdin) != NULL) {
int year = strtol(buf, NULL, 0);
const char *p = strchr(buf, ' ');
if (p != NULL) {
char name[LINE_MAX];
strcpy(name, p + 1); // safe because strlen(p) <= sizeof(name)
}
}

Is their a way for a user to input a word and have that word be (turn into) a #?

I am trying to create program that roles 2 dice. Then the user and say Yes to role the dice again or say No to stop rolling the dice.
import java.util.*;
public class Dice
{
public static void main(String[] args)
{
Random dice1 = new Random();
Scanner in = new Scanner(System.in);
//varibles
int die1;
int die2;
byte playagain=1;
byte Yes = 1;
byte No = 0;
int total;
int stop = 0;
//Want find I way to change words into #s
String start = Yes;
while(stop<5 && start<Yes){
stop+=1;
die1=dice1.nextInt(6)+1;
die2=dice1.nextInt(6)+1;
total=die1 + die2;
System. out. println("You rolled a " + total+ ".");
System. out. println("Do you want to play again?");
System. out. println("Type Yes to keep playing you and No to stop.");
/*I want people to be able to input Yes and that equal a # so I can use it in the While loop. Same with No.*/
start=in.next();
System. out. println("start is at " + start);
}
}
}
I have looked throughout internet an could not find any help so that is why I am asking.
If you mean you want to read an int from your scanner, try using Scanner.nextInt http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()
You can use hasNextInt to determine if using nextInt will work or not: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
If you already have the string and want to turn it into an int, try Integer.parseInt http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
In general, if you want to know if a function that does something basic exists, you should check the APIs in java.lang, java.util, java.io, etc (depending on where you think it would be)

Any programming language with "strange" function call?

I was wondering, is there any programming language where you can have function calls like this:
function_name(parameter1)function_name_continued(parameter2);
or
function_name(param1)function_continued(param2)...function_continued(paramN);
For example you could have this function call:
int dist = distanceFrom(cityA)to(cityB);
if you have defined distanceFromto function like this:
int distanceFrom(city A)to(city B)
{
// find distance between city A and city B
// ...
return distance;
}
As far as I know, in C, Java and SML programming languages, this cannot be done.
Are you aware of any programming language that let's you define and call
functions in this way?
It looks an awful lot like Objective-C
- (int)distanceFrom:(City *)cityA to:(City *)cityB {
// woah!
}
Sounds a lot like Smalltalk's syntax, (which would explain Objective-C's syntax - see kubi's answer).
Example:
dist := metric distanceFrom: cityA to: cityB
where #distanceFrom:to: is a method on some object called metric.
So you have "function calls" (they're really message sends) like
'hello world' indexOf: $o startingAt: 6. "$o means 'the character literal o"
EDIT: I'd said "Really, #distanceFrom:to: should be called #distanceTo: on a City class, but anyway." Justice points out that this couples a City to a Metric, which is Bad. There are good reasons why you might want to vary the metric - aeroplanes might use a geodesic while cars might use a shortest path based on the road network.)
For the curious, Agda2 has a similar, very permissive syntax. The following is valid code:
data City : Set where
London : City
Paris : City
data Distance : Set where
_km : ℕ → Distance
from_to_ : City → City → Distance
from London to London = 0 km
from London to Paris = 342 km
from Paris to London = 342 km
from Paris to Paris = 0 km
If
from Paris to London
is evaluated, the result is
342 km
Looks a lot like a fluent interface or method chaining to me.
In Python, you can explicitly pass the name of the arguments you're calling the function with, which lets you pass them in a different order or skip optional arguments:
>>> l = [3,5,1,2,4]
>>> print l.sort.__doc__
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
>>> l.sort (reverse=True)
>>> l
[5, 4, 3, 2, 1]
This looks a lot like what the Objective C syntax is doing, tagging each argument to a function with its name.
C# 4.0's Named and Optional Arguments feature allows you to achieve something pretty similar:
public static int Distance(string from, string to, string via = "")
{
...
}
public static void Main()
{
int distance;
distance = Distance(from: "New York", to: "Tokyo");
distance = Distance(to: "Tokyo", from: "New York");
distance = Distance(from: "New York", via: "Athens", to: "Tokyo");
}
(see my very favourite personal effort - the final C++ approach at the end of this answer)
Language One
Objective-C but the calling syntax is [object message] so would look like:
int dist = [cities distanceFrom:cityA to:cityB];
if you have defined distanceFromto function like this, within a cities object:
- (int)distanceFrom:(City *)cityA to:(City *)cityB
{
// find distance between city A and city B
// ...
return distance;
}
Language Two
I also suspect you could achieve something very close to this in the IO Language but I'm only just looking at it. You may also want to read about it in comparison to other languages in Seven Languages in Seven Weeks which has a free excerpt about IO.
Language Three
There's an idiom ("chaining") in C++ where you return temporary objects or the current object that is used to replace keyword arguments, according to The Design and Evolution of C++ and looks like this:
int dist = distanceFrom(cityA).to(cityB);
if you have defined distanceFrom function like this, with a little helper object. Note that inline functions make this kind of thing compile to very efficient code.
class DistanceCalculator
{
public:
DistanceCalculator(City* from) : fromCity(from) {}
int to(City * toCity)
{
// find distance between fromCity and toCity
// ...
return distance;
}
private:
City* fromCity;
};
inline DistanceCalculator distanceFrom(City* from)
{
return DistanceCalculator(from);
}
Duhh, I was in a hurry earlier, realised I can refactor to just use a temporary object to give the same syntax:
class distanceFrom
{
public:
distanceFrom(City* from) : fromCity(from) {}
int to(City * toCity)
{
// find distance between fromCity and toCity
// ...
return distance;
}
private:
City* fromCity;
};
MY FAVOURITE
and here's an even more inspired C++ version that allows you to write
int dist = distanceFrom cityA to cityB;
or even
int dist = distanceFrom cityA to cityB to cityC;
based on a wonderfully C++ ish combination of #define and classes:
#include <vector>
#include <numeric>
class City;
#define distanceFrom DistanceCalculator() <<
#define to <<
class DistanceCalculator
{
public:
operator int()
{
// find distance between chain of cities
return std::accumulate(cities.begin(), cities.end(), 0);
}
DistanceCalculator& operator<<(City* aCity)
{
cities.push_back(aCity);
return *this;
}
private:
std::vector<City*> cities;
};
NOTE this may look like a useless exercise but in some contexts it can be very useful to give people a domain-specific language in C++ which they compile alongside libraries. We used a similar approach with Python for geo-modeling scientists at the CSIRO.
You can do this in C, albeit unsafely:
struct Arg_s
{
int from;
int to;
};
int distance_f(struct Arg_s args)
{
return args.to - args.from;
}
#define distance(...) distance_f( ((struct Arg_s){__VA_ARGS__}) )
#define from_ .from =
#define to_ .to =
uses compound literals and designated initializers.
printf("5 to 7 = %i\n",distance(from_ 5, to_ 7));
// 5 to 7 = 2
3 of the 4 confederated languages from RemObjects in their Elements Compiler have this capability in precisely the OP's requested syntax (to support Objective-C runtime, but made available to all operating systems).
in Hydrogene (an extended C#)
https://docs.elementscompiler.com/Hydrogene/LanguageExtensions/MultiPartMethodNames
in Iodine (an extended Java)
https://docs.elementscompiler.com/Iodine/LanguageExtensions/MultiPartMethodNames
in Oxygene (an extended ObjectPascal), scroll down to Multi-Part Method Names section
https://docs.elementscompiler.com/Oxygene/Members/Methods
This looks similar to function overloading (C++/C#)/default parameters (VB).
Default Parameters allow the person defining the function to set defaults for the latter parameters:
e.g. c# overloading:
int CalculateDistance(city A, city B, city via1, city via2)
{....}
int CalculateDistance(city A, city B)
{
return CalculateDistance(city A, city B, null, null)
}
You can use a member function for this.
cityA.distance_to(cityB);
That's valid code in C++, C(with a little tweaking), C#, Java. Using method chains, you can do:
cityA.something(cityB).something(cityC).something(cityD).something(cityE);
In SML you could simply make "to" some value (unit, for example), and "distanceFrom" a curried function that takes three parameters. For example:
val to = ()
fun distanceFrom x _ y = (* implementation function body *)
val foo = distanceFrom cityA to cityB
You could also take advantage of the fact that SML doesn't enforce naming conventions on datataype constructors (much to many peoples' annoyance), so if you want to make sure that the type system enforces your custom syntax:
datatype comp = to
fun distanceFrom x to y = (* implementation *)
val foo = distanceFrom cityA to cityB (* works *)
val foo' = distanceFrom cityA cityB (* whoops, forgot 'to' - type error! *)
You could do this in Scheme or LISP using macros.
The form will be something like:
(DISTANCE-FROM city-a TO city-b)
The symbols in uppercase denotes syntax.
You could even do something like 'named parameters':
(DISTANCE TO city-a FROM city-b)
(DISTANCE FROM city-a TO city-b)
Tcl allows you to do something like this:
proc distance {from cityA to cityB} {...}
set distance [distance from "Chicago IL" to "Tulsa OK"]
I'm not sure if that's quite what you are thinking of though.
You can do it in Java, Use Builder pattern that appears in the book Effective Java by Joshua Bosch (this is second time I put this link in SO, I still didn't use that patern, but looks great)
Well, in Felix you can implement this in two steps: first, you write an ordinary function. Then, you can extend the grammar and map some of the new non-terminals to the function.
This is a bit heavyweight compared to what you might want (welcome to help make it easier!!) I think this does what you want and a whole lot more!
I will give a real example because the whole of the Felix language is actually defined by this technique (below x is the non-terminal for expressions, the p in x[p] is a precedence code):
// alternate conditional
x[sdollar_apply_pri] := x[stuple_pri] "unless" x[let_pri]
"then" x[sdollar_apply_pri] =>#
"`(ast_cond ,_sr ((ast_apply ,_sr (lnot ,_3)) ,_1 ,_5))";
Here's a bit more:
// indexes and slices
x[sfactor_pri] := x[sfactor_pri] "." "[" sexpr "]" =>#
"`(ast_apply ,_sr (,(noi 'subscript) (,_1 ,_4)))";
x[sfactor_pri] := x[sfactor_pri] "." "[" sexpr "to" sexpr "]" =>#
"`(ast_apply ,_sr (,(noi 'substring) (,_1 ,_4 ,_6)))";
x[sfactor_pri] := x[sfactor_pri] "." "[" sexpr "to" "]" =>#
"`(ast_apply ,_sr (,(noi 'copyfrom) (,_1 ,_4)))";
x[sfactor_pri] := x[sfactor_pri] "." "[" "to" sexpr "]" =>#
"`(ast_apply ,_sr (,(noi 'copyto) (,_1 ,_5)))";
The Felix grammar is ordinary user code. In the examples the grammar actions are written in Scheme. The grammar is GLR. It allows "context sensitive keywords", that is, identifiers that are keywords in certain contexts only, which makes it easy to invent new constructs without worrying about breaking existing code.
Perhaps you would like to examine Felix Grammar Online.

Resources