【问题标题】:java programming (convert from integer to string)java编程(从整数转换为字符串)
【发布时间】:2015-02-08 21:06:30
【问题描述】:

我正在尝试从整数转换为字符串以读取字符串中的数字序列。每次输入必须是一个字符串,而不是一个整数。将存储在 arraylist 中的数字不应是整数,而是字符串。

//wbin

//ow

int 计数 = 0; 整数 = 0;

最终 int SENTINEL = 0;

int 分数; `

int sum;
Scanner scan = new Scanner(System in);
ArrayList list = new Array();
System.out.println("Enter your digits");
System.out.println("Enter 0 to calculate");
score = scan.nextint();
while ( score !=SENTINEL)
{ total  = score + total;
list.add(score);
count++;
System.out.println("next number");
score = scan.nextint();
}
if (count != 0)
{
DecimalFormat oneDecimalPlace = new DecimalFormat( "##.0" );
System.out.println("\nYour Average is "                         
+ oneDecimalPlace.format( (double) ( total / count) ) );        
System.out.println("Your Total is " + total);




for (int i = list.size()-1; i >= 0; i--)
System.out.println(list.get(i));
}
else
System.out.println( "\nNo digits were entered" );               

【问题讨论】:

  • 请缩进你的代码并删掉与问题无关的代码。

标签: java arrays string arraylist integer


【解决方案1】:
ArrayList list = new Array();

为什么不使用字符串的 ArrayList?

ArrayList<String> list = new ArrayList<>();

-

score = scan.nextint();

你为什么不要求下一行而不是下一个 int?

score = scan.nextLine();

这可以解决您的问题,但是,如果您要对这些数字进行算术运算,为什么首先要将它们存储为字符串?当您应该将分数加到总分时,您最终会连接字符串。

【讨论】:

    【解决方案2】:

    字符串 s = Integer.toString(n);或字符串 s = "" + n; 此代码将为您提供整数到字符串的转换。

    【讨论】:

      猜你喜欢
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 2011-07-01
      • 2023-03-13
      • 2014-09-19
      • 2018-08-04
      相关资源
      最近更新 更多