I've written a code to calculate the no of factors of a given list of elements.
INPUT:
test- no of test cases
num- no of elements in 1 test case
numarr- string in which the values(whose product's factors are to be found) is divide by spaces.
When input is:
3
3
3 5 7
3
2 4 6
2
5 5
Ideally, the output should be
8
10
3
But, Exception is:
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:31)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int test = 0;
Scanner scn = new Scanner(System.in);
if (scn.hasNextLine())
test = scn.nextInt();
int op = 0;
int[] out = new int[test];
while ((test <= 100) && (test > 0)) {
int num = 0;
if (scn.hasNextLine())
num = scn.nextInt();
if (num <= 10) {
String numarr = null;
Scanner sc = new Scanner(System.in);
if (sc.hasNextLine())
numarr = sc.nextLine();
String splitt[] = null;
if (numarr != null)
splitt = numarr.split(" "); <--ERROR!!!
if (splitt.length == num) {
double[] arr = new double[splitt.length];
int i = 0;
while (i < splitt.length) {
arr[i] = Double.parseDouble(splitt[i]);
++i;
}
i = 0;
double prod = 1;
while (i < arr.length) {
prod *= arr[i];
++i;
}
double[] factor = new double[100000];
int value = 0;
pfac(prod, factor);
for (i = 0; (i < factor.length) && (factor[i] != 0); ++i) {
value += 1;
}
out[op] = value;
op++;
}
}
--test;
}
for (int i = 0; i < op; ++i) {
System.out.println(out[i]);
}
}
private static void pfac(double n, double[] factor) {
int pos = 0;
long max = (long) Math.sqrt(n);
for (long i = 1; i <= max; ++i) {
if (n % i == 0) {
factor[pos] = i;
pos += 1;
if (n / i != i) {
factor[pos] = n / i;
pos += 1;
}
}
}
}
}
Think about what your code is doing:
if(numarr!=null)
splitt=numarr.split(" ");
if(splitt.length==num)
{
...
}
If numarr is null you aren't doing the split, which means splitt is still null when you start using it.
Put the whole thing in {}.
if(numarr!=null)
{
splitt=numarr.split(" ");
if(splitt.length==num)
{
...
}
}
The line you indicate can't throw an NPE, since the preceding if statement protects that from ever happening. In the cases where numarr is null however, you will get an NPE on the next row:
if (splitt.length==num)
I would guess this is a case of you thinking the if statement is covering the next row too. It is good practice to always use curly braces in your if statements, to clearly mark where they end.
Related
I have successfully compiled this java program (which generates 100 random numbers between 0 and 25, puts them in an array, and sorts them into two different arrays based on whether each is even or odd), although it does not run. I suspect I have made a mistake with one of the while loops, although I don't know for sure. Also, I struggled to get the code in properly formatted in the question, so the tabs are somewhat off, but it is still mostly legible. Here is the .java text:
public class Assignment8
{
public static void main( String [] args )
{
int storage [] = new int[100];
int j = 0;
while ( storage.length < 100 ) {
int testVariable = 0 + (int) (Math.random() * ((25 - 0) + 1));
storage[j] = testVariable;
j++;
}
int oddArray[] = OddNumbers( storage );
int evenArray[] = EvenNumbers( storage );
int currentNumber = 0;
System.out.println( "The odd numbers are: " + "\n" );
while ( currentNumber <= 99 ) {
System.out.println( oddArray[currentNumber] + "\n" );
currentNumber++;
}
System.out.println( "\n" + "The even numbers are: " + "\n" );
currentNumber = 0;
while ( currentNumber <= 99 ) {
System.out.println( evenArray[currentNumber] + "\n" );
currentNumber++;
}
}
public static int[] OddNumbers( int storage[] )
{
int currentNumber = 0;
int currentValue = storage[currentNumber];
int oddArray[] = new int[100];
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 != 0 ) {
oddArray[currentNumber] = currentValue;
} else {
continue;
}
currentNumber++;
}
return oddArray;
}
public static int[] EvenNumbers( int storage[] )
{
int currentNumber = 0;
int currentValue = storage[currentNumber];
int evenArray[] = new int[100];
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 == 0 ) {
evenArray[currentNumber] = currentValue;
} else {
continue;
}
currentNumber++;
}
return evenArray;
}
}
storage.length does not change throughout the program's execution, as the array is already allocated. You first while loop is thus wrong, as 100 is not less than 100, it will never execute. Instead, you could use a simple for loop:
for (int j = 0; j < storage.length; ++j) {
int testVariable = 0 + (int) (Math.random() * ((25 - 0) + 1));
storage[j] = testVariable;
}
although it does not run
Yes it does. It's just that the execution can get stuck in the infinite loops in the OddNumbers and EvenNumbers methods.
Take a closer look at this:
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 != 0 ) {
oddArray[currentNumber] = currentValue;
}
else {
continue;
}
The problem is that when storage[currentNumber] is even,
the program executes the else branch with the continue statement,
and since currentNumber hasn't changed, and so storage[currentNumber] hasn't changed either, it's still even, and the else branch will be executed again, and again, and again, forever. EvenNumber has the same problem too.
Here's a fix for OddNumbers:
public static int[] OddNumbers(int[] storage) {
int[] oddArray = new int[storage.length];
int oddIndex = 0;
for (int num : storage) {
if (num % 2 != 0) {
oddArray[oddIndex++] = num;
}
}
return Arrays.copyOf(oddArray, oddIndex);
}
An extra touch I did in this method is the Arrays.copyOf call,
chopping off the excess elements of the array that would be otherwise 0.
Then when you print the content of this array in main, write like this:
System.out.println("The odd numbers are: " + "\n");
for (int num : oddArray) {
System.out.println(num);
}
Follow the same pattern to fix EvenNumbers.
As #Mureinik pointed out,
the loop in main populating storage is also broken.
And you have several other coding issues,
for example the random number generation is particularly ugly and using an obsolete technique.
The complete improved implementation:
import java.util.Arrays;
import java.util.Random;
public class Assignment8 {
public static void main(String[] args) {
Random random = new Random();
int[] storage = new int[100];
for (int i = 0; i < storage.length; i++) {
storage[i] = random.nextInt(25);
}
System.out.println("The odd numbers are: " + "\n");
int oddArray[] = OddNumbers(storage);
for (int num : oddArray) {
System.out.println(num);
}
System.out.println("\n" + "The even numbers are: " + "\n");
int evenArray[] = EvenNumbers(storage);
for (int num : evenArray) {
System.out.println(num);
}
}
public static int[] OddNumbers(int[] storage) {
int index = 0;
int[] result = new int[storage.length];
for (int num : storage) {
if (num % 2 != 0) {
result[index++] = num;
}
}
return Arrays.copyOf(result, index);
}
public static int[] EvenNumbers(int storage[]) {
int index = 0;
int[] result = new int[storage.length];
for (int num : storage) {
if (num % 2 == 0) {
result[index++] = num;
}
}
return Arrays.copyOf(result, index);
}
}
I have made this program using array concept in java. I am getting Exception as ArrayIndexOutOfBound while trying to generate product.
I made the function generateFNos(int max) to generate factors of the given number. For example a number 6 will have factors 1,2,3,6. Now,i tried to combine the first and the last digit so that the product becomes equal to 6.
I have not used the logic of finding the smallest number in that array right now. I will do it later.
Question is Why i am getting Exception as ArrayIndexOutOfBound? [i couldn't figure out]
Below is my code
public class SmallestNoProduct {
public static void generateFNos(int max) {
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
}
}
smallestNoProduct(ar);
}
public static void smallestNoProduct(int x[]) {
int j[] = new int[x.length];
int p = x.length;
for (int d = 0; d < p / 2;) {
String t = x[d++] + "" + x[p--];
int i = Integer.parseInt(t);
j[d] = i;
}
for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}
}
public static void main(String s[]) {
generateFNos(6);
}
}
****OutputShown****
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
at SmallestNoProduct.main(SmallestNoProduct.java:52)
#Edit
The improved Code using array only.
public class SmallestNoProduct {
public static void generateFNos(int max) {
int s = 0;
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
s++;
}
}
for (int g = 0; g < s; g++) {
System.out.println(ar[g]);
}
smallestNoProduct(ar, s);
}
public static void smallestNoProduct(int x[], int s) {
int j[] = new int[x.length];
int p = s - 1;
for (int d = 0; d < p;) {
String t = x[d++] + "" + x[p--];
System.out.println(t);
int i = Integer.parseInt(t);
j[d] = i;
}
/*for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}*/
}
public static void main(String s[]) {
generateFNos(6);
}
}
Maybe it better:
public class SmallestNoProduct {
public static int smallest(int n) {
int small = n*n;
for(int i = 1; i < Math.sqrt(n); i++) {
if(n%i == 0) {
int temp = Integer.parseInt(""+i+""+n/i);
int temp2 = Integer.parseInt(""+n/i+""+i);
temp = temp2 < temp? temp2: temp;
if(temp < small) {
small = temp;
}
}
}
return small;
}
public static void main(String[] args) {
System.out.println(smallest(6)); //6
System.out.println(smallest(10)); //25
System.out.println(smallest(100)); //205
}
}
Problem lies in this line
String t=x[d++]+""+x[p--];
x[p--] will try to fetch 7th position value, as p is length of array x i.e. 6 which results in ArrayIndexOutOfBound exception. Array index starts from 0, so max position is 5 and not 6.
You can refer this question regarding postfix expression.
Note: I haven't checked your logic, this answer is only to point out the cause of exception.
We are unnecessarily using array here...
below method should work....
public int getSmallerMultiplier(int n)
{
if(n >0 && n <10) // if n is 6
return (1*10+n); // it will be always (1*10+6) - we cannot find smallest number than this
else
{
int number =10;
while(true)
{
//loop throuogh the digits of n and check for their multiplication
number++;
}
}
}
int num = n;
for(i=9;i>1;i--)
{
while(n%d==0)
{
n=n/d;
arr[i++] = d;
}
}
if(num<=9)
arr[i++] = 1;
//printing array in reverse order;
for(j=i-1;j>=0;j--)
system.out.println(arr[j]);
I've been trying to solve this rather easy problem on SPOJ: http://www.spoj.com/problems/HS08PAUL/.
It requires the number of prime numbers (less than n) which can be expressed in the form x^2+y^4 (where x and y are integers) to be found out.
I've whipped up a brute force solution which takes up quite a while for (n ~= 1000000), resulting in a TLE (time limit exceeded) error being thrown by the engine. Here's the source code:
import java.io.*;
import java.util.*;
class HS08PAUL {
public static int[] sieve(int n){
boolean[] prime = new boolean[n+1];
int[] primeNumbers = new int[n];
int index = 0;
Arrays.fill(primeNumbers, 0);
Arrays.fill(prime,true);
prime[0] = false;
prime[1] = false;
int m = (int)Math.sqrt(n);
for(int i = 2; i <= m; i++){
if(prime[i])
for(int k = i*i; k<=n; k+=i)
prime[k] = false;
}
for(int j = 2; j <= n; j++) {
if(prime[j]) {
primeNumbers[index] = j;
index++;
}
}
return primeNumbers;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try{
double numberOfTestCases = in.nextDouble();
while(numberOfTestCases -- > 0) {
int index = 0, y = 0, count = 0;
int num = in.nextInt();
int[] primes = sieve(num);
while(index < num/3 ) {
for(y = 1; y < 57 ; y ++) {
if(Math.ceil(Math.sqrt(primes[index] - Math.pow(y,4))) == Math.floor(Math.sqrt(primes[index] - Math.pow(y,4)))) {
count++;
break;
}
}
index++;
}
System.out.println(count);
}
}
catch(Exception e) {
}
}
}
Is there a way in which I can make this approach work?
P.S.:Please ignore the unruly exception handling.
How many numbers of the form x^2+y^4 are there below 1000000? How many prime numbers are there below 1000000? What do these two numbers tell you about how you should approach the solution?
#isnot2bad's comment is also relevant.
My code tries to implement an algorithm to
take user input for two integer numbers and an operand + or - from the console,
store those numbers digit by digit in an int[50], representing negative ones in ten's complement format,
implement (decimal) digit-by-digit add/subtract operations,
print the result in decimal format without leading zeroes.
However, in my current implementation there are two problems
When adding 99 + 9999, the printed result is 01098 instead of the expected 010098.
When subtracting 99 - 9999, I get an ArrayIndexOutOfBoundsException: 50 instead of the expected result -09900.
import java.util.*;
public class Program9 {
public static String getOperand() {
Scanner scan = new Scanner(System.in);
String stringOfInteger;
System.out.print("Please enter an integer up to 50 numbers: ");
stringOfInteger = scan.nextLine();
return stringOfInteger;
}
public static int[] convert(String operand) {
int[] integer = new int[50];
char ch;
int position = operand.length() - 1;
for (int i = integer.length - 1; i >= 0; i--) {
if (position >= 0)
ch = operand.charAt(position--);
else
ch = 0;
if (ch >= '0' && ch <= '9') {
integer[i] = ch - '0';
} else {
integer[i] = 0;
}
}
return integer;
}
public static int[] add(int[] operand1, int[] operand2) {
int[] result = new int[operand1.length];
int carry = 0;
for (int i = operand1.length - 1; i >= 0; i--) {
result[i] = operand1[i] + operand2[i] + carry;
if (result[i] / 10 == 1) {
result[i] = result[i] % 10;
carry = 1;
} else
carry = 0;
}
return result;
}
public static int[] complement(int[] operand) {
int[] result = new int[operand.length];
for (int i = operand.length - 1; i >= 0; i--)
result[i] = 9 - operand[i];
return result;
}
public static int[] add1(int[] operand) {
int[] result = new int[50];
result[49] = 1;
for (int i = result.length - 2; i >= 0; i--)
result[i] = 0;
return result;
}
public static int[] negate(int[] operand) {
return add(add1(operand), complement(operand));
}
public static void print(int[] result, String operation) {
if (operation.charAt(0) == '+')
System.out.print("The subtotal of the two integer = ");
else if (operation.charAt(0) == '-')
System.out.print("The substraction of the two integers = ");
if (result[0] == 9) {
result = negate(result);
System.out.print("-");
for (int i = 0; i < result.length; i++) {
if (result[i] == 0 && result[i + 1] == 0)
continue;
else
System.out.print(result[i]);
}
} else
for (int i = 0; i < result.length; i++) {
if (result[i] == 0 && result[i + 1] == 0)
continue;
else
System.out.print(result[i]);
}
System.out.println();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] result = new int[50];
String string1 = getOperand();
String string2 = getOperand();
int[] integer1 = convert(string1);
int[] integer2 = convert(string2);
String operation;
System.out.print("Please enter which operation will be used (+ or -): ");
operation = scan.nextLine();
if (operation.charAt(0) == '+')
add(integer1, integer2);
else if (operation.charAt(0) == '-')
integer2 = negate(integer2);
result = add(integer1, integer2);
System.out.println(Arrays.toString(integer1));
System.out.println(Arrays.toString(integer2));
System.out.println(Arrays.toString(add(integer1, integer2)));
print(result, operation);
}
}
Okay, after so much discussion and so many issues with your code I have totally revised your original code because you said you wanted to learn more. Among other improvements I have done the following changes:
Meaninfgul class name
Meaningful method and parameter names
Convert repeated and often used constants like 50 and the array representation of the number 1 (needed for negation) into static final members for clean code reasons (documentation, easy change in one place, meaningful names), runtime optimisation).
Extend the code to permit negative integers as operands
Added validation patterns for user input. E.g. now the maximum number length is checked in order to avoid an array overflow.
Avoid numeric overflows during calculation by making the array bigger than the maximum number of digits permitted for user input (see source code comments)
Add retry loops with error handling for operand and operator input, extract console handling into one parametrised method.
Simplify code by removing unnecessary checks because user input is already validated before converting it into an int[].
Make debug output optional
package de.scrum_master.stackoverflow;
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Pattern;
public class TensComplementArithmetic {
// Print debug messages?
private static final boolean DEBUG = true;
// Maximum length for numbers entered by a user
// (number of digits excluding the optional +/- sign)
private static final int MAX_NUMBER_LENGTH = 50;
// Array must have one additional element for the sign and
// one more to avoid overflows when adding big negative numbers
private static final int ARRAY_LENGTH = MAX_NUMBER_LENGTH + 2;
// Scanner for console input handling
private static final Scanner INPUT_SCANNER = new Scanner(System.in);
// Regex pattern for positive/negative integer number format verification incl. length check
private static final Pattern INTEGER_PATTERN = Pattern.compile("[+-]?[0-9]{1," + MAX_NUMBER_LENGTH + "}");
// Regex pattern for operator verification (currently only "+"/"-" allowed)
private static final Pattern OPERATOR_PATTERN = Pattern.compile("[+-]");
// The number 1 is always needed for converting a 9's into a 10's complement
// during negation, so we define it as a reusable constant
private static final int[] NUMBER_ONE;
static {
// Initialise constant carrying array representation for number 1
NUMBER_ONE = new int[ARRAY_LENGTH];
NUMBER_ONE[ARRAY_LENGTH - 1] = 1;
}
public static String readConsoleInput(String prompt, Pattern validationPattern, String errorMessage) {
String input = null;
while (input == null) {
System.out.print(prompt + ": ");
if (INPUT_SCANNER.hasNext(validationPattern))
input = INPUT_SCANNER.next(validationPattern);
else {
INPUT_SCANNER.nextLine();
System.out.println(errorMessage);
}
}
return input;
}
public static String getOperand(String operandName) {
return readConsoleInput(
"Operand " + operandName,
INTEGER_PATTERN,
"Illegal number format, please enter a positive/negative integer of max. " + MAX_NUMBER_LENGTH + " digits."
);
}
private static String getOperator() {
return readConsoleInput(
"Arithmetical operator (+ or -)",
OPERATOR_PATTERN,
"Unknown operator, try again."
);
}
public static int[] parseInteger(String number) {
char sign = number.charAt(0);
boolean isNegative = sign == '-' ? true : false;
if (isNegative || sign == '+')
number = number.substring(1);
int[] result = new int[ARRAY_LENGTH];
int parsePosition = number.length() - 1;
for (int i = result.length - 1; i >= 0; i--) {
if (parsePosition < 0)
break;
result[i] = number.charAt(parsePosition--) - '0';
}
return isNegative ? negate(result) : result;
}
public static int[] add(int[] operand1, int[] operand2) {
int[] result = new int[ARRAY_LENGTH];
int carry = 0;
for (int i = ARRAY_LENGTH - 1; i >= 0; i--) {
result[i] = operand1[i] + operand2[i] + carry;
if (result[i] >= 10) {
result[i] = result[i] % 10;
carry = 1;
} else
carry = 0;
}
return result;
}
public static int[] complement(int[] operand) {
int[] result = new int[ARRAY_LENGTH];
for (int i = operand.length - 1; i >= 0; i--)
result[i] = 9 - operand[i];
return result;
}
public static int[] negate(int[] operand) {
return add(complement(operand), NUMBER_ONE);
}
public static void print(int[] result, String operation) {
System.out.print(operation.charAt(0) == '-' ? "Difference = " : "Sum = ");
if (result[0] == 9) {
result = negate(result);
System.out.print("-");
}
boolean leadingZero = true;
for (int i = 0; i < result.length; i++) {
if (leadingZero) {
if (result[i] == 0)
continue;
leadingZero = false;
}
System.out.print(result[i]);
}
System.out.println(leadingZero ? "0" : "");
}
public static void main(String[] args) {
int[] operand1 = parseInteger(getOperand("#1"));
int[] operand2 = parseInteger(getOperand("#2"));
String operator = getOperator();
if (operator.equals("-"))
operand2 = negate(operand2);
int[] result = new int[ARRAY_LENGTH];
result = add(operand1, operand2);
if (DEBUG) {
System.out.println("Operand #1 = " + Arrays.toString(operand1));
System.out.println("Operand #2 = " + Arrays.toString(operand2));
System.out.println("Result = " + Arrays.toString(result));
}
print(result, operator);
}
}
Disclaimer: Your source code has multiple problems, but in order to keep it simple I am going to ignore most of them now and will just explain the reasons for your current problems and suggest fixes for them only.
If you check the array outputs from your main method, you see that the addition/subtraction results look good, i.e. the problem is not located in the calculation routines but in the print routine. There you have
duplicate code: The for loops printing the positive/negative numbers are identical.
a cosmetic problem: One leading zero is always printed.
a logical error: You check for two consecutive zeroes in order to determine where leading zeroes end and the actual number begins. But you forget that
within a number there can also be duplicate zeroes, e.g. within 10098 or -9900. This explains why 10098 is printed as 1098: You are suppressing the first zero from being printed.
if there is a zero in the last array element (e.g. 9900) you cannot check the (non-existent) subsequent element without causing an ArrayIndexOutOfBoundsException. This explains why you get the exception for -9900.
Now what can/should you do?
Eliminate the redundant for loop. You can use the same loop to print both positive and negative numbers.
Use a boolean flag in order to remember if you are still looping through leading zeroes or not.
You can change your print method like so:
public static void print(int[] result, String operation) {
System.out.print(operation.charAt(0) == '-' ? "Difference = " : "Sum = ");
if (result[0] == 9) {
result = negate(result);
System.out.print("-");
}
boolean leadingZero = true;
for (int i = 0; i < result.length; i++) {
if (leadingZero) {
if (result[i] == 0)
continue;
leadingZero = false;
}
System.out.print(result[i]);
}
System.out.println(leadingZero ? "0" : "");
}
The code after fixing the problems. all thanks to #kriegaex !
import java.util.*;
public class Program9 {
public static String getOperand() {
Scanner scan = new Scanner(System.in);
String stringOfInteger;
System.out.print("Please enter an integer up to 50 numbers: ");
stringOfInteger = scan.nextLine();
return stringOfInteger;
}
public static int[] convert(String operand) {
int [] integer = new int[50];
char ch;
int position = operand.length() - 1;
for (int i = integer.length - 1; i >= 0; i--) {
if (position >= 0)
ch = operand.charAt(position--);
else
ch = 0;
if (ch >= '0' && ch <= '9') {
integer[i] = ch - '0';
} else {
integer[i] = 0;
}
}
return integer;
}
public static int[] add(int[] operand1, int[] operand2) {
int [] result = new int[operand1.length];
int carry = 0;
for (int i = operand1.length - 1; i >= 0; i--) {
result[i] = operand1[i] + operand2[i] + carry;
if (result[i] / 10 == 1) {
result[i] = result[i] % 10;
carry = 1;
} else
carry = 0;
}
return result;
}
public static int[] complement(int[] operand2){
int [] result = new int[operand2.length];
for (int i = operand2.length - 1; i >= 0; i--)
result[i] = 9 - operand2[i];
return result;
}
public static int[] add1(int[] operand2){
int [] result = new int[operand2.length];
result[operand2.length - 1] = 1;
for (int i = result.length - 2; i >= 0; i--)
result[i] = 0;
return result;
}
public static int[] negate(int[] operand2){
return add(add1(operand2), complement(operand2));
}
public static void print(int[] result, String operation) {
if (operation.charAt(0) == '+')
System.out.print("The subtotal of the two integers = ");
else if (operation.charAt(0) == '-')
System.out.print("The subtraction of the two integers = ");
if (result[0] == 9) {
result = negate(result);
System.out.print("-");
}
boolean leadingZero = true;
for (int i = 0; i < result.length; i++) {
if (leadingZero) {
if (result[i] == 0)
continue;
leadingZero = false;
}
System.out.print(result[i]);
}
if (leadingZero == true)
System.out.println('0' - '0');
System.out.println();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] result = new int[50];
String string1 = getOperand();
String string2 = getOperand();
int [] integer1 = convert(string1);
int [] integer2 = convert(string2);
String operation;
System.out.print("Please enter which operation will be used (+ or -): ");
operation = scan.nextLine();
if (operation.charAt(0) == '+')
add(integer1, integer2);
else if (operation.charAt(0) == '-')
integer2 = negate(integer2);
result = add(integer1, integer2);
System.out.println(Arrays.toString(integer1));
System.out.println(Arrays.toString(integer2));
System.out.println(Arrays.toString(add(integer1, integer2)));
print(result, operation);
}
}
When I run the code below, why does it throw this error?
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at GuessNumber.main(GuessNumber.java:35)
This is my code, thank you:
public class GuessNumber {
public static void main(String[] args) {
int[][] num = new int[5][16];
int[] len = new int[5];
char[] bit;
for (int i = 1; i <= 32; i++) {
bit = ToBinary(i);
//bit的大小为5:把二进制数存储到数组中num
for (int j = 0; j < bit.length; j++) {
if (bit[j] == '1') {
//11000
num[j][len[j]++] = i;
}
}
}
Random r = new Random((new Date()).getTime());
int numRoad = r.nextInt(31);
bit = ToBinary(numRoad);
String cardRand = "";
for (int i = 0; i < bit.length; i++) {
if (bit[i] == '1') {
cardRand = cardRand + (i + 1) + ",";
}
}
System.out.println("在卡片" + cardRand + "上的数字是:");
System.out.println("请玩家输入猜测数字:");
Scanner c = new Scanner(System.in);
int number = c.nextInt();
if (number == numRoad) {
System.out.println("恭喜您,猜对了.");
} else {
System.out.println("对不起!猜错了,该数应该为:" + numRoad);
}
}
/**
* 将十进制数转成二进制数
*
* #param i
* #return
*/
public static char[] ToBinary(int c) {
char[] bit = new char[5];
String a = Integer.toBinaryString(c);
bit = a.toCharArray();
char temp;
for (int i = 0; i < bit.length / 2; i++) {
temp = bit[i];
bit[i] = bit[bit.length - 1 - i];
bit[bit.length - 1 - i] = bit[i];
}
return bit;
}
}
Most likely because the Scanner expected an integer value and found something else. The exception is a result of your actual input at the console.
Looks like you see a binary number (10011) and have to enter the decimal value (19)
Javadoc to the rescue:
Throws:
InputMismatchException - if the next token does not match the
Integer regular expression, or is out of range
You probably don't enter a valid integer whan asked for it by your program.