java吧 关注:1,261,245贴子:12,757,622
  • 4回复贴,共1

小白求助关于 java 里scanner的问题

只看楼主收藏回复

前两周的LAB课 没有去上 导致现在很多东西都不懂 希望大神们能指点迷津


IP属地:吉林1楼2015-08-16 17:12回复
    下面是我的 代码
    import java.util.Scanner;
    public class BookTest {
    public static void main(String args[]){
    Scanner keyboard = new Scanner(System.in);
    int n;
    System.out.println("How many books do you want to input");
    n = keyboard.nextInt();
    Book[] books = new Book[n];
    for(int i = 0; i < n; i++){
    books[i] = new Book();
    System.out.println("Please enter the title for book "+(i+1)+" :");
    books[i].title = keyboard.nextLine();//这里用nextline 每次运行都会被跳过 如果只用next 就不能输入类似New York 这种带空格的string
    System.out.println("Please enter the author name");
    books[i].author = keyboard.nextLine();
    do{
    System.out.println("please enter the number of pages");
    books[i].numberOfPadge = keyboard.nextInt();
    }while(books[i].numberOfPadge < 1);
    }
    System.out.println("Book titles:");
    for (int i = 0; i < n; i++){
    System.out.println((i+1)+". "+books[i].title);
    }
    }
    }


    IP属地:吉林2楼2015-08-16 17:12
    回复
      2025-05-26 02:55:41
      广告
      当然着前面有一个 book的 class, 里面也就只有 String title, String author , int Pagenumber。


      IP属地:吉林3楼2015-08-16 17:14
      回复
        请问 大神们 有什么解决方法能在用了 System.out.println方法之后扫描带有空格的字符串


        IP属地:吉林4楼2015-08-16 17:17
        回复
          nextLine会接收‘\n’换行符(虽然不会显示),和nextDouble,nextInt等一起使用的时候会接收到上一个输入的换行符。所以你在System.out.println("Please enter the title for book "+(i+1)+" :");后面加上 keyboard.nexLine(); 先把那个换行符跳过就好了


          5楼2015-08-16 18:33
          回复