我做了一个数字到数字转换器,但是看起来写起来太冗长了。 我似乎有些人在谈论使用开关。我应该用一个开关重写还是有更好的写方法?
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class BooleanBindingExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Simple interface
VBox root = new VBox(5);
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
// TextField and Button
TextField textField = new TextField();
Button button = new Button("Click Me");
root.getChildren().addAll(textField, button);
// Create a BooleanBinding for the textField to hold whether it is null
BooleanBinding isTextFieldEmpty = Bindings.isEmpty(textField.textProperty());
// Now, bind the Button's disableProperty to that BooleanBinding
button.disableProperty().bind(isTextFieldEmpty);
// Show the Stage
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
答案 0 :(得分:6)
尝试使用数组文字。
string numberToString(int n) {
return (n >= 0 && n <= 9) ?
(string[]){
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
}[n]
:
"?";
}
答案 1 :(得分:5)
我根本不会使用开关
std::string numberToString(int n)
{
const char *literal[] = {"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"};
const char *no_result = "?";
return std::string ( (n < 0 || n >= 10) ? no_result : literal[n]);
}
return语句中的转换是可选的(隐式发生),但我更希望使其明确。
如果需要,可以将literal
的类型no_result
和std::string
设置为
答案 2 :(得分:1)
简短版本:
std::string numberToString(int n)
{
return (const char *[]){"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "?"}[unsigned(n) < 11 ? n : 10];
}
答案 3 :(得分:-3)
这很容易工作,并且可读性和可重用性。
#include <string>
#include <vector>
#include <iostream>
class Converter {
private:
const std::vector<std::string> numbers{ "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine", "?" };
public:
std::string operator()( int n ) {
if ((n < 0) || (n > 10))
return numbers.at(10);
return numbers.at(n);
}
};
int main() {
Converter c;
for ( int i = -5; i < 15; i++ )
std::cout << c(5) << '\n';
return 0;
}
-输出-
?
?
?
?
?
zero
one
two
three
four
five
six
seven
eight
nine
?
?
?
?
?
?