我正在创建一些项目,用于将小数转换为二进制和返回。我明白了: 此行有多个标记
Syntax error on token ";", Identifier expected
Syntax error on token ".", @ expected after
涉及我的第一个System.out.println()
方法。为什么这不能编译?
package numbers;
import java.util.Scanner;
class DecimalBinaryWork {
DecimalBinaryWork() {
}
String number = "-1";
Scanner scan = new Scanner(System.in);
System.out.println("Enter in type: binary is 0 or decimal which is 10\n");
number = scan.next();
if (number != "0" && number != "10") {
System.out.println("Error: Enter in 0 for binary or 10 for decimal. Try again");
number = scan.next();
}
else if (number == "-1") {
System.out.println("Enter in some type please");
}
else {
convert(number);
}
String convert(String aString) {
//fill in later
}
}
答案 0 :(得分:0)
您的代码不在函数中。看起来你试图创建一个构造函数,但没有将代码分成单独的函数
尝试:
class DecimalBinaryWork {
public DecimalBinaryWork() {
}
public static void main(String[] args) {
String number = "-1";
Scanner scan = new Scanner(System.in);
System.out.println("Enter in type: binary is 0 or decimal which is 10\n");
number = scan.next();
if (number != "0" && number != "10") {
System.out.println("Error: Enter in 0 for binary or 10 for decimal. Try again");
number = scan.next();
}
else if (number == "-1") {
System.out.println("Enter in some type please");
}
else {
// convert(number);
}
}
public String convert(String aString) {
return null;
// fill in later
}
}
答案 1 :(得分:0)
你可能想在main方法中编写逻辑。
package com.test;
import java.util.Scanner;
class DecimalBinaryWork {
DecimalBinaryWork() {
}
private static String number = "-1";
public static void main(String[] str) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter in type: binary is 0 or decimal which is 10\n");
number = scan.next();
if (number != "0" && number != "10") {
System.out.println("Error: Enter in 0 for binary or 10 for decimal. Try again");
number = scan.next();
} else if (number == "-1") {
System.out.println("Enter in some type please");
} else {
convert(number);
}
}
private static String convert(String aString) {
// fill in later
}
}
答案 2 :(得分:0)
我会为你的班级创建一个独立的功能来完成你的逻辑。您可以将逻辑放入main中,也可以为该对象创建一个方法,为您的逻辑调用方法,如下所示:
public void DetermineDecimalBinaryWork()
{
String number = "";
Scanner scan = new Scanner(System.in);
//ask for input until you get a valid response
do {
System.out.println("Enter in type: binary is 0 or decimal which is 10\n");
number = scan.nextLine();
if(!number.equals("0") && !number.equals("10"))
System.out.println("Error: Invalid Input! Try again");
} while (!number.equals("0") && !number.equals("10"));
if (number.equals("-1")) {
System.out.println("Enter in some type please");
}
else {
convert(number);
}
}
如何将函数与对象一起使用的示例
public static void main(String[] args) {
DecimalBinaryWork worker = new DecimalBinaryWork();
worker.DetermineDecimalBinaryWork();
}
答案 3 :(得分:0)
您的System.out.println
来电不在方法中。在方法之外但在类体内部,您可以做的只是声明字段和方法,并且方法之外的前一行位置被解释为声明并初始化名为scan
的字段。 println
语句既不是赋值也不是声明,因此它是语法错误。将代码放入方法中,例如main
。