根据作业要求改为java代码

测试帖链接:http://www.cnblogs.com/destinyandfate/p/6606681.html

根据测试所暴露的问题,经过分析为atoi函数转换字符数组会自动将非数字字符作为终止符号,所以对数字字母混合的非法数据失去判断能力

经过修改后的代码:

由于是从c语言改为java代码,故不贴出修改代码清单

package text01;

import java.util.Scanner;

public class Main {

public static double commission(int headphone,int shell,int protector)
{
double back = 0;
float sum = 0;
sum=headphone*80+shell*10+protector*8;
if(sum<1000)
{
back=sum*0.1; //小于1000时所抽取的佣金
}
else if(sum>=1000 && sum<=1800)
{
back=100+(sum-1000)*0.15;//计算1000--1800的佣金
}
else if(sum>=1800)
{
back=220+(sum-1800)*0.2;//1800以上的佣金
}

return back;
}


static int tu(String a)
{
int back;
char a_c[]=a.toCharArray();
int len=a.length();

for(int i=0;i<=len-1;i++) //逐个检查是否为数字,小数点同样不通过
{
if( a_c[i]>'9' || a_c[i]<'0')
{
back=-1;
return back;
}
}

back=Integer.parseInt(a);
return back;

}

public static void main(String[] args) {
int pass=0;//设置初始判断循环是否通过的值
String headphone;
String shell;
String protector;
@SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
int headphone_i = 0;
int shell_i = 0;
int protector_i = 0;
double back;
while(pass==0)
{
System.out.printf("请分别输入三种手机配件的销售情况:\n");
while(pass==0)
{
System.out.printf("请输入耳机的销售数量:(输入exit退出)\n");
headphone=s.next();
if(headphone.equals("exit")==true)
{
System.exit(0);
}
else if(tu(headphone)==-1)
{
System.out.printf("输入的数据不合法,请重新输入!\n");
continue;
}
else
{
headphone_i=tu(headphone);break;
}
}
while(pass==0)
{
System.out.printf("请输入手机外壳的销售数量:\n");
shell=s.next();
if(tu(shell)==-1)
{
System.out.printf("输入的数据不合法,请重新输入!\n");
continue;
}
else
{
shell_i=tu(shell);break;
}
}
while(pass==0)
{
System.out.printf("请输入手机护膜的销售数量:\n");
protector=s.next();
if(tu(protector)==-1)
{
System.out.printf("输入的数据不合法,请重新输入!\n");
continue;
}
else
{
protector_i=tu(protector);break;
}
}
back=commission(headphone_i,shell_i,protector_i);
System.out.println("佣金为:"+back+"\n");
}

}}