结果为
请输入长度为6的字符串:
abc
请输入长度为6的字符串:
abcdef
程序退出,你输入了:abcdef
先看截图:
参考如下:
import java.util.Scanner;
/**
* @author huazie
* @version 2.0.0
* @since 2.0.0
*/
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input;
boolean isValid = false;
do {
System.out.println("请输入长度为6的字符串:");
input = scanner.nextLine();
if (null != input && input.length() == 6) {
isValid = true;
}
} while (!isValid);
System.out.println("程序退出,你输入了:" + input);
}
}
实现描述:建立三个线程A、B、C,分别按照顺序输出十次ABC
首先建立一个方法,按照条件进行输出
class PrintABC{
private int index=0;
public synchronized void print(int n) {
// TODO Auto-generated method stub
try {
while(index!=n) {
wait();
}
if(index==0) {
System.out.print("A");
}else if(index==1) {
System.out.print("B");
}else if(index==2) {
System.out.print("C");
}
index = (n+1)%3;
notifyAll();
}catch(Exception e) {
e.printStackTrace();
}
}
}
其后在建立三个线程,分别调用输出方法
public class AllThread {
private PrintABC printABC;
public AllThread(PrintABC printABC) {
this.printABC=printABC;
}
class ThreadA extends Thread{
@Override
public void run() {
for(int i=0;i<10;i++) {
printABC.print(0);
}
}
}
class ThreadB extends Thread{
@Override
public void run() {
for(int i=0;i<10;i++) {
printABC.print(1);
}
}
}
class ThreadC extends Thread{
@Override
public void run() {
for(int i=0;i<10;i++) {
printABC.print(2);
}
}
}
public static void main(String[] args) {
AllThread allThread = new AllThread(new PrintABC());
allThread.new ThreadA().start();
allThread.new ThreadB().start();
allThread.new ThreadC().start();
}
}
结果展示
要编写一个控制台程序,在用户输入字符串时,只接受长度为6的字符串,如果用户输入的字符串长度不等于6,则要求用户重新输入,可以按照以下步骤来完成:
创建一个 Scanner 对象,通过控制台输入获取用户的字符串。
使用一个 while 循环来接受用户输入,并检查字符串长度是否为 6,如果不是则提示用户重新输入。
如果用户输入的字符串长度为 6,则退出循环,在控制台输出用户输入的字符串,程序结束。
具体代码实现如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = "";
while (true) {
System.out.print("请输入长度为6的字符串:");
input = sc.nextLine();
if (input.length() != 6) {
System.out.println("输入有误,请重新输入!");
} else {
System.out.println("输入的字符串为:" + input);
break;
}
}
}
}