Java 如何同时打印所有输出
我给出了一个总数和从输入中提取的字符串 我的代码是:Java 如何同时打印所有输出,java,string,Java,String,我给出了一个总数和从输入中提取的字符串 我的代码是: public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int tot = sc.nextInt(); for(int i=0; i<r; i++){ int L;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int tot = sc.nextInt();
for(int i=0; i<r; i++){
int L;
String str = sc.next();
if(L == str.length()) {
print(str);
}
}
}
private static void print(String str){
System.out.println("String is "+ str);
}
但我想要的是,它首先接受所有输入,然后打印
例:
OutPut : 3
"ABC"
"ABCD"
"ABCDE"
String is ABC
String is ABCD
String is ABCDE
谁能解释一下,帮我修改我的字符串吗
注意:我的想法是把所有的东西都放进堆栈,但又不知道该打印谁。我知道我的结果是因为for循环而来的,但不知道如何从中得出结果将所有文本保存在一个全局变量中
public static void main(String[] args) {
String str="";
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int tot = sc.nextInt();
for(int i=0; i<r; i++){
str += sc.next();
}
print(str);
}
private static void print(String str){
System.out.println("String is "+ str);
}
有一个简单的方法可以做到这一点 在代码中使用StringBuilder,如下所示:
...
StringBuilder sb = new StringBuilder();
for(int i=0; i<r; i++){
String str = sc.next();
sb.append(str);
}
return/print sb.toString();
...
第一件事:将print方法移出for循环,您只需要在收集输入后执行一次,然后使用String对象并附加输入,可能在每次循环迭代后使用新行字符
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tot = sc.nextInt();
String str = "";
for (int i = 0; i < tot; i++) {
str += "String is: ";
str += sc.next();
str += "\n";
}
print(str);
sc.close();
}
private static void print(String str) {
System.out.println(str);
}
我不能在for循环之外使用print方法,因为对于每个字符串 我正在检查一个关于其长度的条件。我更新我的 问题你能再看一下吗 既然你问了这个问题,我已经更新了答案。 希望这能对你有所帮助
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int tot = sc.nextInt();
int counter = 0;//add a counter
String str = "";
for (int i = 0; i < tot; i++)
{
counter++;//increment for for each input
str += "String is: ";
str += sc.next();
str += "\n";
if(counter == tot)//if tot ia equal to total number of intake then print
{
print(str);
}
}
sc.close();
}
private static void print(String str)
{
System.out.println("String is "+ str);
}
其中是print方法??使用字符串[]str数组并添加如下字符串str[i]=sc.next;。在循环调用printstr之后;但将方法的参数更改为字符串数组。然后迭代数组并打印每个值@ΦXocę웃Пepeúpaツ 我更新了我的问题,将字符串生成器或连接操作放入if语句中。我不能在for循环之外使用print方法,因为对于每个字符串,我都要检查一个关于其长度的条件。我更新我的问题。请您再看一看。具体条件是什么?我不能在for循环之外使用print方法,因为对于每个字符串,我都要检查一个关于其长度的条件。我更新我的问题。请你再看一看。在比较之前,你没有初始化L,对不起,我不明白你的意思,你是什么意思?你可以在任何需要的地方使用print谢谢@Gokul让我试试你的答案。
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int tot = sc.nextInt();
int counter = 0;//add a counter
String str = "";
for (int i = 0; i < tot; i++)
{
counter++;//increment for for each input
str += "String is: ";
str += sc.next();
str += "\n";
if(counter == tot)//if tot ia equal to total number of intake then print
{
print(str);
}
}
sc.close();
}
private static void print(String str)
{
System.out.println("String is "+ str);
}