我有一堆布尔变量。一些变量可能是 TRUE ,其他变量可能是 FALSE 。对于这个例子,我将有十个(10)变量:
//Variables
$a $b $c $d $e $f $g $h $i $j;
目标是在两个或多个变量为真时测试并执行代码。如果我为每个可能的变量组合声明一个条件,那么if语句将变得很长并且不可维护。
//Condition Example
if ( ($a && $b) ||
($a && $c) ||
($a && $d) ||
($a && $e) ||
($a && $f) ||
($a && $g) ||
($a && $h) ||
($a && $i) ||
($a && $j) ||
($b && $c) ||
($b && $d) ||
($b && $e) ||
($b && $f) ||
($b && $g) ||
(etc.) ){
//DO something
}
我如何测试2个或更多变量是否 TRUE ?
感谢您的回答。使用PHP的array_filter()似乎在不同情况下表现最佳。出于好奇,我测试了@AbraCadaver和@Chizzle答案的表现。
值较低(数组值5和10的1000为真)
count(array_filter($array)) : Execution time = 0.00319
array_sum($array) : Execution time = 0.00369
implode($array) : Execution time = 0.02098
foreach($array) : Execution time = 0.00939
中间值(数组值400和500的1000为真)
count(array_filter($array)) : Execution time = 0.00247
array_sum($array) : Execution time = 0.00340
implode($array) : Execution time = 0.01091
foreach($array) : Execution time = 1.00006
值很高(数组值950和1000的1000为真)
count(array_filter($array)) : Execution time = 0.00250
array_sum($array) : Execution time = 0.00329
implode($array) : Execution time = 0.01089
foreach($array) : Execution time = 1.02739
答案 0 :(得分:1)
最简单的方法(IMO)是将它们放入一个数组中,然后循环遍历它,如果找到两个真值,则快速循环。你可以把它放在这样的函数中:
<?php
// put vars into array
$varArray = array(
$a, $b, $c, $d, $e, $f, $g, $h, $i, $j
);
if(twoTrue($varArray)){
// Do something
}
function twoTrue($arrayOfVars){
$trueCount = 0;
foreach($arrayOfVars as $aVar){
if($aVar)
$trueCount++;
if($trueCount >= 2)
return true;
}
return false;
}
最糟糕的情况是必须遍历循环N次,每次变量一次。
答案 1 :(得分:1)
您应该创建一个包含变量的数组。 然后迭代它们。
例如:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package emptyframeviewer;
/**
*
* @author ACER
*/
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
/*Business P11.26 Write a program with a graphical interface that implements a login window with text
fields for the user name and password. When the login is successful, hide the login
window and open a new window with a welcome message. Follow these rules for
validating the password:
1. The user name is not case sensitive.
2. The password is case sensitive.
3. The user has three opportunities to enter valid credentials.
Otherwise, display an error message and terminate the program. When the program
starts, read the file users.txt . Each line in that file contains a username and password,
separated by a space. You should make a users.txt file for testing your program.
Business P11.27 In Exercise P11.26, the password is shown as it is typed. Browse the Swing documentation
to find an appropriate component for entering a password. Improve the
solution of Exercise P11.26 by using this component instead of a text field. Each
time the user types a letter, show a ■ character.*/
@SuppressWarnings("serial")
public class LoginFrame extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private HashMap<String, String> usernamesAndPasswords;
private JTextField usernameField;
private JTextField passwordField;
private JButton loginButton;
private JPanel loginPanel;
private JPanel welcomePanel;
private JPanel mainPanel;
private CardLayout cardLayout;
public LoginFrame() {
this.createComponents();
super.setTitle("Login Panel");
super.setSize(FRAME_WIDTH, FRAME_HEIGHT);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setVisible(true);
}
private void createComponents() {
this.mainPanel = new JPanel(new CardLayout());
this.createHashMap();
this.loginPanel = this.createLoginPanel();
this.welcomePanel = this.createWelcomePanel();
this.mainPanel.add(this.loginPanel, "LoginPanel");
this.mainPanel.add(this.welcomePanel, "WelcomePanel");
this.cardLayout = (CardLayout) this.mainPanel.getLayout();
this.cardLayout.show(this.mainPanel, "LoginPanel");
super.add(this.mainPanel);
}
private JPanel createLoginPanel() {
JPanel panel = new JPanel(new GridLayout(3, 2));
this.loginButton = new JButton("Login");
final int TEXT_FIELD_SIZE = 10;
this.usernameField = new JTextField(TEXT_FIELD_SIZE);
this.passwordField = new JPasswordField(TEXT_FIELD_SIZE);
this.loginButton.addActionListener(new ActionListener() {
private int loginAttempts = 3;
@Override
public void actionPerformed(ActionEvent arg0) {
boolean loggedIn = false;
String inputUsername = usernameField.getText().toLowerCase();
String inputPassword = passwordField.getText();
if (this.loginAttempts == 1) {
JOptionPane.showMessageDialog(null, "Number of login attemtps exceeded. Exitting...");
System.exit(1);
}
for (Map.Entry<String, String> validUser : usernamesAndPasswords.entrySet()) {
if (inputUsername.equals(validUser.getKey().toLowerCase())) {
if (inputPassword.equals(validUser.getValue())) {
System.out.println("Login successful!");
cardLayout.show(mainPanel, "WelcomePanel");
loggedIn = true;
}
}
}
if (!loggedIn) {
this.loginAttempts -= 1;
String message = String.format("Invalid username/password. %d %s remaining", this.loginAttempts,
(this.loginAttempts > 1) ? "attempts" : "attempt");
JOptionPane.showMessageDialog(null, message, "LOGIN FAILED", JOptionPane.INFORMATION_MESSAGE);
}
}
});
panel.add(new JLabel("Username"));
panel.add(this.usernameField);
panel.add(new JLabel("Password"));
panel.add(this.passwordField);
panel.add(this.loginButton);
return panel;
}
private JPanel createWelcomePanel() {
JPanel panel = new JPanel(new GridLayout(3, 1));
panel.add(new JLabel("Welcome"));
panel.add(new JButton("Change password"));
JButton logoutBtn = new JButton("Logout");
logoutBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
panel.add(logoutBtn);
return panel;
}
private void createHashMap() {
this.usernamesAndPasswords = new HashMap<String, String>();
try {
Scanner fileScanner = new Scanner(new File("usersff.txt"));
while (fileScanner.hasNextLine()) {
String[] line = fileScanner.nextLine().split(" ");
this.usernamesAndPasswords.put(line[0], line[1]);
System.out.println(line[0] + " " + line[1]);
}
fileScanner.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null,
"Error: no users.txt file found. No users/passwords available to read.", "USERS.TXT NOT FOUND!",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
public static void main(String[] args) {
JFrame testFrame = new LoginFrame();
}
}
<强> DEMO 强>
答案 2 :(得分:1)
我喜欢数组方法,但是我会过滤掉false
值并计算是否超过1:
if(count(array_filter([$a,$b,$c,$d,$e,$f,$g,$h,$i,$j])) > 1) {
// yes
}
实际上,在第二个想法中,true
将评估为1,false
评估为0。
我个人会使用这个:
if(array_sum([$a,$b,$c,$d,$e,$f,$g,$h,$i,$j]) > 1) {
// yes
}
事情一直在我脑海中浮现。对于一个true
,它将为1
,两个为11
,三个为111
等...
if(implode([$a,$b,$c,$d,$e,$f,$g,$h,$i,$j]) > 1) {
// yes
}
如果您的PHP版本不支持[]
数组,请使用array()
。
答案 3 :(得分:0)
您可以放置一个布尔变量列表并使用while循环列表,并检查是否在2为真时停止。我希望能帮助你。