import java.util.Scanner;
public class Digits {
public static void main(String[] args) {
/*
*
count = 1
temp = n
while (temp > 10)
Increment count.
Divide temp by 10.0.
*/
//Assignment: fix this code to print: 1 2 3 (for 123)
//temp = 3426 -> 3 4 2 6
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int count = 1;
int temp = input.nextInt();
while(temp >= 10){
count ;
temp = temp / 10;
System.out.print(temp " ");
}
}
}
需要幫助修復代碼。示例:當您鍵入 123 時,它會變成 1 2 3。
uj5u.com熱心網友回復:
您的代碼每次除以 10,可用于反向列印該值。要向前列印它,您需要更多涉及對數的數學運算。有時候,
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int temp = input.nextInt();
while (temp > 0) {
int p = (int) (Math.log(temp) / Math.log(10));
int v = (int) (temp / Math.pow(10, p));
System.out.print(v " ");
temp -= v * Math.pow(10, p);
}
或者,讀取一行輸入。去掉所有非數字,然后列印由空格分隔的每個字符。喜歡,
String temp = input.nextLine().replaceAll("\\D", "");
System.out.println(temp.replaceAll("(.)", "$1 "));
uj5u.com熱心網友回復:
您的大部分代碼都是正確的,您要做的是除以 10,然后列印出該值——這可能應該是一個模數運算%,以獲取剩余的操作并將其列印出來——但這是一種很好的方式考慮此事。
盡管如此。
您可以只使用一個字串,然后在每個字符上拆分字串
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
// we know that we are going to get some input - so we will just grab it as a String
// whilst we are expecting an int - we will test this later.
// we are doing this as it makes it easier to split the contents of a string
String temp = input.next();
// is this an int? - we will test this first
try {
// if this parsing fails - then it will throw a java.lang.NumberFormat exception
// see the catch block below
int test = Integer.parseInt(temp);
// at this point it is an int no exception was thrown- so let's go
// through and start printing out each character with a space after it
// the temp(which is a string).toCharArray returns a char[] which we
// can just iterate through and set the variable of each iteration to 'c'
for (char c : temp.toCharArray()) {
// now we are going to print out the character with a space after it
System.out.print(c " ");
}
} catch (NumberFormatException ex){
// this is not an int as we got a number format exception...
System.out.println("You did not enter an integer. :(");
}
// be nice and close the resource
input.close();
}
uj5u.com熱心網友回復:
僅回答您的問題,您可以使用此單行代碼。
int test = 123;
System.out.println(String.join(" ", Integer.toString(test).split("")));
輸出是:1 2 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/533897.html
標籤:爪哇蚀循环伪代码
