1.读取字符串的问题
import java.util.Scanner;
public class Class2 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str="";
int num;
while(true)
{
str = in.nextLine();
num = in.nextInt();
System.out.println(str+num);
}
}
}读第一个循环的时候没问题。读第二个循环就有问题了。
请帮忙解释一下。
按要求不能将nextline改为next,因为是要读一行,而不是一个字串。
import java.util.Scanner;
public class Class2 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str="";
int num;
while(true)
{
str = in.nextLine();
num = in.nextInt();
System.out.println(str+num);
}
}
}读第一个循环的时候没问题。读第二个循环就有问题了。
请帮忙解释一下。
按要求不能将nextline改为next,因为是要读一行,而不是一个字串。
import java.util.Scanner;public class Class2 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str = "";
int num = 0;
while(num != -1) //输入-1就跳出
{
str = in.next();//改了这个地方
num = in.nextInt();
System.out.println(str + num);
}
}
}
结果:
we
12
we12
1
22
122
weee
222
weee222
/**
*
* @author Administrator
*/
public class Main {
/** Creates a new instance of Main */
public Main() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
String str="";
String num="";
while(true)
{
str = in.nextLine();
num = in.nextLine();
int k=0;
do
{
k=0;
abc: for(int i=0;i<num.length();i++)
{
if(num.charAt(i)<'0'||num.charAt(i)>'9')
{
System.out.println("不全是数字,请再次输入:");
k=1;
break abc;
}
}
if(k==1){ num = in.nextLine(); }
}while(k!=0);
System.out.println(str+num);
}
}
}
/**
*
* @author Administrator
*/
public class Main {
/** Creates a new instance of Main */
public Main() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
String str="";
String num="";
while(true)
{
str = in.nextLine();
num = in.nextLine();
int k=0;
do
{
k=0;
abc: for(int i=0;i<num.length();i++)
{
if(num.charAt(i)<'0'||num.charAt(i)>'9')
{
System.out.println("不全是数字,请再次输入:");
k=1;
break abc;
}
}
if(k==1){ num = in.nextLine(); }
}while(k!=0);
System.out.println(str+num);
}
}
}
3樓的錯誤之處在于:當我輸入的字串包涵空格時就錯了。anyway,謝謝。修改一下以適應我的需求。如下:import java.util.Scanner;
public class Class2 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str="";
String strnum="";
int num=0;
int i=0;
while(i<3)
{
str = in.nextLine();
strnum = in.nextLine();
num = Integer.parseInt(strnum);
System.out.println(str+num);
i++;
}
}
}