Java的简单输入与输出
输入
1、简单输入
Scanner
类是在Java5新加的特征,我们可以使用Scanner在控制台输入信息
next.Line()与next()的区别:
1、next.Line()是以回车为结束符,可以获得空白
2、next()是不能得到带有空格的字符串,一定要读取到有效字符后才可以结束输入
public class Dome1{
public static void main(String[] args){
// 从键盘接受数据
var sc = new Scanner(System.in);
// 因为类不会提示 所以添加一行说明提示
System.out.println("请输入数据:");
// 使用nextLine() 接受数据
String str = sc.nextLine();
System.out.println(str);
}
}
2、窗口输入
JOptionPane
输入内容确定的话就是字符串值,不确定的都是null
public class Dome2{
public static void main(String[] args){
// 参数有父组件 消息 标题 图片 初始化值等等
// 这里参数只有消息
//String w = JOptionPane.showInputDialog("请输入词汇:");
// 参数有消息 有初始化信息word
//String w = JOptionPane.showInputDialog("请输入词汇","word");
String w = JOpitonPane.showInputDialog(null,"请输入词汇","超级词典",JOptionPane.WARNING_MESSAGE);
System.out.println(w//);
}
}
3、安全输入
只有在真实的控制台才可以不报错的使用
public class Dome3{
public static void main(String[] args){
Console con = System.console();
String name = con.readLine("请输入姓名:");
String password = new String(con.readPassword("请输入秘密:"));
System.out.println(name);
System.out.println(password);
}
}
输出
1、控制台输出
public class Dome4{
public static void main(String[] args){
// 输出空行
System.out.println();
System.out.print("\n");// 空行
System.out.print("a"); // a 不换行
System.out.print("b"); // b
System.out.println("java") // java
System.err.println("hello error message"); // 红色字符串
}
}
2、对话框输出
public class Dome5{
public static void main(String[] args){
JOptionPane.showMessageDialog(null,"hello wrold");
JOptionPane.showMessageDialog(null,"122","showuser",JOptionPane.ERROW_MESSAGE);
}
}
3、文件输出 将内容输出到某个指定文件中
public class Dome6{
public static void main(String[] args){
// 默认会覆盖文件
PrintWriter out = new PrintWriter("d:/user.log");
// 将日期输出到文件中
out.printf("今日日期:%tF %<tT %<tA %n",System.currentTimeMillis());
//关闭文件
out.close();
}
}
// 追加到文件
public class Dome7{
public static void main(String[] args){
// true 代表追加到文件
PrintWriter out = new PrintWriter(new FileOutputStream("d:/user.log",true));
// 将日期输出到文件中
out.printf("今日日期:%tF %<tT %<tA %n",System.currentTimeMillis());
//关闭文件
out.close();
}
}