如何在java上打印每个整数的第2位到最后一位的总和?
(因此,将打印8,因为1 + 3 + 4为8,并且将在3453 + 65324 + 354之后打印35)在以下程序中: *不使用if语句* < / p>
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int num1;
int num2;
int num3;
int sumSecToLast;
System.out.print("Please write an integer: ");
num1 = scan.nextInt();
System.out.print("Please write an integer: ");
num2 = scan.nextInt();
System.out.print("Please write an integer: ");
num3 = scan.nextInt();
sumSecToLast = (num1/10) % 10 + (num2/10) % 10 + (num3/10) % 10;
System.out.print((num1/10) % 10 + " + " + (num2/10) % 10 + " + " + (num3/10) % 10 + " = " + sumSecToLast);
}//main
}//Pr6
答案 0 :(得分:0)
一旦您扫描了所有整数:
//In main method:
int secLast1 = Pr6.getSecLastDigit(num1);
int secLast2 = Pr6.getSecLastDigit(num2);
int secLast3 = Pr6.getSecLastDigit(num3);
int sum = secLast1 + secLast2 + secLast3;
System.out.println(secLast1 + " + " + secLast2 + " + " + secLast3 + " = " + sum);
您还想创建其他方法:
private static int getSecLastDigit(int num) {
return (num / 10) % 10;
}
答案 1 :(得分:0)
我将如何做到这一点。根据您对if
语句的定义,这可能不适合您(剧透)。
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int total = 0;
String num1, num2, num3;
System.out.print("Please write an integer: ");
num1 = scan.nextLine(); // rather than taking an integer this takes a String because it is easier to extract a single element.
... // get the other numbers
for (int i = 1; i < num1.length(); i++){
total += Character.getNumericValue(num1.charAt(i)); // adds each number to the total
}
... // do this for the other Strings (or use another loop for with a String[])
System.out.println(total);
}//main
}//Pr6
为了使这更简洁,我高度建议使用String[]
而不是3个不同的变量。另外,我假设for
循环不算作if
语句。但是我意识到,由于boolean
检查,它们可能被认为与您目前的情况太相似。我希望这有帮助! :)
答案 2 :(得分:0)
很抱歉给您带来不便。我的问题被误解了。我的意思是我想编写一个代码来查找三个不同整数的第二个到最后一个数字的总和。例如:如果用户输入了15,34和941,在这种情况下,第二个到最后一个数字将是1,3和4.因此,它们的小计将是1 + 3 + 4 = 8。 / p>
我找到答案,我想与大家分享,我还要感谢所有试图提供帮助的人。 谢谢..
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int num1;
int num2;
int num3;
int sumSecToLast;
System.out.print("Please write an integer: ");
num1 = scan.nextInt();
System.out.print("Please write an integer: ");
num2 = scan.nextInt();
System.out.print("Please write an integer: ");
num3 = scan.nextInt();
sumSecToLast = ((num1/10) % 10) + ((num2/10) % 10) + ((num3/10) % 10);
System.out.println("The subtotal of the 2nd to the last digit = " + sumSecToLast);
System.out.println();
}//main
}//Pr6