write code calculater app in ArkTS
- User
write code calculater app in ArkTS
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
write code calculater app in ArkTS
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Below is a simple calculator app implemented in ArkTS (Ark TypeScript). This example includes basic operations such as addition, subtraction, multiplication, and division, and a basic user interface.
Please note that ArkTS is used in HarmonyOS, and the following example assumes that you have a basic understanding of building applications for this ecosystem.
import { Application, Component, View, Text, Button, TextInput } from '@arkjs/ui';
class CalculatorApp extends Component {
private num1: string = '';
private num2: string = '';
private result: string = '';
private setNum1(value: string) {
this.num1 = value;
}
private setNum2(value: string) {
this.num2 = value;
}
private add() {
const sum = parseFloat(this.num1) + parseFloat(this.num2);
this.result = sum.toString();
}
private subtract() {
const difference = parseFloat(this.num1) - parseFloat(this.num2);
this.result = difference.toString();
}
private multiply() {
const product = parseFloat(this.num1) * parseFloat(this.num2);
this.result = product.toString();
}
private divide() {
const num1Value = parseFloat(this.num1);
const num2Value = parseFloat(this.num2);
if (num2Value !== 0) {
const quotient = num1Value / num2Value;
this.result = quotient.toString();
} else {
this.result = 'Error: Division by 0';
}
}
render() {
return (
<View>
<TextInput placeholder="Enter first number" onChange={this.setNum1.bind(this)} />
<TextInput placeholder="Enter second number" onChange={this.setNum2.bind(this)} />
<Button text="Add" onClick={this.add.bind(this)} />
<Button text="Subtract" onClick={this.subtract.bind(this)} />
<Button text="Multiply" onClick={this.multiply.bind(this)} />
<Button text="Divide" onClick={this.divide.bind(this)} />
<Text>Result: {this.result}</Text>
</View>
);
}
}
const app = new Application();
app.render(<CalculatorApp />);
Component: The CalculatorApp class extends Component and manages the state of the first number (num1), the second number (num2), and the calculation result (result).
Methods: Four methods are implemented to handle the four basic operations. Each method parses the numbers from strings, performs the calculation, and updates the result.
User Interface: The render method defines the user interface, which includes two inputs for numbers, buttons for each operation, and a text display for the result.
Make sure to handle potential errors and edge cases for better user experience, such as invalid inputs. The example provided is for simplicity and clarity.
Not yet included in a published release.