This question already has answers here:
How to divide two Int a get a BigDecimal in Kotlin?
(3 answers)
Closed 7 months ago.
fun main() {
println("This is a calculator")
println("enter your first number")
val no1 = readLine()!!
println("enter your operation")
val operation1 = readLine()!!
println("enter your second number")
val no2 = readLine()!!
val result = if (operation1 == "*")
print(no1.toInt() * no2.toInt())
else if (operation1 == "+")
print(no1.toInt() + no2.toInt())
else if (operation1 == "-")
print(no1.toInt() - no2.toInt())
else if (operation1 == "/")
print(no1.toInt() / no2.toInt())
else
println("Please Enter just numbers and operations")
}
Whenever I run this, I can use whole numbers fine but the minute the answer is a decimal, it rounds and the if the userinput is a decimal, it comes up with an error.
if you change all of your toInt() into toDouble() it will print out everything with a decimal if it's a whole number or not but it will work correctly.
val result = if (operation1 == "*")
print(no1.toDouble() * no2.toDouble())
else if (operation1 == "+")
print(no1.toDouble() + no2.toDouble())
else if (operation1 == "-")
print(no1.toDouble() - no2.toDouble())
else if (operation1 == "/")
print(no1.toDouble() / no2.toDouble())
else
println("Please Enter just numbers and operations")
Related
I have a question I wrote this script to format an arabic text to a certain format. But I found a problem then when I type a longer sentence it adds more dots then there are letters. I will paste the code here and explain what the problem is.
import itertools
while True:
input_cloze_deletion = input("\nEnter: text pr 'exit'\n> ")
input_exit_check = input_cloze_deletion.strip().lower()
if input_exit_check == "exit":
break
# copy paste
interpunction_list = ["الله", ",", ".", ":", "?", "!", "'"]
# copy paste
interpunction_list = [ ",", ".", ":", "?", "!", "'", "-", "(", ")", "/", "الله", "اللّٰـه"]
text_replace_0 = input_cloze_deletion.replace(",", " ,")
text_replace_1 = text_replace_0.replace(".", " .")
text_replace_2 = text_replace_1.replace(":", " :")
text_replace_3 = text_replace_2.replace(";", " ;")
text_replace_4 = text_replace_3.replace("?", " ?")
text_replace_5 = text_replace_4.replace("!", " !")
text_replace_6 = text_replace_5.replace("'", " ' ")
text_replace_7 = text_replace_6.replace("-", " - ")
text_replace_8 = text_replace_7.replace("(", " ( ")
text_replace_9 = text_replace_8.replace(")", " ) ")
text_replace_10 = text_replace_9.replace("/", " / ")
text_replace_11 = text_replace_10.replace("الله", "اللّٰـه")
text_split_list = text_replace_11.split()
count_number = []
letter_count_list = []
index_list = itertools.cycle(range(1, 4))
for letter_count in text_split_list:
if letter_count in interpunction_list:
letter_count_list.append(letter_count)
elif "ـ" in letter_count:
letter_count = len(letter_count) - 1
count_number.append(letter_count)
print(letter_count)
else:
letter_count = len(letter_count)
count_number.append(letter_count)
print(letter_count)
for count in count_number:
letter_count_list.append(letter_count * ".")
zip_list = zip(text_split_list, letter_count_list)
zip_list_result = list(zip_list)
for word, count in zip_list_result:
if ((len(word)) == 2 or word == "a" or word == "و") and not word in interpunction_list :
print(f" {{{{c{(next(index_list))}::{word}::{count}}}}}", end="")
elif word and count in interpunction_list:
print(word, end = "")
else:
print(f" {{{{c{(next(index_list))}::{word}::{count}}}}}", end="")
when I type كتب عليـ ـنا و علـ ـي
the return is {{c1::كتب::...}} {{c2::عليـ::...}} {{c3::ـنا::...}} {{c1::و::..}} {{c2::علـ::..}} {{c3::ـي::..}}
but it should be
{{c1::كتب::...}} {{c2::عليـ::...}} {{c3::ـنا::..}} {{c1::و::.}} {{c2::علـ::..}} {{c3::ـي::.}}
I add a print function the print the len() results and the result is correct but it add an extra dot in some case.
But when I type just a single "و" it does a correct len() function but when I input a whole sentence it add an extra dot and I don't know why.
please help
Practicing some stuff and I've been way beyond this simple of a concept but this loop won't close and I can't understand why.
ans = "Y"
while ans == "Y" or "y":
num = int(input("What's your number? "))
if num % 2 == 0:
print("That number is even!\n")
else:
print("That number is odd!\n")
ans = str(input("Do you have another number, Y/y or N/n? "))
So I declare the variable first so I can enter the loop then ask for it again on the tail side to close it out...but no matter what I enter it continues.
I'm sure it's simple like I said i'm way past this kind of thing but it won't close and I'm not sure what the issue is?
The problem lies in the 'or "y"':
You should check if ans is Y or y which is correctly expressed as 'ans == "Y" or ans == "y"'
You as well needs to specify a starting condition for ans.
ans = "y"
while ans == "Y" or ans == "y":
num = int(input("What's your number? "))
if num % 2 == 0:
print("That number is even!\n")
else:
print("That number is odd!\n")
ans = str(input("Do you have another number, Y/y or N/n? "))
This is what I am currently using.
fun main() {
val num1 = readLine()!!.toInt()
val num2 = readLine()!!.toInt()
val num3 = readLine()!!.toInt()
println(num1 >= 1 || num2 >= 1 || num3 >= 1)
}
One way is to make a list, and count
// prints true if exactly one of the numbers is positive
println(listOf(num1, num2, num3).count { it > 0 } == 1)
If you don't want to create the list, the logic is equivalent to (num1 > 0) XOR (num2 > 0) XOR (num3 > 0), except the case when all three are positive. We can replace XORs with !=, and handle the edge case, like this:
println(((num1 > 0) != (num2 > 0) != (num3 > 0)) &&
!(num1 > 0 && num2 > 0 && num3 > 0))
Try this , it will mean if any of this number positive number then it will return true. You can't go from num1 > 1 . because one is already positive number , in your code you checking if num1 is bigger that 1 . But your questions is about positive number , then use num1 > 0 . Done!
fun main() {
val num1 = readLine()!!.toInt()
val num2 = readLine()!!.toInt()
val num3 = readLine()!!.toInt()
println(num1 > 0 || num2 > 0 || num3 > 0)
}
I have a textbox which i need to validate for the below entries and also need to replace
"3 GB" valid input
"3.2 GB" valid input
"3.2GB" valid input >> then replace as "3.2 GB"
"3.2" invalid input, ask for follow correct format MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
"VGGGB" invalid input, ask for follow correct format MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Sub Main()
Dim input = Console.ReadLine().ToUpper()
Dim nInput, value
Dim ChkDecimal As Double
If input IsNot "" Then
If input.EndsWith("TB") Then
nInput = input.Replace("TB", "")
If nInput IsNot vbNullString And IsNumeric(nInput) Then
value = Convert.ToDouble(nInput)
value = CDbl(value * 1048576 + 1)
ChkDecimal = FormatNumber(CDbl(value / 1048576), 2) Mod 1 ' check the number has a valid Decimal value
If ChkDecimal = 0 Then
Console.WriteLine(FormatNumber(CDbl(value / 1048576), 0) & " TB")
Else
Console.WriteLine(FormatNumber(CDbl(value / 1048576), 2) & " TB")
End If
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
ElseIf (input.EndsWith("GB")) Then
nInput = input.Replace("GB", "")
If nInput IsNot vbNullString And IsNumeric(nInput) Then
value = Convert.ToDouble(nInput)
value = CDbl(value * 1024)
ChkDecimal = FormatNumber(CDbl(value / 1024), 2) Mod 1 ' check the number has a valid Decimal value
If ChkDecimal = 0 Then
Console.WriteLine(FormatNumber(CDbl(value / 1024), 0) & " GB")
Else
Console.WriteLine(FormatNumber(CDbl(value / 1024), 2) & " GB")
End If
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
ElseIf input.EndsWith("MB") = True Then
nInput = input.Replace("MB", "")
If nInput IsNot vbNullString And IsNumeric(nInput) Then
value = Convert.ToDouble(nInput)
value = CDbl(value * 1)
Console.WriteLine(FormatNumber(CDbl(value * 1), 0) & " MB")
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
Else
Console.WriteLine("Capacity input Format: 99.99 MB/GB/TB")
End If
End Sub
I wouldn't use a regular-expression for this, because there's a much simpler (and more robust!) approach described below.
If you do use a regular-expression, you'll need to add all of the unit names to the expression, which is painful. Regular-expressions are not well-suited to accepting a large list of possible literal inputs.
Using a regular-expression would also mean the input would not be culture-aware, which is bad for usability (as many places around the world swap the , and . glyphs in numbers) - and you really don't want to handle things like digit-grouping, etc.
Instead, first extract and validate the unit name, then parse the numeric value using Decimal.TryParse
Like so (using C# because it's 2am here and I'm not getting paid to write this answer):
void Example()
{
String textBoxValue = "3 GB";
if( TryParseBinaryDataQuantity( textBoxValue, out Int64 valueBytes ) )
{
MessageBox.Show( "Visual Basic is dead." );
}
else
{
MessageBox.Show( "Input is not a valid binary data quantity." );
}
}
public static Boolean TryParseBinaryDataQuantity( String input, out Int64 valueBytes )
{
input = ( input ?? "" ).Trim();
if( input.Length < 3 ) // input is too short to be meaningful.
{
valueBytes = default;
return false;
}
// Extract the unit-name by taking the last 3 characters of the input string and trimming any whitespace (this isn't the most robust or correct approach, but I'm feeling lazy):
String unitName = input.Substring( startIndex: input.Length - 3 );
// Validate the unit-name and get the bytes multiplier:
if( !TryParseBinaryDataUnit( unitName, out Int64 multiplier ) )
{
valueBytes = default;
return false;
}
// Consider repeating the above but for the last 2 characters of the string in order to match input like "3GB" instead of "3GiB" and "3 GB" and "3 GiB".
// Parse and multiply:
String numberPart = input.Substring( startIndex: 0, length: input.Length - 3 );
if( Decimal.TryParse( numberPart, NumberStyles.Any, CultureInfo.CurrentCulture, out Decimal quantity )
{
Decimal bytesValue = quantity * multiplier;
// Fail if the bytesValue is non-integral or negative:
if( bytesValue != Math.Floor( bytesValue ) || bytesValue < 0 )
{
valueBytes = default;
return false;
}
return (Int64)bytesValue;
}
}
private static Boolean TryParseBinaryDataUnit( String unitName, out Int64 equivalentBytes )
{
if( "GB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024 * 1024; // or 1000 * 1000 * 1000 depending on if you're differentiating between GiB and GB.
return true;
}
else if( "GiB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024 * 1024;
return true;
}
else if( "MiB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024;
return true;
}
else if( "MB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024;
return true;
}
else if( "KB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024;
return true;
}
else if( "KB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024;
return true;
}
else
{
equivalentBytes = default;
return false;
}
}
I will recommend you to use proper library to parse the given input. I have used one in past for doing this (https://github.com/omar/ByteSize)
Here is quick example of how you can do this. I know there must be better way to do this but this would do the job =)
var input = Console.ReadLine();
input = input.ToLower();
var reg = Regex.Match(input, "([\\d\\.]+)");
if (reg.Success && double.TryParse(reg.Groups[1].Value, out double rawSize))
{
if (input.EndsWith("tb"))
Console.WriteLine(ByteSize.FromTeraBytes(rawSize));
else if (input.EndsWith("gb"))
Console.WriteLine(ByteSize.FromGigaBytes(rawSize));
else if (input.EndsWith("mb"))
Console.WriteLine(ByteSize.FromMegaBytes(rawSize));
else if (input.EndsWith("kb"))
Console.WriteLine(ByteSize.FromKiloBytes(rawSize));
}
Input> 1234.56mb
Output> 1.23 GB
You can try my method as following:
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'1.3 GB
'1.3gb
'1gb
Console.WriteLine("Pleasen input your entry:")
Dim str As String = TextBox1.Text
Dim str1 As String = str.Substring(str.Length - 2, 2)
If str1.ToUpper = "TB" Or str1.ToUpper = "GB" Or str1.ToUpper = "MB" Then
Dim str2 As String = str.Remove(str.Length - 2)
Dim str3 As String = str.Substring(str2.Length - 1, 1)
If str3 = " " Then
Dim str4 As String = str.Remove(str.Length - 3)
If Regex.IsMatch(str4, "^\d*[.]?\d*$") Then
MsgBox("valid input")
Else
MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Return
End If
Else
If Regex.IsMatch(str2, "^\d*[.]?\d*$") Then
TextBox1.Text = str.Insert(str.Length - 2, " ")
MsgBox("valid input")
Else
MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Return
End If
End If
Else
MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Return
End If
End Sub
End Class
This question already has answers here:
method for serializing lua tables
(5 answers)
Closed 8 years ago.
I would like to serialize a table so that I can insert it into a database and retrieve it later on. How would I do this?
maybe like this https://gist.github.com/rangercyh/5814003
local szStr = ""
function print_lua_table (lua_table, indent)
indent = indent or 0
for k, v in pairs(lua_table) do
if type(k) == "string" then
k = string.format("%q", k)
end
local szSuffix = ""
if type(v) == "table" then
szSuffix = "{"
end
local szPrefix = string.rep(" ", indent)
formatting = szPrefix.."["..k.."]".." = "..szSuffix
if type(v) == "table" then
szStr = szStr..formatting
print_lua_table(v, indent + 1)
szStr = szStr..szPrefix.."},"
else
local szValue = ""
if type(v) == "string" then
szValue = string.format("%q", v)
else
szValue = tostring(v)
end
szStr = szStr..formatting..szValue..","
end
end
end
How to serialize Lua value nicely?
local serialize
do
local num_fmt = '%.17g'
local NaN_serialized = { -- This idea was stolen from lua-nucleo
[num_fmt:format(1/0)] = '1/0',
[num_fmt:format(-1/0)] = '-1/0',
[num_fmt:format(0/0)] = '0/0'
}
local function serialize_table(t, indent)
indent = indent or ''
local new_indent = indent..'\t'
if next(t) == nil then
return '{}'
else
local lines = {}
local function add_line(key)
local ser_key = key
if type(key) ~= 'string' or not key:find'^[%a_][%w_]*$' then
ser_key = '['..serialize(key, new_indent)..']'
end
table.insert(lines,
ser_key..' = '..serialize(t[key], new_indent))
end
local other_keys = {}
local keys = setmetatable({number = {}, string = {}},
{__index = function() return other_keys end})
for k in pairs(t) do
table.insert(keys[type(k)], k)
end
table.sort(keys.number)
table.sort(keys.string)
for _, k in ipairs(keys.number) do
add_line(k)
end
for _, k in ipairs(keys.string) do
add_line(k)
end
for _, k in ipairs(other_keys) do
add_line(k)
end
return '{\n'..new_indent..table.concat(lines, ',\n'..new_indent)
..'\n'..indent..'}'
end
end
function serialize(v, indent)
if type(v) == 'string' then
return ('%q'):format(v)
elseif type(v) == 'boolean' then
return tostring(v)
elseif type(v) == 'nil' then
return tostring(v)
elseif type(v) == 'number' then
return (num_fmt:format(v):gsub('^.*', NaN_serialized))
elseif type(v) == 'table' then
return serialize_table(v, indent)
else
error('Can not serialize '..type(v))
end
end
end
-- What it can:
print(serialize(math.huge))
print(serialize'"What\'s up?"\n\t123')
print(serialize{{}, {{}}})
-- And what it can not:
local t = {}
local tt = {[t] = t}
print(serialize(tt)) -- tt is not a tree, so it was serialized incorrectly