我必须创建一个与用户界面交互的程序,该用户界面要求用户输入数字和基数以转换为二进制,十六进制或八进制。我制作了一个有效的程序但是当用户输入" 0 0"时,假设终止并结束程序。另一方面,我的程序不会这样做,但继续进行while循环。
以下是代码:
import java.util.*; //for Scanner
public class BaseConversionApp {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String combo = numbers(console);
while(combo != "0 0") {
if(combo.length() > 0) { //breaks the string into integers to do math to it
Scanner s = new Scanner(combo);
int count = s.nextInt();
int countSecond = s.nextInt();
s.close();
conversion(count,countSecond);
System.out.println();
//now if it goes 0 0 or
String again = numbers(console);
// conversion(count,countSecond);
}
}
//prompts the user for two numbers and checks if the bases are 16, 8, 2.
public static String numbers(Scanner console) {
String combination = "";
String nothing = "0 0";
System.out.print("Enter an integer and the new base: ");
int integer = console.nextInt();
int base = console.nextInt();
if(base == 16 || base == 2 || base == 8) {
combination = integer + " " + base;
return combination;
} else if (base == 0 && integer == 0){
System.out.println("Good bye!");
return nothing;
} else {
System.out.println("Sorry, that is an invalid base. Please enter 2, 8, or 16
only.");
}
return "";
}
//converts the integers into binary, hexa, or octo.
public static void conversion (int integer, int base) {
//takes cares of the special case if the user wants to know hexidecimal
if(base <= 16) {
String calculations = Integer.toString(integer, base);
if(integer > 0 && base > 0) {
System.out.println(integer + " in binary -> " + Integer.toString(integer,
base));
}
}
}
}
答案 0 :(得分:1)
您无法比较这样的字符串,您必须使用String
对象的equals()
方法。所以,你应该:
while(!"0 0".equals(combo)) {
...
}
请注意,我已将常量"0 0"
置于首位 - 这可以保护您免受combo
null
!combo.equals("0 0")
的攻击。否则,您有null
,如果组合为NullPointerException
,当您尝试在{{1}上拨打equals()
时,您将获得null
}值。
答案 1 :(得分:0)
请尝试使用此代码。你的看起来很复杂。顺便说一下,你的代码适合我。
import java.util.Scanner;
public class NewClass {
static Scanner inp = new Scanner(System.in);
static String line1 = "";
static String line2 = "";
static String exit = "exit";
public static void main(String[] args) {
System.out.println("Enter int first and then base...");
System.out
.println("Enter the word exit to exit!");
while (true) {
line1 = inp.next();
if (line1.equalsIgnoreCase(exit)) {
break;
}
line2 = inp.next();
try {
conversion(Integer.parseInt(line1), Integer.parseInt(line2));
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
System.out.println("Bye...");
}
public static void conversion(int integer, int base) {
// takes cares of the special case if the user wants to know hexadecimal
if (base <= 16) {
String calculations = Integer.toString(integer, base);
if (integer > 0 && base > 0) {
System.out.println(integer + " in binary -> "
+ Integer.toString(integer, base));
}
}
}
}