【问题标题】:I need to identify characters in a string using a users input我需要使用用户输入识别字符串中的字符
【发布时间】:2019-10-22 20:40:11
【问题描述】:

例如,如果用户输入字符串“hello world”,他们将被提示输入一个数字。如果用户输入“6”,我想打印“w”

这是我目前的工作,但似乎不起作用

import java.util.Scanner;

public class Test {

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    System.out.print("Enter a string:");

    String str = in.next();

    System.out.print("Enter the index: ");

    Scanner reader = new Scanner(System.in);
    char c = reader.next().charAt(0);

    System.out.print(c);
  }
}

【问题讨论】:

    标签: charat


    【解决方案1】:

    这是代码。你必须使用 nextLine 而不是 next

        import java.util.Scanner;
    
    
        public class Test {
           public static void main(String[] args) {
           Scanner in = new Scanner(System.in);
    
           System.out.print("Enter a string:");
    
    
           String str = in.nextLine();
    
           System.out.print("Enter the index: ");
    
    
           Scanner reader = new Scanner(System.in);
    
           Integer index = Integer.parseInt(reader.nextLine());
           char c = str.charAt(index);
    
           System.out.print(c);
           }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      相关资源
      最近更新 更多