![](/img/trans.png)
[英]Parameter passed from Java is automatically converted to Octal equivalent in JSP Page
[英]java program that takes a value from user and converts it to its octal equivalent
因此,我正在嘗試構建一個接受用戶輸入的程序,然后如果該輸入介於0和2097151之間,則該程序會將該int轉換為它的八進制等效項,然后在最后顯示它。 我在WORKS下面發布的程序很好,但可能效率不高,我很好奇,並試圖在使用計數器控制重復的while循環中尋求實現相同程序的方法方面尋求幫助。使用,但我不知道該怎么做。
我問自己一個困惑的問題是:如何繼續將數字除以8,繼續將數字的模數除以8,並將該模數存儲到單獨的變量中,以便可以正確地打印出來彼此相鄰? 我不確定如何保持模數直到我的數字達到0並使用while循環跟蹤余數。
為了明確起見,這是學校的作業,並且僅限於while循環,for循環,邏輯運算符和if / if else語句。 我無法使用方法或內置方法來實現所需的最終結果。
import java.util.Scanner;
public class kwatke_OctalConversion {
public static void main(String args[]) {
Scanner input = new Scanner( System.in );
int modulus1, modulus2, modulus3, modulus4, modulus5, modulus6, modulus7;
int smallest=0;
int Largest=2097151;
System.out.println("The purpose of this program is to take a value from the "
+ "user and\n convert it from a base 10 number to a base 8 number and "
+ "display it\n for the user to see the converted octal number\n"
+ "Please enter a non-negative number between 0 and 2097151 to see it's "
+ "octal equivalent: " );
int number = input.nextInt();
if (number<smallest || number>Largest) {
System.out.println ( "UNABLE TO CONVERT" );
} else {
modulus1 = (number % 8); //meat of our program, take number from user,
number /= 8; // take modulus of number, divide by 8, rinse and
modulus2 = (number % 8); // repeat storing the modulus in a differnt var
number /= 8; // each time and continusing to divide the
modulus3 = (number % 8); // leftover number by 8 until it reaches 0,
number /= 8; // storing modulus in a new variable each time.
modulus4 = (number % 8);
number /= 8;
modulus5 = (number % 8);
number /= 8;
modulus6 = (number % 8);
number /= 8;
modulus7 = (number % 8);
System.out.printf("%d%d%d%d%d%d%d\n", modulus7, modulus6, modulus5,
modulus4, modulus3, modulus2, modulus1);
}
}
}
您可以使用 :
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number : ");
int number = input.nextInt();
String result = Integer.toOctalString(number);
這樣行嗎?
int i=0;
int a[] = new int[100];
while (number>0) {
a[i] = number % 8;
number = number / 8;
i++;
}
for(int j=i-1; j>=0; j--) {
System.out.printf("%d", a[j]);
}
如注釋中所建議,您還可以使用遞歸來查找八進制數。 您可以對其進行調整以接受和驗證用戶輸入。
class OctalNumbers
{
static int a[] = new int[100];
static int index = 0;
public static void main (String[] args) throws java.lang.Exception
{
int number = 56;
findOctal(number);
for(int j = index-1; j>=0; j--) {
System.out.printf("%d", a[j]);
}
}
private static void findOctal(int number) {
if(number != 0) {
int rem = number % 8;
a[index] = rem;
number = number / 8;
index++;
findOctal(number);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.