stringindexoutofbounds with currency converter java program

时间:2012-11-03 04:36:23

标签: java

我没有显示摘要的问题。我应该通过添加一个对象数组来修改以前的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结束转换并让它询问我是否要查看摘要。此错误显示:

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

我的代码:

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);

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

3 个答案:

答案 0 :(得分:1)

问题不在于该行,而在于前一行的最后一行。 您已阅读int使用: -

c= Keyboard.nextInt();

如果您看到Scanner#nextInt方法的文档,它会从用户输入中读取下一个标记。因此,当您传递一个整数值时,linefeed不会读取由于您按enter而传递的末尾的Keyboard.nextInt,然后剩下的就是剩余的a = Keyboard.nextLine(); 阅读: -

while
Keyboard.nextInt退出后

。所以,基本上这句话是通过prevoius a调用读取剩余的换行符,因此empty包含newline字符串,最后有Exception。因此你得到了Keyboard.nextLine

解决方法: -

您可以在此语句之前触发空linefeed,这将使用 // 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(); 作为其输入,以便您的下一个用户输入在它之后开始。

Keyboard.nextLine

或者,另一种方式是您也可以使用Integer.parseInt来读取整数值。然后使用Exception Handling方法将其转换为整数。但要小心,你必须做一些异常处理。因此,如果您仍然要研究do-while,那么您可以采用第一种方式。因此,在try { c = Integer.parseInt(Keyboard.nextLine()); } catch (NumberFormatException e) { e.printStackTrace(); } 内,你可以这样做: -

{{1}}

答案 1 :(得分:1)

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

您有两种选择:

  1. 在阅读Keyboard.nextLine(); a

  2. 之前,添加额外的a = Keyboard.nextLine();来清理缓冲区
  3. 如果你想让它完全证明以避免在读取空行时出现问题(使用按回车键而不输入日期),然后按如下所示放置一个while循环:

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

    a出现循环时,这将确保string length >1有{{1}}。使用真正的输入,它不会进行任何迭代。

答案 2 :(得分:0)

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

您可以从我的控制台课程中挖掘出您需要的方法,直接将它们放在Lab8课程中......但我会鼓励您习惯于分离问题&#34;通过创建自己的键盘来快速进入不同的班级。 class,作为我的控制台的简化版本。

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:通过练习可以轻松实现......你进展顺利......只需继续使用卡车。