如何存储java循环输出?

时间:2017-07-20 05:08:38

标签: java for-loop

这里是我的随机邮件生成器代码,我想保存那些随机邮件,我该怎么做?

public class stupit {

    public static void main(String[] args) {
        Random randomGenerator = new Random();

        for (int i=1; i<=5; i++) {
            int randomInt = randomGenerator.nextInt(1000);
            System.out.println("username"+randomInt+"@gmail.com");
        }
    }
}

输出是:

 username394@gmail.com
 username429@gmail.com
 username70@gmail.com
 username419@gmail.com
 username744@gmail.com

如何将这些输出保存为 a = username394@gmail.co ,   b =username429@gmail.com .....

2 个答案:

答案 0 :(得分:1)

您需要为要保存这些电子邮件的数据库添加其他驱动程序库。
您可以在maven central中找到数据库的jdbc驱动程序。

对于mysql数据库,通用代码可以如下所示:

ArrayList<String> objectsToStore = new ArrayList<>();
    Random rnd = new Random();

    for (int i = 1; i <= 5; i++) {
        objectsToStore.add("username" + rnd.nextInt() + "@gmail.com");
    }

    try {
        //1) this used to load mysql jdbc driver into memory
        Class.forName("com.mysql.jdbc.Driver");
        //2) create connection to running mysql instance
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName?useSSL=false", "username", "password");
        connection.setAutoCommit(false);
        Statement statement = connection.createStatement();
        for (String x : objectsToStore) {
            // this insert will work assuming you have table user_data with email field
            statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" + x +"')");
        }
        //commit transaction
        connection.commit();
        statement.close();
        connection.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

用于在数据库中创建表的SQL:

create table User_data(
  email varchar(255)
);

答案 1 :(得分:-1)

如果你想保存它们......在循环外面声明一个字符串[] arrsy ....然后尝试使用嵌套循环将邮件地址存储在字符串中......

你也可以使用FileIlnputStrem类将它们存储在一个文本文件中.... in a txt file ...