Java error when converting String in ArrayList to int - java

I am very new at Java. I am trying to write a lottery simulator. I have the following code:
Scanner input = new Scanner(System.in);
System.out.println("Enter six whole numbers between 1 and 49 in a comma-separated list: ");
String userNumbersString = input.nextLine();
String[] userNumbersArray = userNumbersString.replaceAll("\\s+","").split(",");
ArrayList userNumbers = new ArrayList(Arrays.asList(userNumbersArray));
boolean validNumbers = true;
for(int v = 0; v <= 6; v++){
if((int)userNumbers.get(v) > 49){
validNumbers = false;
v = 7;
}else{
v++;
}
}
if(validNumbers == false){
String[] str = new String[0];
main(str);
}
It compiles properly. However, when I input a series of numbers, I get this error:
java.lang.ClassCastException:
java.lang.String cannot be cast to java.lang.Integer.
I am very confused about why this string can't be cast to an integer.
Sorry if this is a long-winded question, but I would hugely appreciate any help.
I have just realised that the OutOfBounds exception was due to a stupid maths mistake on my part; v was starting at 0; there were five values in the array, but I gave the for loop the condition <= 6. Sorry about that.
Thank you everybody for all your help. Together, you have resolved my question.

In simple terms
int is a primitive type for representing a 32-bit integer number.
String is a reference type wrapped arround an array of chars to represent a sequence of characters.
You cannot just change the type from int to String and make the character sequence in the string magically becomes a number.
Think about how you would implement this conversion. You would look at each character, make sure it is a valid digit etc.
Change:
if((int)userNumbers.get(v) > 49)
To:
if(Integer.parseInt(userNumbers.get(v)) > 49)
Further, when creating Generic type containers like ArrayList make sure you also declare what type of objects they store for type safety reasons.
Change:
ArrayList userNumbers = new ArrayList(Arrays.asList(userNumbersArray));
To:
ArrayList<String> userNumbers = new ArrayList<String>(Arrays.asList(userNumbersArray));
This way you calling userNumber.get() will return a String.
If you don't put this it will return an Object so you would actually call Integer.parseInt(Object) which is invalid. You would get a pretty self-explanatory error looking like this:
The method parseInt(String) in the type Integer is not applicable for the arguments (Object)
EDIT:
For your IndexOutOfBounds error, you are trying to access more elements than you have. Basically, you want to have 6 values but your for loop says from 0 until 6 (included). That is a total of 7 elements: 0, 1, 2, 3, 4, 5, 6
You can fix this by changing the <= 6 to < 6 in your loop but the best way to fix it so it will work no matter how many elements you have is to use the size() property of ArrayList:
Change:
for(int v = 0; v <= 6; v++)
To:
for(int v = 0; v < userNumbers.size(); v++)

First, you should use generics for ArrayList. Please replace
ArrayList userNumbers = new ArrayList(Arrays.asList(userNumbersArray));
with
ArrayList<String> userNumbers = new ArrayList<>(Arrays.asList(userNumbersArray));
However, this is not your problem. The misconception here is that casting will infer what type of conversion you need; it won't. Replace (int)userNumbers.get(v) with Integer.parseInt(userNumbers.get(v)) to parse the int from a String.

Type casting is not meant to parse an Integervalue from an String.
You should use Integer.parseInt for that.
if(Integer.parseInt(userNumbers.get(v)) > 49
should solve your error.

First, you will get an ArrayIndexOutOfBounds exception because of the <= 6 in your for loop.
Secondly, you should use the Integer.parseInt(String intStr) method to turn each number into its int equivalent.
Here is a stripped down version that I think works:
public static void main(String[] args)
{
String testInputOne = "14,22,18,2,5,11";
boolean allNumbersAreValid = true;
String[] userNumbersStrArray = testInputOne.split(",");
for (String numberStr: userNumbersStrArray)
{
Integer number = Integer.parseInt(numberStr.trim());
if (number > 49)
{
allNumbersAreValid = false;
break;
}
}
System.out.println("Testing " + testInputOne + ": " + (allNumbersAreValid?"All valid!":"At least one invalid"));
}
If you want to further guard against bad input such as someone entering an alpha character, you could wrap the Integer.parseInt call in a try catch block and catch the NumberFormatException and output a suitable error message.
I'm frankly a little scared as to what the recursive call to main is supposed to do? :)

Related

Is it possible to pass input.next - after verification - directly to a method as parameters in a variable length argument list? <in java>

package compute.greatest.common.denominator;
import java.util.Scanner;
public class computeGreatestCommonDenominator{
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
final int MAX = 20;
final int MIN = 2;
System.out.println("Enter between " + MIN + " and " + MAX + " numbers ( inclusive ) to find the GCD of: ");
for(int i = 0; input.nextInt() != '\n'; i++) { // Normally I would use a for loop to populate input into
if(input.nextInt() < MIN) { // an array and pass the array to method gcd().
System.out.println("ERROR! That number is not within the given constraints! Exiting.......");
System.exit(1); // Any non-zero value, is considered an abnormal exit.
}
}
public static int gcd(int... numbers) {
int greatestCommonDenominator = 0;
}
}
Normally I would use a for loop to populate input into an array and pass that to method gcd(int... numbers). However, that seems to be a case of redundancy to me - passing an array to a variable length argument list, which is treated as an array.
First let me say that I'm still in the learning phase of java and, while understanding variable length argument lists, it's not a confident understanding.
Is there a way to verify the input data and pass it, one by one, in the loop,
directly to the variable length argument list - without using an array?
With an array seems redundant to me and without seems illogical :/
I think you are misunderstanding the use of variable length parameters (varargs) here.
Varargs are nice syntactic sugar because it makes this code:
int[] ints = {1, 2, 3};
gcd(ints);
more elegant:
gcd(1, 2, 3);
That is the purpose of varargs.
If you don't have or expect code like this:
int[] ints = {1, 2, 3};
gcd(ints);
then varargs is not so useful, and certainly don't force your code fit into this varargs thing.
My suggestion is that you keep your code the way it is, or you can change the varargs into a normal array parameter if you don't need to use the varargs feature anywhere else in your code.

Error in swapping characters in stringbuffer object

i am trying to sort a string in the alphabetical order, however i am facing an error in the line :
sb.charAt(j)=sb.charAt(j+1);
where the compiler shows an error as expected variable; found value
the rest of the code is as follows :
import java.util.Scanner;
class a
{
public static void main(String[] agrs)
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
StringBuffer sb = new StringBuffer();
sb.append(s);
for(int i = 0; i< s.length(); i++)
{
for(int j = 0; j<s.length(); j++)
{
if(s.charAt(j)>s.charAt(j+1)){
char temp = s.charAt(j);
sb.charAt(j)=sb.charAt(j+1);
sb.charAt(j+1)=temp;
}
}
}}}
kindly help me out as i'm a beginner and i cannot figure out why this issue is occurring , thank you .
This looks like a homework assignment where the goal is to sort the characters of a text being entered, so if you enter gfedbca the result should be abcdefg.
You already got a comment telling you what the problem is: StringBuffer#charAt() is not returning a reference to StringBuffer's internal array that you can change the value of. Dependent on the actual assignment you can call StringBuffers setCharAt method or you can go another approach by converting the text to sort to a char array and do the sorting in there. There are actually helper-classes in the JVM, that do that for you, have a look e.g. at the class java.util.Arrays
As already answered by many, the issue is in charAt(index) you are using, as this returns the character at the given index rather than setting a char at the index position.
My answer is to divert your approach of sorting. For simpler solutions, where smaller data sets (like your problem) are used, you should use the predefined sorting algorithms, like Insertion Sort
You may get help for the algo from here: http://www.geeksforgeeks.org/insertion-sort/
StringBuffer's charAt returns just the value of the char at the index, if you want to swap two chars you need to use setter for that, so you possible want to do somtehing like:
for(int j = 0; j < s.length() - 1; j++) {
if(s.charAt(j) > s.charAt(j + 1)) {
char temp = s.charAt(j);
sb.setCharAt(j, sb.charAt(j + 1));
sb.setCharAt(j + 1, temp);
}
}
This method can only return values and can not set values, I guess you might want to use this method:
setCharAt()
It can meet your requirement

How do I fix this coding bat FizzBuzz code, it keeps returning null as first value

I don't know what is causing this error. I also tried to add
String[] b = Arrays.copyOfRange(a, 1, start-end+1);
at the end but it kept saying it only accepts String[], int, int even though that is what I entered. Here is the full error: Error:
String[] b = Arrays.copyOfRange(a, 1, start-end+1);
^^^^^^^^^^^
The method copyOfRange(String[], int, int) is undefined for the type Arrays
All of your cases are correct, but arrays are zero indexed.
Start with int i = 0 or set a[0] yourself before the loop to the value you need (but, it seems you just want i = 0)
And the array size seems to just be end-start. Not sure why you add one. That would explain why there's one extra element in all your arrays
public String[] fizzBuzz(int start, int end) {
int temp=start;
int i=0;
String[] str= new String[end-start];
while(temp<end){
if (temp%15==0)
str[i]="FizzBuzz";
else
if(temp%3==0)
str[i]="Fizz";
else
if(temp%5==0)
str[i]="Buzz";
else
str[i]=String.valueOf(temp);
temp++;
i++;
}
return str;
}

Extracting characters from a string and putting into specific arrays by type

I'm new to Java so I'm trying to write random programs to figure it out. I'm trying to write something that takes as user-input a quadratic equation like so: x^2 + 3x -1
Maybe this is too advanced (or maybe it isn't) but I'm wondering how to extract the characters one-by-one in a loop. If it was all digits I think I could use .isDigit() and save them to an array, but because they're different data types I'm not sure how to go about doing this. My 'code' so far looks like this
import java.lang.String;
import java.lang.StringBuffer;
import java.util.Scanner;
import java.lang.Character;
public class Lab
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
System.out.print("Please input the quadratic equation (ex: 2x^2 + 3x - 2): ");
String request = user_input.nextLine();
int myArr[];
String lettArr[];
for (int i = 0; i <= request.length(); i++)
{
String c = request.charAt(i);
if (request.isDigit(c))
{
myArr[1] += c;
}
if(request.isLowerCase(c))
{
lettArr[1] += c;
}
}
System.out.println(myArr[0]);
}
}
my .isDigit() and .isLowerCase() methods are not working. I think I'm using them in the right sense. This is pretty complex for my level and I'm wondering if this is a dead-end or an acceptable strategy.
Thanks.
I think what your are trying to do is to extract the coefficients from the user input. Your approach might work but there would be many case that you have to consider (+/- signs for example). Instead why don't you try Java's regular expressions
String input = "2x^2 - 4x + 1";
input = input.replaceAll("\\s", ""); //removes all whitespaces
Pattern p = Pattern.compile("(-?\\d+)x\\^2((\\+|-)\\d+)x((\\+|-)\\d+)");
Matcher m = p.matcher(input);
if (!m.matches()) {
System.out.println("Incorrect input");
return;
}
int a, b, c;
a = Integer.parseInt(m.group(1));
b = Integer.parseInt(m.group(2));
c = Integer.parseInt(m.group(4));
System.out.println(String.format("a=%d, b=%d, c=%d", a, b, c));
You can adapt this fragment and use it in your code. I , however, supposed that your coefficients are integer numbers. If you need them, instead, to be double you have to change the format of the given regex and also to change Integer.parseInt to Double.parseDouble. I could write this in more details if you are interested.
There are a few things wrong with your code:
public class Lab
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
System.out.print("Please input the quadratic equation (ex: 2x^2 + 3x - 2): ");
String request = user_input.nextLine();
int myArr[]; //not initialized
String lettArr[]; //should be a character type & not initialized
for (int i = 0; i <= request.length(); i++)
{
String c = request.charAt(i); // returns a char
if (request.isDigit(c))
{
myArr[1] += c; // not right, myArr is ints and c is a char
}
if(request.isLowerCase(c))
{
lettArr[1] += c; // not right
}
}
System.out.println(myArr[0]); //only prints one char (you might want this
}
}
1.
You are extracting a character from the input string and trying to add it to the second entry in an uninitialized array. You're line in code is:
myArr[1] += c;
myArr is an integer array and c is a character. You can't do that in java. What's more, you are trying to add a char to an int, which was not initialized in the first place!! The type of everything in an array must be the same. This gets more complicated when it comes to inheritance and such, but for now just know that you can't do that. If you wanted the Integer value of a character you can use:
Integer.parseInt(c)
I'm not sure what you are trying to do with your statement, but I'm 90% sure that it's not trying to do what you want it to. For reference:
myCharArr[i] = c;
assigns the i-th element (starting from 0) to the value of c. So if i=1 and myCharArr was initialized to 3 elements long, it would look like this:
[ ? | c | ?]
where ? is just a garbage value.
2.
In java you need to initialize your arrays, or use a more dynamic List object. The thing with primitive arrays is that their size cannot change, i.e. when an primitive array is initialized:
int arr[] = new int[5];
it stays the same size (in this case 5). If you use something like an ArrayList, you can add as many things as you want. The way you would initialize ArrayLists would be like:
ArrayList<Integer> intArr = new ArrayList<Integer>();
ArrayList<Character> charArr = new ArrayList<Character();
and with those initialized you can do:
intArr.add(someInt);
charArr.add(someChar);
You can use primitive arrays for this problem but it will save you a bit of trouble if you use Lists.
Read up on arrays.

Understanding Array Indexing in Java

I have a brief question about how Java handles arrays. Below is my code:
//import java.util.Arrays;
import static java.lang.System.out;
public class Arrays
{
public static void main(String[] args)
{
String [][] multiArray = new String[10][8];
int k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println ();
for (int i = 0; i < multiArray.length; i++)
{
for (int j = 0; j < multiArray[i].length; j++)
{
multiArray[i][j] = i + "" + j;
out.print ("| " + multiArray[i][j] + " ");
}
out.println ("|");
}
k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println();
}
}
I understand that you have to create a double "for" loop to print out values for both dimensions and that you have to have:
multiArray[i].length
so that it knows to reference the length of the second dimension. I just don't understand how it works.
What I'm confused about is this: At the very beginning of the program, directly after I declare my array, if I write a statement like:
system.out.println (multiArray.length);
It will print the value of 10, which is the length I declared in the first dimension. If I, however, create some random variable like "int a = 0" or "int idontgetthis = 0" and then I write:
system.out.println (multiArray[a].length);
it somehow knows to print the length of the second dimension, 8. So my question is, how does it know how to do this? It's killing me!! lol
Because multiArray is really an array of arrays. So multiArray[a] is a reference to an object. That object is itself an array. That array has a length (8), and a property called length which can be used to return that length.
Basically, it is a concept confusion, by doing:
String[] array;
you are declaring that you will have an array of Strings with an unknown lenght.
A call to: System.out.println(array.length) at this moment will fail with a compilation error because array is not yet initialized (so the compiler can't know how long it is).
By doing:
String[] array = new String[8]
you declare that you will have and array of String and initialize it, specifying it will have space for 8 Strings, the compiler then allocates space for this 8 Strings.
Something important to notice is that even when the compiler now knows that you will store 8 Strings in your array, it will fill it with 8 nulls.
So a call to System.out.println(array.length) at this point will return 8 (Compiler knows the size) but a call to System.out.println(array[1]) will return a Null Pointer Exception (You have 8 nulls in it).
Now, in the example you presented, you are declaring a bidimensional array, this is, an array that will contain other arrays.
Bidimensional arrays are initialized as String[][] multiarray = new String[10][8]; and the logic is the same as in simple arrays, the new String[10][8]; indicates the lenght of the array that contains the other arrays, and the new String[10][8]; indicates the length of the contained arrays.
So doing system.out.println(multiArray[x].length); after initializing multiarray is translated as "What is the length of the Xth contained array?", which the compiler, thanks to your initialization, now knows is 8 for all the contained arrays, even when they are full of nulls at the moment.
Hope it helps to add a bit more understanding!
You could try looking at it like this.
public class Arrays{
public static class EightStrings {
public String[] strings = new String[8];
}
EightStrings[] tenOfThem = new EightStrings[10];
}

Categories