我正在做一个问题,它希望我得到12位数乘以。如果第一个数字是奇数,则必须乘以1,否则数字乘以3.我的程序正在运行。但是,编码很长。请问是否有其他方法?
import java.util.Scanner;
public class ass2a
{
public static void main(String []args)
{
Scanner reader = new Scanner(System.in);
String input,b;
long checked;
System.out.print("Please enter the 12 digit:");
input = reader.nextLine();
long one,two,three,four,five,six,seven,eight,nine,ten,eleven,twevle;
checked =Long.parseLong(input);
one= checked / 100000000000L;
two = (checked % 100000000000L)/10000000000L;
three =(checked % 10000000000L)/ 1000000000L;
System.out.println(one);
System.out.println(two);
System.out.println(three);
if((input.length() < 12) || (input.length() > 12))
{
System.out.println("The entered digits is not equal to 12.");
System.exit(0);
}
else
{
System.out.println("Calculating...");
}
if (one % 2 ==0)
{
one = one * 1;
}
else
{
one = one * 3;
System.out.println("one is "+one);
}
if (two % 2 ==0)
{
two = two * 1;
}
else
{
two = two * 3;
System.out.println("two is "+two);
}
if (three % 2 ==0)
{
three = three * 1;
}
else
{
three = three * 3;
System.out.println("three is "+three);
}
System.out.println(one);
System.out.println(two);
System.out.println(three);
long sum = one +two+three;
System.out.println(sum);
}
}
答案 0 :(得分:0)
您可以将值存储在长度为12的数组中,而不是创建单个变量,并迭代该数组:
long[] digits = new long[12];
// Add the input to the array
...
for(int i=0;i<digits.length;i++){
if(digits[i]%2==0){
digits[i] *= 3;
}
}
这不是完整的代码,只是一个让您入门的示例。您可以阅读Java arrays。