Blockquote
I want to make a calculator which calculate the general point of subjects. For exm, every right question of Math gives 8 points, so 25 questions and 5 wrong answers will give 25-5=20*8=160. And then continue to count other subjects (History, Geography...) to give me at the end the total point. In terminal it asks me till the wrong question and then does not show the general point. What should I do?
void main() {
String? Subject;
int General;
String? Math;
String? History;
String? Geography;
String? Spanish;
String? English;
int AllQuestions;
int Wrong;
print("Let's calculate your points");
print("Choose the subject");
Subject = stdin.readLineSync();
print("Enter the number of questions");
AllQuestions = int.parse(stdin.readLineSync()!);
print("Enter the number of wrong questions");
Wrong = int.parse(stdin.readLineSync()!);
if (Subject == Math) {
General = (AllQuestions - Wrong)*8;
print(General);
}
if (Subject == History) {
General = (AllQuestions - Wrong)*4;
print(General);
}
if (Subject == Geography) {
General = (AllQuestions - Wrong)*8;
print(General);
}
if (Subject == Snapish) {
General = (AllQuestions - Wrong)*4;
print(General);
}
if (Subject == English) {
General = (AllQuestions - Wrong)*4;
print(General);
}
Because you intialized your variables with no values for the Strings. Example:
String? Math;
should be:
String? Math = "Math";
I believe you want something like this:
void main() {
String? Subject;
int General;
int AllQuestions;
int Wrong;
print("Let's calculate your points");
print("Choose the subject");
Subject = stdin.readLineSync();
print("Enter the number of questions");
AllQuestions = int.parse(stdin.readLineSync()!);
print("Enter the number of wrong questions");
Wrong = int.parse(stdin.readLineSync()!);
if (Subject == "Math") {
General = (AllQuestions - Wrong)*8;
print(General);
}
if (Subject == "History") {
General = (AllQuestions - Wrong)*4;
print(General);
}
if (Subject == "Geography") {
General = (AllQuestions - Wrong)*8;
print(General);
}
if (Subject == "Spanish") {
General = (AllQuestions - Wrong)*4;
print(General);
}
if (Subject == "English") {
General = (AllQuestions - Wrong)*4;
print(General);
}
}
Related
I am trying to build a basic quiz app to improve my, so I was able to use if and else statement to know when they entered the right answer or not then I will print out their score, I was able to achieve this, so the main issue is that I want to add all the sores together and tell them the total they have scored. my code is below. thanks in advance.
import 'dart:io';
import 'dart:math';
void main() {
print("Hi, welcome to quize app");
print("what is your name?");
String? username = stdin.readLineSync();
print("welcome ${username}");
print("Who is Christiano ronaldo?");
List? answers1 = [26, 30, 37, 36];
List? answers2 = ['Musician', 'Footballer', 'Swimmer'];
List? answers3 = [3, 5, 7, 17];
List? answers4 = ['Yes', 'No'];
int? ans1 = 36;
String? ans2 = 'Footballer';
int? ans3 = 17;
String? ans4 = 'no';
int? num1 = (0 + 10);
int? num2 = (0 + 0);
int? num3 = (10 + 10 + 20);
print(answers1);
int? userans1 = int.parse(stdin.readLineSync()!);
print("Who the next president of Nigeria?");
print(answers2);
String? userans2 = stdin.readLineSync();
print(
"How many times did national Grid collaps in 2022 alone? please type in numbers:");
print(answers3);
int? userans3 = int.parse(stdin.readLineSync()!);
print('Is Nigerian air still functioning?');
print(answers4);
String? userans4 = stdin.readLineSync();
print('end of quize');
print('calculating answers...');
if (userans1 == ans1) {
String? cal = "$num1";
print("In question number one (1) you got $cal");
} else {
String? cal1 = "$num2";
print("In question number one (1) you got $cal1");
}
if (userans2 == ans2) {
String? cal = "$num1";
print("In question Number two (2) you got $cal");
} else {
String? cal1 = "$num2";
print("In question Number two (2) you got $cal1");
}
if (userans3 == ans3) {
String? cal = "$num1";
print("In question Number three (3) you got $cal");
} else {
String? cal1 = "$num2";
print("In question Number three (3) you got $cal1");
}
if (userans4 == ans4) {
String? cal = "$num1";
print("In question Number four (4) you got $cal");
} else {
String? cal1 = "$num2";
print("In question Number four (4) you got $cal1");
}
}
It is not just about Dart, it is a general programming logic question.
You can declare a variable of type int to hold the total score and start it with value of 0 like the following:
int totalScore = 0;
then every time the user answers a question correctly, just add the score of the question to the answer, for example:
if (userans1 == ans1) {
String? cal = "$num1";
print("In question number one (1) you got $cal");
totalScore += 10; // 10 is the score user received, replace it with the correct score.
}
Note: totalScore += 10 is equivalent to totalScore = totalScore + 10
At the end, you will have the Total Score in our variable, do whatever you want with it.
That's it!
I want to count the number of letters, digits and special characters in the following string:
let phrase = "The final score was 32-31!"
I tried:
for tempChar in phrase {
if (tempChar >= "a" && tempChar <= "z") {
letterCounter++
}
// etc.
but I'm getting errors. I tried all sorts of other variations on this - still getting error - such as:
could not find an overload for '<=' that accepts the supplied arguments
For Swift 5 see rustylepord's answer.
Update for Swift 3:
let letters = CharacterSet.letters
let digits = CharacterSet.decimalDigits
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.contains(uni) {
letterCount += 1
} else if digits.contains(uni) {
digitCount += 1
}
}
(Previous answer for older Swift versions)
A possible Swift solution:
var letterCounter = 0
var digitCount = 0
let phrase = "The final score was 32-31!"
for tempChar in phrase.unicodeScalars {
if tempChar.isAlpha() {
letterCounter++
} else if tempChar.isDigit() {
digitCount++
}
}
Update: The above solution works only with characters in the ASCII character set,
i.e. it does not recognize Ä, é or ø as letters. The following alternative
solution uses NSCharacterSet from the Foundation framework, which can test characters
based on their Unicode character classes:
let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.longCharacterIsMember(uni.value) {
letterCount++
} else if digits.longCharacterIsMember(uni.value) {
digitCount++
}
}
Update 2: As of Xcode 6 beta 4, the first solution does not work anymore, because
the isAlpha() and related (ASCII-only) methods have been removed from Swift.
The second solution still works.
Use the values of unicodeScalars
let phrase = "The final score was 32-31!"
var letterCounter = 0, digitCounter = 0
for scalar in phrase.unicodeScalars {
let value = scalar.value
if (value >= 65 && value <= 90) || (value >= 97 && value <= 122) {++letterCounter}
if (value >= 48 && value <= 57) {++digitCounter}
}
println(letterCounter)
println(digitCounter)
For Swift 5 you can do the following for simple strings, but be vigilant about handling characters like "1️⃣" , "④" these would be treated as numbers as well.
let phrase = "The final score was 32-31!"
var numberOfDigits = 0;
var numberOfLetters = 0;
var numberOfSymbols = 0;
phrase.forEach {
if ($0.isNumber) {
numberOfDigits += 1;
}
else if ($0.isLetter) {
numberOfLetters += 1
}
else if ($0.isSymbol || $0.isPunctuation || $0.isCurrencySymbol || $0.isMathSymbol) {
numberOfSymbols += 1;
}
}
print(#"\#(numberOfDigits) || \#(numberOfLetters) || \#(numberOfSymbols)"#);
I've created a short extension for letter and digits count for a String
extension String {
var letterCount : Int {
return self.unicodeScalars.filter({ CharacterSet.letters.contains($0) }).count
}
var digitCount : Int {
return self.unicodeScalars.filter({ CharacterSet.decimalDigits.contains($0) }).count
}
}
or a function to get a count for any CharacterSet you put in
extension String {
func characterCount(for set: CharacterSet) -> Int {
return self.unicodeScalars.filter({ set.contains($0) }).count
}
}
usage:
let phrase = "the final score is 23-13!"
let letterCount = phrase.characterCount(for: .letters)
In case you only need one information (letter or number or sign) you can do it in one line:
let phrase = "The final score was 32-31!"
let count = phrase.filter{ $0.isLetter }.count
print(count) // "16\n"
But doing phrase.filter several times is inefficient because it loops through the whole string.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm currently taking a chemistry class and thought it would be fun to make a program that can calculate the pH of strong/weak acid solutions. The code works in playgrounds and I'd like to eventually implement it into an iOS project. The program takes in 3 parameters: the initial concentration of the acid, the acid's chemical formula, and the equilibrium constant of the acid (if needed). The program begins by taking in the initial concentration of the acid, then it takes in the chemical formula of the acid and determines if the acid is strong or weak. Next, I set up an if statement to calculate the pH according to the strength of the acid. If the acid is weak, an equilibrium constant is needed. Here is what I have so far:
import UIKit
func acidConcentration(acidMolarity: Double) -> Double {
return acidMolarity
}
let initialConcentration = acidConcentration(0.50)
var hydroniumConcentration = 0.00
var pH = 0.00
func determineAcidStrength(acidName: String) -> String {
var acidStrength = ""
if acidName=="HBr" || acidName=="HI" || acidName=="HClO4" || acidName=="HCl" || acidName=="HClO3" || acidName=="H2SO4" || acidName=="HNO3" {
acidStrength = "strong"
} else {
acidStrength = "weak"
}
return acidStrength
}
let strength = determineAcidStrength("HBr")
if strength == "strong" {
hydroniumConcentration = initialConcentration
pH = -log10(hydroniumConcentration)
print(String(format: "%.2f", pH))
} else {
func equilibriumConstant(ka: Double) -> Double {
return ka
}
let eqConstant = equilibriumConstant
var weakAcidConcentration = sqrt(eqConstant(1.8e-5) * initialConcentration)
pH = -log10(weakAcidConcentration)
print(String(format: "%.2f", pH))
}
As I am very new to programming and this is my first attempt at writing any code, I was wondering if there are any ways to clean up what I have or any tips to organize the code better. Any help is appreciated. Thanks.
The code that you have posted is overly complicated for something that can be accomplished in a single function.
The function below accepts 2 arguments, the acidName as a String, and the initialConcentration as a Double and returns the concentration as a Double value.
func calculateConcentration(acidName: String, initialConcentration: Double) -> Double {
var acidIsStrong = false;
if acidName=="HBr" || acidName=="HI" || acidName=="HClO4" || acidName=="HCl" || acidName=="HClO3" || acidName=="H2SO4" || acidName=="HNO3" {
acidIsStrong = true;
}
if acidIsStrong {
return -log10(initialConcentration);
} else {
return -log10( (1.8e-5) * initialConcentration);
}
}
Here is an example use of the function:
//Just pass in your acid name and initial concentration
let concentration = calculateConcentration("HBr", initialConcentration: 0.50);
print(String(format: "%.2f", concentration));
Here is a smaller version of the function written a bit more efficiently (it works the same):
func calculateConcentration(acidName: String, initialConcentration: Double) -> Double {
if acidName=="HBr" || acidName=="HI" || acidName=="HClO4" || acidName=="HCl" || acidName=="HClO3" || acidName=="H2SO4" || acidName=="HNO3" {
return -log10(initialConcentration);
}
return -log10( (1.8e-5) * initialConcentration);
}
And an even smaller version that isn't very readable:
func calculateConcentration(acidName: String, initialConcentration: Double) -> Double {
return -log10( initialConcentration * ((acidName=="HBr" || acidName=="HI" || acidName=="HClO4" || acidName=="HCl" || acidName=="HClO3" || acidName=="H2SO4" || acidName=="HNO3") ? (1.8e-5) : 1.0));
}
I'm not much of a chemist so, I'm not sure about the formula, but how about this:
class Acid: CustomStringConvertible {
static let strongAcids = [ "HBr", "HI", "HClO4", "HCl", "HClO3", "H2SO4", "HNO3" ]
var name: String
var concentration: Double
var equilibriumConstant: Double?
var pH: Double {
get {
var adjustedConcentration = concentration
if !Acid.strongAcids.contains(name) {
guard let ka = equilibriumConstant else {
return Double.NaN;
}
adjustedConcentration = sqrt(ka * concentration)
}
return -log10(adjustedConcentration)
}
}
init(name: String, concentration: Double, equilibriumConstant ka: Double? = nil) {
self.name = name
self.concentration = concentration
self.equilibriumConstant = ka
}
var description: String {
get {
if let ka = equilibriumConstant {
return "\(name) (concentration: \(concentration) / EqK: \(ka) pH: \(String(format: "%.2f", pH)))"
} else {
return "\(name) (concentration: \(concentration) / pH: \(String(format: "%.2f", pH)))"
}
}
}
}
let acid = Acid(name: "HBr", concentration: 0.5);
print("\(acid)") // prints "HBr (concentration: 0.5 / pH: 0.30)"
print(String(format: "%.2f", acid.pH)) // prints "0.30"
let weakAcid = Acid(name: "Weak", concentration: 0.2, equilibriumConstant: 1.8e-5)
print("\(weakAcid)") // prints "Weak (concentration: 0.2 / EqK: 1.8e-05 pH: 2.72)"
As for creating an app... For a simple app like this, you can probably just create a "Single View Application" with 3 text fields (name, concentration, and constant) and a button the "calculate". I hope that makes sense.
I am making a game using Swift and SpriteKit where i move an object to random locations based on an array.
The array that is made up of CGPoints:
let easyArray = [CGPointMake(0,0), CGPointMake(126.6,0), CGPointMake(253.4,0), CGPointMake(0,197.5), CGPointMake(126.7,197.5), CGPointMake(253.4,197.5), CGPointMake(0,395), CGPointMake(126.7,395), CGPointMake(253.4,395)]
I use this function to generate a random number:
func randomNumber(maximum: UInt32) -> Int {
var randomNumber = arc4random_uniform(maximum)
while previousNumber == randomNumber {
randomNumber = arc4random_uniform(maximum)
}
previousNumber = randomNumber
return Int(randomNumber)
}
I used this to move the object based on the random number generated:
let greenEasy = randomNumberNew(9)
let moveSelector = SKAction.moveTo(easyArray[greenEasy], duration: 0)
selector.runAction(moveSelector)
I have done some reading online and found that the "While" condition should make it so that the same random number isn't generate twice in a row. But it still happens.
Can anyone please help me on how to make it so i don't get the same number twice in a row?
The code below doesn't random the same number.
var currentNo: UInt32 = 0
func randomNumber(maximum: UInt32) -> Int {
var randomNumber: UInt32
do {
randomNumber = (arc4random_uniform(maximum))
}while currentNo == randomNumber
currentNo = randomNumber
return Int(randomNumber)
}
I think Larme's suggestion is pretty clever, actually.
easyArray.append(easyArray.removeAtIndex(Int(arc4random_uniform(UInt32(easyArray.count)-1))))
selector.runAction(SKAction.moveTo(easyArray.last!, duration: 0))
I would recommend to not use while() loops with randomizers.
Theoretically it can cause infinite loops in worst case scenario, in more positive scenario it will just take few loops before you get desired results.
Instead I would advice to make an NSArray of all values, remove from this NSArray last randomized element and randomize any of other existing elements from such an array - that is guarantee result after only one randomize iteration.
It can be easily achieved by making NSArray category in Objective-C:
- (id) randomARC4Element
{
if(self.count > 0)
{
return [self objectAtIndex:[self randomIntBetweenMin:0 andMax:self.count-1]];
}
return nil;
}
- (int)randomIntBetweenMin:(int)minValue andMax:(int)maxValue
{
return (int)(minValue + [self randomFloat] * (maxValue - minValue));
}
- (float)randomFloat
{
return (float) arc4random() / UINT_MAX;
}
If you can use linq then you can select a random value that doesn't match the last value. Then for any left over values you can loop through and find valid places to insert them.
It's not the most efficient but it works.
public static List<int> Randomize(List<int> reps, int lastId) {
var rand = new Random();
var newReps = new List<int>();
var tempReps = new List<int>();
tempReps.AddRange(reps);
while (tempReps.Any(x => x != lastId)) {
var validReps = tempReps.FindAll(x => x != lastId);
var i = rand.Next(0, validReps.Count - 1);
newReps.Add(validReps[i]);
lastId = validReps[i];
tempReps.Remove(validReps[i]);
}
while (tempReps.Any()) {
var tempRep = tempReps.First();
bool placed = false;
for (int i = 0; i < newReps.Count; i++) {
if (newReps[i] == tempRep) {
continue;
}
else if ((i < newReps.Count - 1) && (newReps[i + 1] == tempRep)) {
continue;
}
else {
newReps.Insert(i + 1, tempRep);
placed = true;
break;
}
}
if (placed) {
tempReps.Remove(tempRep);
}
else {
throw new Exception("Unable to randomize reps");
}
}
return newReps;
}
I want to count the number of letters, digits and special characters in the following string:
let phrase = "The final score was 32-31!"
I tried:
for tempChar in phrase {
if (tempChar >= "a" && tempChar <= "z") {
letterCounter++
}
// etc.
but I'm getting errors. I tried all sorts of other variations on this - still getting error - such as:
could not find an overload for '<=' that accepts the supplied arguments
For Swift 5 see rustylepord's answer.
Update for Swift 3:
let letters = CharacterSet.letters
let digits = CharacterSet.decimalDigits
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.contains(uni) {
letterCount += 1
} else if digits.contains(uni) {
digitCount += 1
}
}
(Previous answer for older Swift versions)
A possible Swift solution:
var letterCounter = 0
var digitCount = 0
let phrase = "The final score was 32-31!"
for tempChar in phrase.unicodeScalars {
if tempChar.isAlpha() {
letterCounter++
} else if tempChar.isDigit() {
digitCount++
}
}
Update: The above solution works only with characters in the ASCII character set,
i.e. it does not recognize Ä, é or ø as letters. The following alternative
solution uses NSCharacterSet from the Foundation framework, which can test characters
based on their Unicode character classes:
let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.longCharacterIsMember(uni.value) {
letterCount++
} else if digits.longCharacterIsMember(uni.value) {
digitCount++
}
}
Update 2: As of Xcode 6 beta 4, the first solution does not work anymore, because
the isAlpha() and related (ASCII-only) methods have been removed from Swift.
The second solution still works.
Use the values of unicodeScalars
let phrase = "The final score was 32-31!"
var letterCounter = 0, digitCounter = 0
for scalar in phrase.unicodeScalars {
let value = scalar.value
if (value >= 65 && value <= 90) || (value >= 97 && value <= 122) {++letterCounter}
if (value >= 48 && value <= 57) {++digitCounter}
}
println(letterCounter)
println(digitCounter)
For Swift 5 you can do the following for simple strings, but be vigilant about handling characters like "1️⃣" , "④" these would be treated as numbers as well.
let phrase = "The final score was 32-31!"
var numberOfDigits = 0;
var numberOfLetters = 0;
var numberOfSymbols = 0;
phrase.forEach {
if ($0.isNumber) {
numberOfDigits += 1;
}
else if ($0.isLetter) {
numberOfLetters += 1
}
else if ($0.isSymbol || $0.isPunctuation || $0.isCurrencySymbol || $0.isMathSymbol) {
numberOfSymbols += 1;
}
}
print(#"\#(numberOfDigits) || \#(numberOfLetters) || \#(numberOfSymbols)"#);
I've created a short extension for letter and digits count for a String
extension String {
var letterCount : Int {
return self.unicodeScalars.filter({ CharacterSet.letters.contains($0) }).count
}
var digitCount : Int {
return self.unicodeScalars.filter({ CharacterSet.decimalDigits.contains($0) }).count
}
}
or a function to get a count for any CharacterSet you put in
extension String {
func characterCount(for set: CharacterSet) -> Int {
return self.unicodeScalars.filter({ set.contains($0) }).count
}
}
usage:
let phrase = "the final score is 23-13!"
let letterCount = phrase.characterCount(for: .letters)
In case you only need one information (letter or number or sign) you can do it in one line:
let phrase = "The final score was 32-31!"
let count = phrase.filter{ $0.isLetter }.count
print(count) // "16\n"
But doing phrase.filter several times is inefficient because it loops through the whole string.