Using the do while - infinite loop - powershell

I'm completely lost on some homework. The assignment is to use a while loop and prompt the user to enter 5 numbers. My current code looks like the following:
$x = 1
do
{
Write-Host 'Enter 5 numbers'
$x++
} while ($x -eq 5)
Seems like issue is somewhere in here ($x -eq "5"). I want PowerShell just to prompt the user for 5 random numbers then get the sum of those numbers.

A homework assignment. 8^}
Oh well... Here is one way to do this.
Yet, taking your original post and what you show in your comment. Your issue is, you are not capturing anything to sum up, nor are you using a counter to meet you entry limit.
Clear-Host
# Initial variables
$ResponseCount = 0
$Total = 0
do {
# Get a user response
$response = Read-Host "Enter 5 numbers"
# increment response counts
$ResponseCount ++
# capture and sum the entered numbers
$Total += $response
}
until ($ResponseCount -eq "5")
"`nYou have completed the required 5 entries"
"The sum of the entered numbers is: $Total"
Enter 5 numbers: 10
Enter 5 numbers: 20
Enter 5 numbers: 30
Enter 5 numbers: 40
Enter 5 numbers: 50
You have completed the required 5 entries
The sum of the entered numbers is: 150

You're correct that the issue is your condition for the loop. Currently you're telling PowerShell to run the loop while $x is exactly five. If you want your loop to properly work you will have to change the condition. You can check the PowerShell help for about_Comparison_Operators to get an idea about the operators that are available.
The other thing you need to do is read the actual values and save whatever the user enters to build the sum. There are quite a few approaches to this and the other answer has a solution for that. Also consider using more expressive variable names to make it easier for someone else to follow your code (though that's not so much an issue for this short example).

Related

Range operator [3..max?] for selecting elements from an array [duplicate]

How can I get the array element range of first to second last?
For example,
$array = 1,2,3,4,5
$array[0] - will give me the first (1)
$array[-2] - will give me the second last (4)
$array[0..2] - will give me first to third (1,2,3)
$array[0..-2] - I'm expecting to get first to second last (1,2,3,4) but I get 1,5,4 ???
I know I can do long hand and go for($x=0;$x -lt $array.count;$x++), but I was looking for the square bracket shortcut.
You just need to calculate the end index, like so:
$array[0..($array.length - 2)]
Do remember to check that you actually have more than two entries in your array first, otherwise you'll find yourself getting duplicates in the result.
An example of such a duplicate would be:
#(1)[0..-1]
Which, from an array of a single 1 gives the following output
1
1
There might be a situation where you are processing a list, but you don't know the length. Select-object has a -skiplast parameter.
(1,2,3,4,5 | select -skiplast 2)
1
2
3
As mentioned earlier the best solution here:
$array[0..($array.length - 2)]
The problem you met with $array[0..-2] can be explained with the nature of "0..-2" expression and the range operator ".." in PowerShell. If you try to evaluate just this part "0..-2" in PowerShell you will see that result will be an array of numbers from 0 to -2.
>> 0..-2
0
-1
-2
And when you're trying to do $array[0..-2] in PowerShell it's the same as if you would do $array[0,-1,-2]. That's why you get results as 1, 5, 4 instead of 1, 2, 3, 4.
It could be kind of counterintuitive at first especially if you have some Python or Ruby background, but you need to take it into account when using PowerShell.
Robert Westerlund answer is excellent.
This answer I just saw on the Everything you wanted to know about arrays page and wanted to try it out.
I like it because it seems to describe exactly what the goal is, end at one short of the upper bound.
$array[0..($array.GetUpperBound(0) - 1)]
1
2
3
4
I used this variation of your original attempt to uninstall all but the latest version from Get-InstalledModule. It's really short, but not perfect because if there are more than 9 items it still returns just 8, but you can put a larger negative number, though.
$array[-9..-2]
1
2
3
4

How to correctly round numbers in PowerShell

As the title suggest i'm expiriencing some issues with rounding numbers. My Script currently looks like this:
[uint16]$Product1 = Read-Host "Enter the price of your product: "
...
#$TotalProducts contains the Value from all products together
Write-Host "You spent an amount of $TotalProducts for todays shopping."
I want the programm to round the numbers so the total isn't some ridiculous long number. It does work but after i calculated it manually i saw that the programm calculated something else.
The problem here is that the programm rounds for example 122.50 to 122 instead of 123.
I tried using the following syntax but without success:
[math]::Round($Product1)[System.Midpoint.Rounding]::AwayFromZero) = Read-Host "Enter the price of your product: "
Am i trying the right thing but i'm butchering the syntax or am i completly wrong with this approach?
Read-Host returns a string.
You should read first, then round the number.
$Product1 = Read-Host "Enter the price of your product: "
$RoundedNumber = [math]::Round($Product1, [System.MidpointRounding]::AwayFromZero)
You now have your rounded value in $RoundedNumber.

How to Have Multiple or Conditions for While Loop

I'm trying to make a basic while loop to get back into the swing of things with matlab. All I'm trying to do is create a prompt to ask the user if today is their birthday and if they say yes it'll wish them happy birthday and if they say no it'll say "that's too bad". I can make the prompts appear but what I want to do is unless the user inputs 'yes' or 'no' they will continually be asked if today is their birthday. My question is how I create the loop to prompt my question over and over until the user inputs 'yes' or 'no'.
Try this:
while 1
b = input('Is today your birthday? ','s');
if any(strcmpi(b,{'yes','no'}))
break
end
end
Here is a way (there are many others):
Use a while loop in which you put the prompt (here I use inputdlg) and once the user enters the answer, you check if the string entered compares to either yes, Yes, no and No. If it does not, the dialog box pops up again. If it fits, a message appears.
In order to compare multiple strings at once, you can use strcmp with the answer provided by the user and use a cell array containing the strings you are looking for (i.e. yes/no/etc.). If the answer corresponds to any of the strings, the array (called CheckAns) contains a 1 and the sum is different than 0; otherwise the sum equals 0 so the loop continues.
That's a lot of words so here is the code:
%// Initialize the look up array. All 0 to start and enter the loop
CheckAns = [0 0 0 0];
while ~sum(CheckAns)
Ans = inputdlg('Is this your birthday?');
CheckAns = strcmpi(Ans,{'yes';'no'});
if strcmpi(Ans,'yes')
disp('Happy birthday')
elseif strcmpi(Ans,'no')
disp('Haha loser')
end
end

Looping in filemaker using a local variable

Been programming in C# for a little bit - trying to use file maker and I cant believe it but I cant even get a simple for loop to work.
What I want to do is simple: loop through for the amount of entries in my "amountOfRooms" field and create an entry in a table for each room.
Sounds so simple, but I cant get it to work. Right now I have this:
Set Variable[$cnt[Customers::AmountOfRooms]; value:1]
Go to Layout["rooms"(Rooms)]
Loop
Exit Loop If[$cnt = Customers::AmountOfRooms]
New Record / Request
Set Variable[$cnt; Value: $cnt + 1]
End Loop
Exit Script
No new records are created. I know the script is running because it does go to my layout, but doesnt create any new records. There is a "Repetition" field for my local variable - not sure how to use that or what it means? Any thoughts on how to do this simple loop? Thanks.
Loop
Depending on your relationship, the line Exit Loop If[$cnt = Customers::AmountOfRooms] might be equal at the first iteration because you set the variable to the value three lines above it: Set Variable[$cnt[Customers::AmountOfRooms]; value:1]
There are other ways to do it, but one common technique is to have a $i variable compare against $cnt like this:
Set Variable [$cnt; Value:Customers::AmountOfRooms]
Go to Layout ["Rooms" (Rooms)]
#
Set Variable [$i; Value:1]
Loop
Exit Loop If [$i >= $cnt]
New Record/Request
Set Variable [$i; Value:$i + 1]
End Loop
Exit Script []
Repetition Number
At a high level, you can think of a FileMaker variable as a 1-indexed array. So the statements:
# Set Repetition 1 of $i to 1
Set Variable [$i; Value:1]
#
# Set Repetition 2 of $j to "Second Array Position"
Set Variable [$j[2]; Value:"Second Array Position"]
Would be equivalent to:
# Set the first value of array $i to 1
$i[0] = 1;
#
# Set the second value of array $j to "Second Array Position"
$j[1] = "Second Array Position";
in some other languages.
It's worth nothing that the array comparison is not strictly apt, but it's a good way to begin thinking of them. Regardless, you don't need to worry about the repetition number in this instance. If you want to learn more, you can start here: http://www.filemaker.com/11help/html/scripts_ref1.36.15.html

Need to add two values in perl

In if condition I used to take one value from log file after matching the particular pattern. That pattern is matched two times in log file. While matching the pattern first time that value is 0 and second time value is 48. It may be also reverse. First value may contain 48 and second value may contain 0. I need to calculate the exact value. So I planned to add these two values. but after adding these two values also while printing the total value in if condition I used to get the two values separately. But I need single value only.
Please give me solution to solve this issue.
Thanks in advance.
Do you mean something like this:
my $entry = "First is 10, seconds is 48";
if(my ($a,$b) = $entry =~ /(\d+)/g) {
print $a + $b,"\n"; # 58
}
But without actual code it is hard to see what your problem really is.