В моей домашней работе BigInteger есть три фрагмента кода, которые требуют от нас, как следует из названия, сохранять целые числа экстремального размера в связанных списках при вводе строки.
Если задана строка«0054321» результирующий связанный список будет хранить 1-> 2-> 3-> 4-> 5 в позиционном порядке, без учета незначительных цифр.
Но когда я пытаюсь пройти через строку, я пытаюсьувеличивайте numDigits на 1 каждый раз, когда я нахожу значащую цифру.
BigInteger.java (код, над которым я сейчас работаю)
package bigint;
import sun.security.x509.InvalidityDateExtension;
public class BigInteger {
boolean negative;
int numDigits;
DigitNode front;
public BigInteger() {
negative = false;
numDigits = 0;
front = null;
}
public static BigInteger parse(String integer)
throws IllegalArgumentException {
int a = 0;
int b = 0;
this.front = new DigitNode(1, null);
int length = integer.length();
while (length > 0 && a <= length) {
if (integer.charAt(a) == '-') {
this.negative = true;
a++;
}
if (integer.charAt(a) == ' ' && this.numDigits == 0) {
a++;
}
if (integer.charAt(a) == ' ' && this.numDigits == 0) {
a++;
continue;
}
if (Character.isDigit(integer.charAt(a))) {
if(integer.charAt(a) == ' ' && this.numDigits == 0) {
a++;
continue;
}
this.numDigits = this.numDigits + 1;
}
/* IMPLEMENT THIS METHOD */
}
// following line is a placeholder for compilation
return null;
}
DigitNode.java (класс, который инкапсулирует связанный список, НЕ РАЗРЕШЕНО ДЛЯ ЭТОГО РЕДАКТИРОВАНИЯ)
package bigint;
public class DigitNode {
int digit;
DigitNode next;
DigitNode(int digit, DigitNode next) {
this.digit = digit;
this.next = next;
}
public String toString() {
return digit + "";
}
}
BigTest.java (класс тестера, который проверяет, является ли слово метод синтаксического анализа / добавления / умножения, НЕ РАЗРЕШЕНО НА ЭТО РЕДАКТИРОВАТЬ)
package bigint;
import java.io.IOException;
import java.util.Scanner;
public class BigTest {
static Scanner sc;
public static void parse()
throws IOException {
System.out.print("\tEnter integer => ");
String integer = sc.nextLine();
try {
BigInteger bigInteger = BigInteger.parse(integer);
System.out.println("\t\tValue = " + bigInteger);
} catch (IllegalArgumentException e) {
System.out.println("\t\tIncorrect Format");
}
}
public static void add()
throws IOException {
System.out.print("\tEnter first integer => ");
String integer = sc.nextLine();
BigInteger firstBigInteger = BigInteger.parse(integer);
System.out.print("\tEnter second integer => ");
integer = sc.nextLine();
BigInteger secondBigInteger = BigInteger.parse(integer);
BigInteger result = BigInteger.add(firstBigInteger,secondBigInteger);
System.out.println("\t\tSum: " + result);
}
public static void multiply()
throws IOException {
System.out.print("\tEnter first integer => ");
String integer = sc.nextLine();
BigInteger firstBigInteger = BigInteger.parse(integer);
System.out.print("\tEnter second integer => ");
integer = sc.nextLine();
BigInteger secondBigInteger = BigInteger.parse(integer);
BigInteger result = BigInteger.multiply(firstBigInteger,secondBigInteger);
System.out.println("\t\tProduct: " + result);
}
public static void main(String[] args)
throws IOException {
// TODO Auto-generated method stub
sc = new Scanner(System.in);
char choice;
while ((choice = getChoice()) != 'q') {
switch (choice) {
case 'p' : parse(); break;
case 'a' : add(); break;
case 'm' : multiply(); break;
default: System.out.println("Incorrect choice");
}
}
}
private static char getChoice() {
System.out.print("\n(p)arse, (a)dd, (m)ultiply, or (q)uit? => ");
String in = sc.nextLine();
char choice;
if (in == null || in.length() == 0) {
choice = ' ';
} else {
choice = in.toLowerCase().charAt(0);
}
return choice;
}
}
Однако я получаю ошибки:
java: нестатическая переменная, на которую нельзя ссылаться из статического контекста,
Для любых this.numDigits, this.front или this.negative.
Всякий раз, когда я пытаюсь увеличитьnumDigits или измените значение целого числа на положительное, так бывает.Кто-нибудь, пожалуйста, помогите, Data Structures действительно пинает меня прямо сейчас.