stringindexoutofbounds与货币转换器java程序
我很难看到摘要。我应该通过添加一个对象数组来修改以前的Java赋值。在循环中,实例化每个单独的对象。确保用户不能继续添加超出数组大小的其他外部转换。 用户从菜单中选择退出后,提示用户是否要显示摘要报告。如果选择“Y”,则使用对象数组显示以下报告:stringindexoutofbounds与货币转换器java程序,java,Java,我很难看到摘要。我应该通过添加一个对象数组来修改以前的Java赋值。在循环中,实例化每个单独的对象。确保用户不能继续添加超出数组大小的其他外部转换。 用户从菜单中选择退出后,提示用户是否要显示摘要报告。如果选择“Y”,则使用对象数组显示以下报告: Item Conversion Dollars Amount 1 Japanese Yen 100.00 32,000.00 2 Mexican Peso 400.
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
位于java.lang.String.charAt(String.java:658)
在Lab8.main(Lab8.java:43)
我的代码:
import java.util.Scanner;
导入java.text.DecimalFormat;
公共类Lab8
{
公共静态void main(字符串[]args)
{
最终int最大值=10;
字符串a;
字符摘要;
int c=0;
外汇[]外汇=新外汇[Max];
扫描仪键盘=新扫描仪(System.in);
对外开放();
做
{
外汇[c]=新外汇();
交换[c].getchoice();
兑换[c]。美元();
交易所[c]。金额();
交换[c].vertical();
System.out.println(“\n”+交换[c]);
C++;
System.out.println(“\n”+”请选择1到4,或选择0退出“+>”\n”);
c=键盘.nextInt();
}
而(c!=0);
System.out.print(“\N是否要转换的摘要?(Y/N):”;
a=键盘.nextLine();
汇总=a.charAt(0);
summary=字符.toUpperCase(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
我看了第43行,它是这一行:summary=a.charAt(0)
但我不确定这有什么问题,有人能指出吗?谢谢。问题不完全在于那一行,而在于前一行的最后一行。 您已使用以下方法阅读您的
int
:
c= Keyboard.nextInt();
如果您看到方法的文档,它将从用户输入中读取下一个标记。因此,当您传递一个整数值时,键盘将不会读取末端的换行符,该换行符也是您按下enter
后传递的。键盘将不会读取该换行符。nextInt
,然后将其保留下来供以下人员读取:-
a = Keyboard.nextLine();
在退出时退出。因此,基本上,这条语句是通过prevoius键盘读取剩余的换行符。nextInt
调用,因此a
包含一个空的字符串,最后是一个换行符。因此,您将得到异常
解决方法:-
您可以在此语句之前启动一个空的键盘.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();
或者,另一种方法是使用键盘.nextLine
也可以读取整数值。然后使用integer.parseInt
方法将其转换为整数。但是要小心,您必须进行一些异常处理。因此,如果您仍然需要学习异常处理,那么您可以使用第一种方法。因此,在您的do while
中,您可以这样做:-
try {
c = Integer.parseInt(Keyboard.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
这是一个普遍的问题。使用c=Keyboard.nextInt()时代码>,它读取int
。如果在此语句中按下了返回键,则a=Keyboard.nextLine()
将从输入缓冲区中的上一条语句中读取一个空字符串作为SUVE
您有两个选择:
添加一个额外的Keyboard.nextLine()
在读取a
asa=Keyboard.nextLine()之前清除缓冲区代码>
如果您想进行完全校对,以避免在阅读空行时出现问题(使用按回车键而不输入日期),请按如下所示进行while循环:
a = "";
while(a.length() <1){
a = Keyboard.nextLine();
}
a=”“;
而(a.length()1
,当它从循环中出来时。使用真正的输入,它不会进行任何迭代
这是我的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:通过练习,这变得容易多了……你做得很好……继续做truckin。好吧,你尝试了什么?显然,当你到达第43行时,字符串a
是一个空字符串。你输入了一个空行吗?就像刚才按enter键一样?只是对样式的一个注释:我鼓励你遵循Java代码约定()…特别是:thisIsAVariableName
,和ThisIsAClassName
…我还将MAX\u交换
设置为一个常量,而不是本地MAX
变量。+1表示“不使用nextInt()”…根据我的经验,整个Scanner类都是无用的垃圾,你最好只使用一个BufferedReader。@corlettk。如果你不想对输入进行任何解析,而只是读取它,BufferedReader会更好。但是如果你想做些什么
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;
}
}