NumberFormatException trying to parse " 66" to an integer - java

So i have this slice of code that reads text from a csv file where nums[] goes throughout the file and stores the number of a said student, and grades[][] goes through and stores each of their grades:
Scanner sc = new Scanner(new FileReader("location.csv"));
String [][] stuff = new String [10][];
for(int i = 0; i<10; i++){
String line = sc.nextLine();
stuff[i] = line.split.(",");
}
int [][] grades = new int [10][10];
int [] nums = new int [10];
for(int x = 0; x<10; x++){
nums[x] = Integer.parseInt(stuff[x][0]);
System.out.println(nums[x]);
for(int y = 0; y<11; y++){
grades[x][y] = Integer.parseInt(stuff[x][y]);
}
}
The problem is that numbs works wonderfully, but grades cant store any value that is past the first column of data. If I set grades [x][y] = stuff[any number] [0] it will run, but if I try to go past 0 in the rows, I error terminate.
Part of data file:
1, 66, 82, 85, 87, 65, 80, 97, 75, 68, 72
2, 70, 63, 75, 62, 84, 65, 67, 95, 81, 96
3, 100, 98, 73, 78, 69, 75, 97, 66, 61, 90
4, 75, 62, 79, 78, 87, 73, 74, 76, 63, 84
5, 81, 90, 80, 66, 75, 96, 73, 77, 66, 87
Stack Trace:
java.lang.NumberFormatException: For input string: " 66"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
Fixed Code ( I apologize, I did not copy the code verbatim and included a few extra errors in it)
public static void main(String[] args)throws FileNotFoundException
{
Scanner sc = new Scanner(new FileReader("location.csv"));
String [][] values = new String [10][];
for(int i = 0; i<10; i++){
String line = sc.nextLine();
values[i] = line.split(",");
}
int [][] grades = new int [10][10];
int [] nums = new int [10];
for(int x = 0; x<10; x++){
nums[x] = Integer.parseInt(values[x][0]);
System.out.println(nums[x]);
for(int y = 0; y<10; y++){
grades[x][y] = Integer.parseInt(values[x][y+1].trim());
}
}

You aren't getting rid of the whitespace between tokens.
Make sure to clear it, preferably with String#trim()
Integer.parseInt(stuff[x][0].trim());
For the record, I'd also look to use better names than stuff.

Also, you're going to get an index out of bounds when you fix those other errors:
for( int y = 0; y < 11; y++ )
grades[x][y] = Integer.parseInt( stuff[x][y] );
All your array indexes go to 10, which in Java means 0 through 9. y here will go to 10, so boom out of bounds.
Considering the syntax errors pointed out in the comments, please in the future copy and paste the EXACT code you are using. It'll be no good if we are debugging different code than what you are actually using.

Related

Generate list of int to populate ComboBox in JavaFX

I'm trying to avoid hardcoding a whole bunch of numbers into my JavaFX ComboBox, but I don't know any other way to do it. Currently I'm doing this:
length_comboBox.getItems().addAll(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
However my aim is to make a call to a method that will generate a list of numbers to some specified upper limit (say 50). I've tried the following but it just adds one last i, instead of all 50:
length_comboBox.getItems().addAll(generator(50));
public static int generator(int limit) {
int i;
for (i = 1; i < limit; i++)
System.out.println(i);
return i;
}
ComboBox cBox = new ComboBox();
cBox.getItems().addAll(generator());
... example ...
private Integer[] generator() {
int size = (int) (Math.random() * 100);
Integer[] result = new Integer[size];
for (int i = 0; i < result.length; i++) {
result[i] = (int) (Math.random() * 50);
}
return result;
}
You can use the one-liner
IntStream.rangeClosed(1,50).boxed().forEach(length_comboBox.getItems()::add);
or, if you want to fire fewer change events to the combo box (in practice it will make very little difference):
length_comboBox.getItems().setAll(
IntStream.rangeClosed(1,50).boxed().collect(Collectors.toList())
);

Change 1d array to 2d array in java

How would i go about converting the following 1d arrays into 2d arrays? I am kind of confused when working with 2d arrays.
[100, 101, 102, 200, 201, 202, 300, 301, 302] [232, 123, 102, 200, 321, 202, 300, 301, 302]
Another way would be to create a 2D array with the dimensions wished, then use an outer and inner for loop to transfer values. For example:
int k = 0
//array declarations
for (int i = 0...)
for (int j = 0...)
if (k < array1D.length)
array2D[i][j] = array1D[k];
k++
You can try this: 2D Array is nothing just an array of arrays, so you can put these two array into a 2D array, every element of a 2D array is an array.
int[] arr1 = {100, 101, 102, 200, 201, 202, 300, 301, 302};
int[] arr2 = {232, 123, 102, 200, 321, 202, 300, 301, 302};
int[][] array2D = new int[2][];
array2D[0] = arr1;
array2D[1] = arr2;
int[] x = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int [][]z = new int[4][4];
for (int i = 0, k=0; i < 4; i++)
for (int jl = 0; jl < 4; jl++)
z[i][jl] = x[k++];
for(int i=0;i<4;i++)
{
System.out.println();
for(int jl=0;jl<4;jl++)
{
System.out.print(z[i][jl]+" ");
}
}
Hope you have got answer to your problem.Happy coding

How do I access a specific element of an object of an array in Java?

This program is a work in progress. In it, I created an array of ten objects with five pieces of different data types for each object. I need to find the highest score for q1 which I hoped to accomplish by creating a loop that would compare the variable highScore with each q1 data(8, 3, 10, 8, 9, 7.5, 8.5, 6, 7.5, 7) as the loop went through its cycles, however, I am getting an error message that says "The operator < is undefined for the argument type(s) double, ClassGrade" at the line that is second from the bottom. I don't understand why I am getting this error message, but i suspect that the reason i am getting it is that I am not correctly specifying the specific element that i am trying to access from each object. Any help on the matter would be greatly appreciated.
public class ClassGrade {
public String studentID;
public double q1;
public double q2;
public int mid;
public int finalExam;
public ClassGrade(String studentID, double q1, double q2, int mid, int finalExam)
{
// TODO Auto-generated constructor stub with a few modifications
}
public static void main(String[] args) {
System.out.println("this program works");
double highScore;
highScore = 0;
ClassGrade [] student = new ClassGrade[10];
student[0] = new ClassGrade ("A1", 8, 8.5, 84, 82);
student[1] = new ClassGrade ("B2", 3, 7, 0, 99);
student[2] = new ClassGrade ("C3", 10, 9.5, 92, 84);
student[3] = new ClassGrade ("D4", 8, 8, 89, 86);
student[4] = new ClassGrade ("E5", 9, 10, 83, 91);
student[5] = new ClassGrade ("F6", 7.5, 8.5, 88, 69);
student[6] = new ClassGrade ("G7", 8.5, 0, 81, 52);
student[7] = new ClassGrade ("H8", 6, 8.5, 79, 68);
student[8] = new ClassGrade ("I9", 7.5, 6, 72, 91);
student[9] = new ClassGrade ("J10", 7, 6.5, 58, 77);
for(int i=0; i<10; i++){
if (highScore < student[i])
highScore = student[i];
}
}
}
First, you need to assign your instance variables in you constructor.
You are comparing a double (highscore) with a ClassGrade (student[i]).
You need to create public methods in ClassGrade to return your desired properties.
Accessing an object's properties from an array is just the same way as from a single object. You fetch the object from the array and use '.' to access its public properties or methods. E.g:
array[i].method()
You are comparing the highscore with the actual object in the array, you are comparing a student with grade, so just make some small change - declare a method in your ClassGrade class like getQ1() and then access the q1 from the loop
This should work:
ClassGrade classGrade = (ClassGrade) student[i];
classGrade.method();
Each member of the array is still a ClassGrade, so all you need to do is check its q1 member like you would any other ClassGrade's q1.
for(int i=0; i<10; i++){
if (highScore < student[i].q1)
highScore = student[i].q1;
}
Just think about it as if the array index is part of the name, and it'll make more sense.
// Consider this:
studentZero = new ClassGrade("A1", 8, 8.5, 84, 82);
if (highScore < studentZero)
highScore = studentZero;
// studentZero is not a double. Therefore...
if (highScore < studentZero.q1)
highScore = studentZero.q1;
Alternatively, you can add a getter for q1, and use it.
int score = student[i].getQ1()
if (highScore < score)
highScore = score;
See here for an example of how to access a member of an object in an array:

Passing parameters from method to main

I can't seem to figure out what my parameters should be for my method "public static int[][] sellSeatByPrice". I need to prompt the user for a price (of a seat), then figure out if that price is taken (if it = 0) and if not, assign it the value 0.
Below is my code, help please!
import java.util.Scanner;
/**
* Write a description of class A10_TheaterSeating here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class A10_TheaterSeating
{
public static void main(String args[])
{
System.out.println("***Welcome to the Ticket Choice App!***");
System.out.println();
int[][] theaterSeats = //set values in seating chart array
{
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{20, 20, 30, 30, 40, 40, 30, 30, 20, 20},
{20, 30, 30, 40, 50, 50, 40, 30, 30, 20},
{30, 40, 50, 50, 50, 50, 50, 50, 40, 30}
};
int[][] seats = theaterSeats;
printArray(seats); //print the seating chart
System.out.println();
//Defining variables
String str = "";
String input = "";
while (!input.equalsIgnoreCase("Q"))
{
System.out.print("Select 'S' to pick a seat, 'P' choose a price or 'Q' to quit: ");
Scanner in = new Scanner(System.in);
input = in.next();
if (input.equalsIgnoreCase("S"))
{
System.out.print("Enter row and seat number desired: ");
int row = in.nextInt();
int seat = in.nextInt();
System.out.println();
sellSeatByNumber(seats, row, seat);
printArray(seats);
System.out.println();
}
else if (input.equalsIgnoreCase("P"))
{
System.out.print("Enter price of seat desired: ");
int price = in.nextInt();
System.out.println();
sellSeatByPrice(seats, row, seat, price);
printArray(seats);
System.out.println();
}
}
System.out.println();
System.out.println("Thank you for choosing the ticket choice app.");
System.out.println();
}
public static void printArray(int[][] currSeat)
{
final int ROWS = 9;
final int COLUMNS = 10;
for(int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLUMNS; j++)
{
System.out.print(currSeat[i][j] + "\t");
}
System.out.println();
}
}
public static int[][] sellSeatByNumber(int[][] seats, int row, int seat)
{
if (row <= 0 || row > 9)
{
if (seat <= 0 || seat > 10)
{
System.out.print("Please enter a valid row and seat: ");
}
}
if (seats[row][seat] == 0)
{
System.out.print("That seat is taken. Please select another seat: ");
}
else
{
seats[seats.length - row][seat - 1] = 0;
}
return seats;
}
public static int[][] sellSeatByPrice(int[][] seats, int row, int seat, int price)
{
if (seats[row][seat] = price)
{
seats[seats.length - row][seat - 1] = 0;
}
return seats;
}
}
Your parameters seem fine - the internal logic and syntax is incorrect.
Since you're using static methods, and passing along the seat matrix, that is okay - but you have to check that the values being passed in are inside the bounds of your matrix - or you will get exceptions on them.
For instance, you don't check the bounds in sellSeatByPrice(). You really should do that, or a bogus row/seat combination could blow your program up.
It's also the case that the comparison given is incorrect:
if (seats[row][seat] = price)
should really be
if (seats[row][seat] == price)
as = is assignment, and == is primitive comparison.
Furthermore, in sellSeatByNumber(), you can still run into issues since an out of bounds row/seat combo will still blow up. You do check the bounds - kudos - but you don't return anything if they're outside of those bounds. In all reality, an IllegalArgumentException should be raised if they're stepping out of bounds, or you can return the matrix unmodified (which may be more straightforward).

How to change value of array element in 2D arrays?

Let's say I got this map that prints out:
00000
00000
00000
How do I change the element in [0][0] into an X?
In other words, how to make it look like this using Screen input:
X0000
00000
00000
Considering Its an 2D Array of String Type...
arr[0][0] = "X";
Run this:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String[][] array = {{"0","0","0"},{"0","0","0"},{"0","0","0"}};
System.out.println("Before: ");
printArray(array);
array[0][0] = "x";
System.out.println("After: ");
printArray(array);
}
private static void printArray(String[][] array){
for(int i=0; i<array.length; i++){
for(int j=0; j<array[0].length; j++){
System.out.print(array[i][j]);
}
System.out.println("");
}
}
}
Or go here: http://ideone.com/2DQC1
In This example user k check array element value and change them
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
Scanner in = new Scanner(System.in);
int inputcol = 0;
int inputrow = 0;
int newnum = 0;
int uinput = 0;
int repeat = 1;
int[][] a = new int[][]{
{ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 },
{ 110, 120, 130, 140, 150, 160, 170, 180, 190, 200 },
{ 210, 220, 230, 240, 250, 260, 270, 280, 290, 300 },
{ 310, 320, 330, 340, 350, 360, 370, 380, 390, 400 },
{ 410, 420, 430, 0, 440, 450, 460, 470, 490, 500 }
};
while(repeat!=0)
{
System.out.println("Select Option:\n 1 for View Value:\n 2 for Replace Value: ");
uinput = in.nextInt();
//int b[][]={{1,3,4},{3,4,5}};
if(uinput==1)
{
System.out.println("Enter Row: ");
inputrow = in.nextInt();
System.out.println("Enter Cols:");
inputcol = in.nextInt();
System.out.println(a[inputrow][inputcol]);
}
else
if(uinput==2)
{
System.out.println("Enter Row: ");
inputrow = in.nextInt();
System.out.println("Enter Cols:");
inputcol = in.nextInt();
System.out.println("Enter New Number: ");
newnum = in.nextInt();
a[inputrow][inputcol] = newnum;
}
else
{
System.out.println("Check your input. ");
}
System.out.println("Want to repeat it? if yes press 1\n for exit press 0 ");
repeat = in.nextInt();
}
}
}

Categories

Resources