I wrote this code to ask user for inputting one of the values in the enumeration but I don't know how to connect the enumeration values to the user input. Please help.
Thank you!
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Hello, please enter the numerical value corresponding to your transportation mode.Car = 10 / Bus = 20 / Bicycle = 5 / Cab = 7.");
int TransportationModeInput = int.Parse(Console.ReadLine());
public enum TransporationMode
{
Car = 10,
Bus = 20,
Bicycle = 5,
Cab = 7
}
int ModeCar = (int)TransporationMode.Car;
int ModeBus = (int)TransporationMode.Bus;
int ModeBicycle = (int)TransporationMode.Bicycle;
int ModeCab = (int)TransporationMode.Cab;
}
}
(TransporationMode)TransportationModeInput It Auto Casting to enum
public enum TransporationMode
{
Car = 10,
Bus = 20,
Bicycle = 5,
Cab = 7
}
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Hello, please enter the numerical value corresponding to your transportation mode.Car = 10 / Bus = 20 / Bicycle = 5 / Cab = 7.");
int TransportationModeInput = int.Parse(Console.ReadLine());
Console.WriteLine("Answer:" + ((TransporationMode)TransportationModeInput).ToString());
Console.ReadLine();
}
}
Related
Hi i am new in java programing. I've created a program to allocate 20 block inside 10 memory.
Here's the code
import java.util.*;
import java.io.*;
public class BestFit
{
private int[] job;//f
private int[] memBlock;//b
private int[] jobStatus;
private int[] jobAT;
static private int[] memTaken;
static int[] ff;
private int[] jobCC;
private int[] ArrivalTime;
private int[] waitingTime;
private int[] turnaroundTime;
public BestFit()
{
job = new int[]{5040,4600,1060,1950,6950,6410,2960,3070,2770,7790,5680,9150,7880,3870,7160,8880,4410,6130,6750,2560};
memBlock = new int[]{4400,6200,9300,1000,4200,8200,4600,3700,6300,2900};
memTaken = new int[20];
ff = new int[20];//to store no. of block that used by particular file
jobCC = new int[]{2,8,10,1,10,8,4,2,6,7,1,1,1,8,8,2,5,7,6,7};//cpu cycle
ArrivalTime = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
waitingTime = new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
turnaroundTime = new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
}
public void BestFitAlgo()
{
int[] frag = new int[25];
int i,j,nb,nf,sizeDifference;
int lowest = 10000;
nf = 20;
nb = 10;
int startTime = 1;
int complete = 1;
int totalTime = 1;
int waitTime;
int tTime = 1;
Arrays.sort(memBlock);
for (i=0;i<nf;i++)
{
if (complete != 20)
{
for (j=0;j<nb;j++)
{
sizeDifference = memBlock[j] - job[i];
if (sizeDifference>=0)
if (lowest>sizeDifference)
{
ff[i] = j;//no of block = j
lowest = sizeDifference;
complete++;
System.out.println("Job: "+i+" is added to block: "+ff[i]+" and being process");
for (int k = 1;k<jobCC[i];k++)
{
startTime++;
}
if(startTime == jobCC[i])
{
waitingTime[i] = tTime - ArrivalTime[i];
turnaroundTime[i] = jobCC[i] + waitingTime[i];
System.out.println("Job: "+i+" is fully processed.Block: "+ff[i]+" is free");
System.out.println("Arrival Time: "+ArrivalTime[i]);
System.out.println("Start time: "+totalTime);
System.out.println("CPU cycle: "+jobCC[i]);
totalTime +=startTime;
startTime = 1;
tTime = totalTime;
System.out.println("Waiting time: "+waitingTime[i]);
System.out.println("Turnaround time: "+turnaroundTime[i]+"\n");
}
}
}
}
frag[i]=lowest;
lowest = 10000;
}
System.out.println("File No:\tFile_Size:\tBlock_No:\tBlock_Size:\tFragment");
for (i=0;i<nf&&ff[i]!=0;i++)
{
System.out.println(i+"\t\t"+job[i]+"\t\t"+ff[i]+"\t\t"+memBlock[ff[i]]+"\t\t"+frag[i]);
}
System.out.println("\nTotal time: "+totalTime);
}
public static void main (String[] args)
{
BestFit b = new BestFit();
b.BestFitAlgo();
}
}
For now the job can be allocated to the memory block by fcfs but the problem now is the next job wont be able to enter the memory list ( where all the block) until the previous job is done. So there are 9 free memory block everytime a job enter.
How do i make it so that job can enter the block simultaneously (with the condition the desired mem block is not occupied and based on arrival time).
I know how fcfs work but that is with only 1 memory block. I've been googling all day trying to find how fcfs work in multiple memory block but no avail.
I hope anyone can help me to understand how it work and maybe a hint on how to implement in in coding.
Thanks in advance
EDIT: i put my code instead so anyone can get a clear view of my problem.
Given an enumeration of records in the format:
Name (string)
Amount (number)
For example:
Laverne 4
Lenny 2
Shirley 3
Squiggy 5
I want to group the records, so that each group's total Amount does not exceed some limit-per-group. For example, 10.
Group 1 (Laverne,Lenny,Shirley) with Total Amount 9
Group 2 (Squiggy) with Total Amount 5
The Amount number is guaranteed to always be less than the grouping limit.
If you allow for captured variables to maintain state, then it becomes easier. If we have:
int limit = 10;
Then:
int groupTotal = 0;
int groupNum = 0;
var grouped = records.Select(r =>
{
int newCount = groupTotal + r.Amount;
if (newCount > limit)
{
groupNum++;
groupTotal = r.Amount;
}
else
groupTotal = newCount;
return new{Records = r, Group = groupNum};
}
).GroupBy(g => g.Group, g => g.Records);
It's O(n), and just a Select and a GroupBy, but the use of captured variables may not be as portable across providers as one may want though.
For linq-to-objects though, it's fine.
Here I have a solution using only LINQ functions:
// Record definition
class Record
{
public string Name;
public int Amount;
public Record(string name, int amount)
{
Name = name;
Amount = amount;
}
}
// actual code for setup and LINQ
List<Record> records = new List<Record>()
{
new Record("Laverne", 4),
new Record("Lenny", 2),
new Record("Shirley", 3),
new Record("Squiggy", 5)
};
int groupLimit = 10;
// the solution
List<Record[]> test =
records.GroupBy(record => records.TakeWhile(r => r != record)
.Concat(new[] { record })
.Sum(r => r.Amount) / (groupLimit + 1))
.Select(g => g.ToArray()).ToList();
This gives the correct result:
test =
{
{ [ "Laverne", 4 ], [ "Lenny", 2 ], [ "shirley", 3 ] },
{ [ "Squiggly", 5 ] }
}
The only downside is that this is O(n2). It essentially groups by the index of the group (as defined by using the sum of the record up to the current one). Note that groupLimit + 1 is needed so that we actually include groups from 0 to groupLimit, inclusive.
I'm trying to find a way of making it prettier, but it doesn't look easy.
A dotnet fiddle with a solution using Aggregate:
https://dotnetfiddle.net/gVgONH
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
// Record definition
public class Record
{
public string Name;
public int Amount;
public Record(string name, int amount)
{
Name = name;
Amount = amount;
}
}
public static void Main()
{
// actual code for setup and LINQ
List<Record> records = new List<Record>()
{
new Record("Alice", 1), new Record("Bob", 5), new Record("Charly", 4), new Record("Laverne", 4), new Record("Lenny", 2), new Record("Shirley", 3), new Record("Squiggy", 5)}
;
int groupLimit = 10;
int sum = 0;
var result = records.Aggregate(new List<List<Record>>(), (accumulated, next) =>
{
if ((sum + next.Amount >= groupLimit) || accumulated.Count() == 0)
{
Console.WriteLine("New team: " + accumulated.Count());
accumulated.Add(new List<Record>());
sum = 0;
}
sum += next.Amount;
Console.WriteLine("New member {0} ({1}): adds up to {2} ", next.Name, next.Amount, sum);
accumulated.Last().Add(next);
return accumulated;
}
);
Console.WriteLine("Team count: " + result.Count());
}
}
With output:
New team: 0
New member Alice (1): adds up to 1
New member Bob (5): adds up to 6
New team: 1
New member Charly (4): adds up to 4
New member Laverne (4): adds up to 8
New team: 2
New member Lenny (2): adds up to 2
New member Shirley (3): adds up to 5
New team: 3
New member Squiggy (5): adds up to 5
Team count: 4
There is no 'performant' way to do this with the built in Linq operators that I am aware of. You could create your own extension method, though:
public static class EnumerableExtensions
{
public static IEnumerable<TResult> GroupWhile<TSource, TAccumulation, TResult>(
this IEnumerable<TSource> source,
Func<TAccumulation> seedFactory,
Func<TAccumulation, TSource, TAccumulation> accumulator,
Func<TAccumulation, bool> predicate,
Func<TAccumulation, IEnumerable<TSource>, TResult> selector)
{
TAccumulation accumulation = seedFactory();
List<TSource> result = new List<TSource>();
using(IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while(enumerator.MoveNext())
{
if(!predicate(accumulator(accumulation, enumerator.Current)))
{
yield return selector(accumulation, result);
accumulation = seedFactory();
result = new List<TSource>();
}
result.Add(enumerator.Current);
accumulation = accumulator(accumulation, enumerator.Current);
}
if(result.Count > 0)
{
yield return selector(accumulation, result);
}
}
}
}
And then call it like this:
int limit = 10;
var groups =
records
.GroupWhile(
() => 0,
(a, x) => a + x,
(a) => a <= limit,
(a, g) => new { Total = a, Group = g });
The way it is currently written, if any single record exceeds that limit then that record is returned by itself. You could modify it to exclude records that exceed the limit or leave it as is and perform the exclusion with Where.
This solution has O(n) runtime.
My issue is that I'm trying to validate my input by making sure that the while loop only takes a number more than 10. If not, they have to try again. But the issue I'm having is that the loop keeps repeating itself if I close the while loop.
import java.util.Scanner;
/**
* #(#)Hotel_Occupancy.java
*
* Hotel_Occupancy application
*
* #author
* #version 1.00 2013/10/28
*/
public class Hotel_Occupancy {
public static void main(String[] args) {
//Declare Variables
int floors;
int rooms;
int roomsOccupied;
int roomsVacant;
int occupancyRate;
//Create Scanner Object
Scanner keyboard = new Scanner(System.in);
//Ask user for # of floors
System.out.print("Enter floors? Input number more than 1. ");
floors = keyboard.nextInt();
while (floors < 1 && floors != 10 )
{
System.out.println("ENTER VALID NUMBER.");
System.out.println("Enter floors? Input number more than 1. ");
System.;
//Create loop with floor iteration
for (rooms = 1; rooms <= floors; rooms++)
{
System.out.println("How many rooms? ");
rooms = keyboard.nextInt();
}
for (roomsOccupied = 1; roomsOccupied <= rooms; roomsOccupied++)
{
System.out.println("How many rooms occupied? ");
roomsOccupied = keyboard.nextInt();
roomsVacant = rooms - roomsOccupied;
System.out.println("Rooms Vacant" + roomsVacant);
}
//Calculate Occupancy Rate
occupancyRate = roomsOccupied + rooms;
System.out.println("Occupancy rate is " + occupancyRate);
}
}
}
while(floor >=10){
// Do whatever you want
}
Go through this basic while loop tutorial.
Im new on C# and now im studying enums and im having this problem on property PTx.
error " 1 Inconsistent accessibility: property type 'EE5.Taxas' is less accessible than property 'EE5.Deposito.PTx' 33 "
what should i do?
namespace EE5
{
enum Taxas
{ A = 20, B = 24, C = 30 }
enum Limites
{L1 = 2, L2 = 5 }
public class Deposito
{
private double Capital;
private int Time;
private Taxas Tx;
public Deposito(int C, double N)
{
Capital = C;
Time = N;
if (N < (int)Limites.L1)
Tx = Taxas.A;
else
if (N < (int)Limites.L2)
Tx = Taxas.B;
else
Tx = Taxas.C;
}
public Taxas PTx
{
get
{
return Tx;
}
}
Make your Taxas enum public.
namespace EE5 { public enum Taxas { A = 20, B = 24, C = 30 }
I'm new to the Visual Studio Unit Testing Framework. I've dabbled a little in XUnit, though (DUnit to be specific).
I don't know why the following tests are failing. Based on my C# code (exhibit A), I would think my tests (exhibit B) would pass with the proverbial flying colors.
[EXHIBIT A - Pertinent code]
public class MessageClass
{
private int _messageTypeCode = 0;
private int _messageTypeSubcode;
private int _messageSequenceNumber;
private string _messageText;
public MessageClass()
{
this._messageTypeCode = 0;
this._messageTypeSubcode = 0;
this._messageSequenceNumber = 0;
this._messageText = string.Empty;
}
public void SetMessageTypeSubcode(int AMessageTypeSubcode)
{
int iMsgTypeSubCode = AMessageTypeSubcode;
if (iMsgTypeSubCode > 9999)
{
iMsgTypeSubCode = 9999;
}
else if (iMsgTypeSubCode < 0)
{
iMsgTypeSubCode = 42;
}
_messageTypeSubcode = AMessageTypeSubcode;
}
public int MessageTypeSubcode()
{
return _messageTypeSubcode;
}
[EXHIBIT B - Test code in the corresponding MessageClassTest]
[TestMethod()]
public void SetMessageTypeSubcodeTest()
{
int AMessageTypeSubcode;
// Should I put this class instantiation in MyTestInitialize?
MessageClass target = new MessageClass();
// Test 1
AMessageTypeSubcode = 0;
target.SetMessageTypeSubcode(AMessageTypeSubcode);
Assert.AreEqual(AMessageTypeSubcode, target.MessageTypeSubcode());
// Test 2 - 10000 is too much
AMessageTypeSubcode = 12345;
target.SetMessageTypeSubcode(AMessageTypeSubcode);
Assert.AreEqual(9999, target.MessageTypeSubcode());
// Test 3 - val must be positive
AMessageTypeSubcode = -77;
target.SetMessageTypeSubcode(AMessageTypeSubcode);
Assert.AreEqual(42, target.MessageTypeSubcode());
}
... It is failing on the second test. Having set the val higher than the cutoff (9999), it should be assigned that (9999) rather than 12345.
As I said, I'm new to Visual Studio Unit Testing Framework; is it not possible to have more than one test in a TestMethod? Or do I need to do something like call flush() or finish() or close() or reset() or something?
The tests are failing because the test should fail. Your method is incorrect:
_messageTypeSubcode = AMessageTypeSubcode;
Should be:
_messageTypeSubcode = iMsgTypeSubCode ;