1

我无法显示摘要。我应该通过添加对象数组来修改以前的 Java 分配。在循环中,实例化每个单独的对象。确保用户不能继续添加超出数组大小的另一个外部转换。用户从菜单中选择退出后,提示用户是否要显示摘要报告。如果他们选择“Y”,则使用您的对象数组,显示以下报告:

Item     Conversion       Dollars     Amount  
 1       Japanese Yen     100.00    32,000.00   
 2       Mexican Peso     400.00    56,000.00  
 3       Canadian Dollar  100.00     156.00

等等

转化次数 = 3

编译时没有错误..但是当我运行程序时它很好,直到我点击 0 结束转换并让它询问我是否想查看摘要。此错误显示:

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:Lab8.main(Lab8.java:43) 的 java.lang.String.charAt(String.java:658) 的 0

我的代码:

import java.util.Scanner;
import java.text.DecimalFormat;

public class Lab8
{
    public static void main(String[] args)
    {
        final int Max = 10;
        String a;
        char summary;
        int c = 0;
      Foreign[] Exchange = new Foreign[Max];
      Scanner Keyboard = new Scanner(System.in);

      Foreign.opening();

        do
        {
         Exchange[c] = new Foreign();
           Exchange[c].getchoice();
         Exchange[c].dollars();
         Exchange[c].amount();
         Exchange[c].vertical();
         System.out.println("\n" + Exchange[c]);
         c++;

  System.out.println("\n" + "Please select 1 through 4, or 0 to quit" + >"\n");
         c= Keyboard.nextInt();

        }
          while (c != 0);


        System.out.print("\nWould you like a summary of your conversions? (Y/N): ");
              a = Keyboard.nextLine();
              summary = a.charAt(0);
              summary = Character.toUpperCase(summary);

      if (summary == 'Y')
              {
      System.out.println("\nCountry\t\tRate\t\tDollars\t\tAmount");
                 System.out.println("========\t\t=======\t\t=======\t\t=========");
        for (int i=0; i < Exchange.length; i++)
        System.out.println(Exchange[i]);

          Foreign.counter();
          }
    }
}

我查看了第 43 行及其这一行: summary = a.charAt(0);

但是我不确定它有什么问题,有人可以指出吗?谢谢你。

4

3 回答 3

1

The problem is not exactly with that line, rather with the last line of the previous while. You have read your int using: -

c= Keyboard.nextInt();

If you see the documentation of Scanner#nextInt method, it reads the next token from the user input. So, when you pass an integer value, then the linefeed at the end which is also passed as a result of you pressing enter is not read by Keyboard.nextInt, which is then leftover to be read by: -

a = Keyboard.nextLine();

after the while exits. So, basically this statement is reading the left over linefeed by the prevoius Keyboard.nextInt call, and thus a contains an empty string, with a newline at the end. And hence you are getting that Exception.

Workaround: -

You can fire an empty Keyboard.nextLine before this statement, which will consume the linefeed as its input, so that your next user input starts after it.

    // Your code before this while
} while (c != 0);

Keyboard.nextLine();  // Add this line before the next line

System.out.print("\nWould you like a summary of your conversions? (Y/N): ");
a = Keyboard.nextLine();

Or, another way is that you can use Keyboard.nextLine to read the integer value also. And then convert it to integer using Integer.parseInt method. But be careful, you would have to do some exception handling. So if you still to study about Exception Handling, then you can go with the first way. So, inside your do-while, you can do it like this: -

try {
    c = Integer.parseInt(Keyboard.nextLine());
} catch (NumberFormatException e) {
    e.printStackTrace();
}
于 2012-11-03T04:41:41.890 回答
1

这是常见的问题。当您使用c= Keyboard.nextInt();时,它会读取int. 如果在此语句期间按下了返回键,则将a = Keyboard.nextLine();从输入缓冲区中的前一个语句读取一个空字符串作为 subdue。

你有两个选择:

  1. 在读取为之前添加一个额外Keyboard.nextLine();的清理缓冲区aa = Keyboard.nextLine();

  2. 如果你想让它充分证明以避免读取空行时出现问题(使用按返回键而不输入日期),然后放置一个 while 循环,如下所示:

    a = "";
    while(a.length() <1){
       a = Keyboard.nextLine();
    }
    

    这将确保ahas string length >1,当它退出循环时。有了真正的输入,它就不会进行任何迭代。

于 2012-11-03T05:02:19.377 回答
0

这是我的 Console 类,我用它代替 Scanner 来读取命令行应用程序中的键盘输入。请注意,该类“包装”了 Java 1.6 中引入的标准 java.io.Console。

您可以从我的控制台类中挖掘出您需要的方法,将它们直接放在您的Lab8类中......但我鼓励您通过创建自己的“键盘”类,尽早习惯于“分离关注点”到不同的类中,作为我的控制台的精简版。

package krc.utilz.io;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


/**
 * A static library of helper methods to read keyboard input.
 * <p>
 * <strong>usage:</strong>
 * <code>
 *   import krc.utilz.io.Console;
 *   while ( (score=Console.readInteger("Enter an integer between 0 and 100 (enter to exit) : ", 0, 100, -1)) != -1) { ... }
 * </code>
 */
public abstract class Console
{
  private static final java.io.Console theConsole = System.console();
  static {
    if ( theConsole == null ) {
      System.err.println("krc.utilz.io.Console: No system console!");
      System.exit(2); // 2 traditionally means "system error" on unix.
    }
  }
  private static final DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
  private static final DateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss");

  public static String readString(String prompt) {
    String response = readLine(prompt);
    if(response==null) throw new NullPointerException("response cannot be null");
    return response;
  }

  public static String readLine(String prompt) {
    if (!prompt.endsWith(" ")) prompt += " ";
    System.out.print(prompt);
    return theConsole.readLine();
  }

  public static String readString(String prompt, String regex) {
    while(true) {
      String response = readString(prompt);
      if ( response.length() > 0 ) {
        if ( response.matches(regex) ) {
          return response;
        }
      }
      System.out.println("Oops: A match for "+regex+" is required!");
    }
  }


  public static Date readDate(String prompt) {
    while(true) {
      try {
        return dateFormatter.parse(readString(prompt+" (dd/MM/yyyy) : "));
      } catch (java.text.ParseException e) {
        System.out.println("Oops: "+e);
      }
    }
  }

  public static Date readTime(String prompt) {
    while(true) {
      try {
        String response = readWord(prompt+" (HH:mm:ss) : ");
        return timeFormatter.parse(response);
      } catch (java.text.ParseException e) {
        System.out.println("Oops: "+e);
      }
    }
  }

  public static String readWord(String prompt) {
    while(true) {
      String response = readString(prompt);
      if(response.length()>0 && response.indexOf(' ')<0) return response;
      System.out.println("Oops: A single word is required. No spaces.");
    }
  }

  public static String readWordOrNull(String prompt) {
    while(true) {
      String response = readLine(prompt);
      if(response==null||response.length()==0) return null;
      if(response.indexOf(' ')<0 ) return response;
      System.out.println("Oops: A single word is required. No spaces.");
    }
  }

  public static char readChar(String prompt) {
    while ( true ) {
      String response = readString(prompt);
      if ( response.trim().length() == 1 ) {
        return response.trim().charAt(0);
      }
      System.out.println("Oops: A single non-whitespace character is required!");
    }
  }

  public static char readLetter(String prompt) {
    while(true) {
      String response = readString(prompt);
      if ( response.trim().length() == 1 ) {
        char result = response.trim().charAt(0);
        if(Character.isLetter(result)) return result;
      }
      System.out.println("Oops: A single letter is required!");
    }
  }

  public static char readDigit(String prompt) {
    while(true) {
      String response = readString(prompt);
      if ( response.trim().length() == 1 ) {
        char result = response.trim().charAt(0);
        if(Character.isDigit(result)) return result;
      }
      System.out.println("Oops: A single digit is required!");
    }
  }

  public static int readInteger(String prompt) {
    String response = null;
    while(true) {
      try {
        response = readString(prompt);
        if ( response.length()>0 ) {
          return Integer.parseInt(response);
        }
        System.out.println("An integer is required.");
      } catch (NumberFormatException e) {
        System.out.println("Oops \""+response+"\" cannot be interpreted as 32-bit signed integer!");
      }
    }
  }

  public static int readInteger(String prompt, int lowerBound, int upperBound) {
    int result = 0;
    while(true) {
      result = readInteger(prompt);
      if ( result>=lowerBound && result<=upperBound ) break;
      System.out.println("An integer between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
    }
    return(result);
  }

  public static int readInteger(String prompt, int defaultValue) {
    String response = null;
    while(true) {
      try {
        response = readString(prompt);
        return response.trim().length()>0 ? Integer.parseInt(response) : defaultValue;
      } catch (NumberFormatException e) {
        System.out.println("Oops \""+response+"\" cannot be interpreted as 32-bit signed integer!");
      }
    }
  }

  public static int readInteger(String prompt, int lowerBound, int upperBound, int defaultValue) {
    int result = 0;
    while(true) {
      result = readInteger(prompt, defaultValue);
      if ( result==defaultValue || result>=lowerBound && result<=upperBound ) break;
      System.out.println("An integer between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
    }
    return(result);
  }

  public static double readDouble(String fmt, Object... args) {
    String response = null;
    while(true) {
      try {
        response = System.console().readLine(fmt, args);
        if ( response!=null && response.length()>0 ) {
          return Double.parseDouble(response);
        }
        System.out.println("A number is required.");
      } catch (NumberFormatException e) {
        System.out.println("\""+response+"\" cannot be interpreted as a number!");
      }
    }
  }

  public static double readDouble(String prompt, double lowerBound, double upperBound) {
    while(true) {
      double result = readDouble(prompt);
      if ( result>=lowerBound && result<=upperBound ) {
        return(result);
      }
      System.out.println("A number between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
    }
  }

  public static boolean readBoolean(String prompt) {
    String response = readString(prompt+" (y/N) : ");
    return response.trim().equalsIgnoreCase("Y");
  }

  public static java.io.Console systemConsole() {
    return theConsole;
  }

}

干杯。基思。

PS:通过练习,这会变得容易得多……你进展顺利……继续加油吧。

于 2012-11-03T05:38:33.530 回答