How to fix this exception in Java? - java

My code is like this
import java.io.File;
import java.util.Scanner;
public class ReadFile{
public static void main(String[] args)throws Exception {
Scanner scan = new Scanner(new File("input.txt"));
int[][] arr = new int[4][4];
for(int t = 1; t <= 2; t++){
int firstRow = scan.nextInt();
System.out.println(firstRow);
for(int i = 0; i <= 4; i++){
if(scan.hasNextLine()){
String[] splited = scan.nextLine().split("\\s");
for(String f : splited)
System.out.println(f);
for(int g = 0; g <= 4; g++){
arr[i][g] = Integer.parseInt(splited[i]); // at this point the exception is being thrown
}
}
}
}
}
Through which I am trying to read a file having data arranged in following format
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3
1 2 5 4
3 11 6 15
9 10 7 12
13 14 8 16
Basically I want to read the first number 2 (single value in a line) and 3(again a single value in line 6th from top) and store them in firstRowNum variable and secondNumRow variable and the rest of the numbers in two 4X4 matrices.
But when I am running the code I am getting the following exception
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at ReadFile.main(ReadFile.java:20)
I think I am not setting the loops correctly.
Thanks

Replace
splited[i]
with
f
as the argument to Integer.parseInt(). Also, don't use another loop for the g index; use
arr[i][g++]
and initialize g to 0 before the inner for each loop. Alternatively, use the g-based loop as it is, but replace splited[i] with splited[g].
You have other issues as well, such as using
i <= 4
as the upper bound condition of the loop, but your array's indices range from 0 to 3 (i < 4 should be used).

You can check if the String is empty before the conversion to Integer, using the function String.isEmpty()

Related

Adding spaces between operation marks [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed last month.
Whats the difference between these two operations?
I imagined:
length - 1
to be the same as
length-1
but I am getting an error with length when using the latter
using operation here: for (int i = length - 1; i >= 0; i--)
int length = Integer.parseInt(scan.nextLine());
Edit: ENTIRE CODE:
import java.util.Scanner;
import java.util.Arrays;
public class continuousmedian
{
public static void main(String args[])
{
Scanner scan = new Scanner (System.in);
int cases = Integer.parseInt(scan.nextLine());
for (int set = 0; set < cases; set++)
{
int length = Integer.parseInt(scan.nextLine()), med = 0;
String[] copy = (scan.nextLine()).split(" ");
int[] test = new int[length];
for (int i = length-1; i >= 0; i--)
{
test [i] = Integer.parseInt(copy[i]);
//System.out.println("4 is " + test[4]);
Arrays.sort(test);
//*
System.out.print(">>");
for (int a = 0; a < length; a++)
System.out.print(test [a]);
System.out.println();
//*/
//System.out.println(i);
int mid = length - 1 - i;
if (i%2 == 0)
med += test[mid];
else
med += Math.floor((test[mid] + test[mid+1])/2);
//System.out.println("TEST AT " + mid + " is " + test[mid]);
}
System.out.println(med);
}
}
}
input case:
2
6
1 3 6 2 7 8
7
1 3 6 2 7 8 5
and finally, the error message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1 3 6 2 7 8"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:784)
at continuousmedian.main(continuousmedian.java:13)
For those of you saying that it is trying to parse a line of input:
The ONLY thing I changed is length-1 -> length - 1
"They are the same. Coding conventions say to use spaces, but the semantics are the same." - Ole
This was correct. Turns out, it didn't matter which of the formats I chose. In the end, it was completely 50/50 when running the program whether it worked or not. I ran the program a few times, copy pasting the same input into the same program. Sometimes it worked, sometimes it didn't. Maybe something with my computer clock or something, Idk but thanks for the help anyways.
This line is your problem:
int length = Integer.parseInt(scan.nextLine()), med = 0;
If the input line is "1 3 6 2 7 8", then you attempt to parse that line as an integer, which it manifestly is not. An exception is thrown indicating you're applying parseInt to invalid data.
We can tell this with absolute certainty - the exception message says so. You were trying to apply parseInt to the string "1 3 6 2 7 8". This is not in doubt.
It looks like that particular line of input was intended for the next line of code, which will split it on spaces, but in fact you never get there because of the previous error.
Given your statement that the input was supposed to be
2
6
1 3 6 2 7 8
7
1 3 6 2 7 8 5
then it looks like you didn't actually type one of the "2" or the "6".

Index n out of bounds for length n Exception. I am trying to try to remove duplicates from an array to make a new array then display it [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
Expected output:
Usage: java Main 1 2 3 4 5 5 to remove duplicates from numbers 1 2 3 4 5 5
java Main 1 2 3 4 5 5
Here are the distinct numbers 1 2 3 4 5
output:
Usage: java Main 1 2 3 4 5 5 to remove duplicates from numbers 1 2 3 4 5 5
java Main 1 2 3 4 5 5
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: Index 5
out of bounds for length 5
at Main.main(Main.java:26)
/*
Johnny Santamaria
CS 111B Assignment 5 - deDup
This program gives you instructions to remove duplicate numbers in an array
*/
class Main {
public static void main(String[] args) {
int[] numArray;
int index = 0;
int num;
if (args == null || args.length < 1) {
System.out.println("Usage: java Main 1 2 3 4 5 5 to remove duplicates from the numbers 1 2 3 4 5 5");
return; //exit function
}
//finds integers in command line
index = args.length;
numArray = new int[index];
//convert to integers to actually make the array
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[index] = num;
index++;
}
int uniqueIndex = deDup(numArray, index);
}
public static int deDup(int[] numArray, int index) {
if (index == 0 || index == 1) {
return index;
}
//creates new index to store unique numbers
int uniqueIndex = 0;
//checks each number in the array to remove duplicates to make a new index
for (int i = 0; i < index - 1; i++) {
//deletes a number in the index of the array then reformats them
if (numArray[i] != numArray[i + 1]) {
numArray[uniqueIndex++] = numArray[i];
}
}
numArray[uniqueIndex++] = numArray[index - 1];
System.out.println("Here are the distinct numbers: " + numArray[uniqueIndex]);
return uniqueIndex;
}
}
The exception message indicates that you are trying to access an index that does not exist:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 5 at Main.main(Main.java:26)
Illegal access occurs on this line:
numArray[index] = num;
The reason is that in numArray there is no index with the value of the index variable.
PS: note that on line 19 you assign the length of args to the variable index.
The problem is that you define these values:
index = args.length;
numArray = new int[index];
and then in the first loop iteration you access
numArray[index] = num;
which is not a valid index since it is too big by 1.
The real problem here is that you are using index as a running variable in your loop, but it is not set to the starting value of 0. You are using the same variable for two different purposes.
Either
set index = 0; before the loop or
use a different variable in your loop, such as i:
int i = 0;
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[i++] = num;
}

How to read a sequence of integers from Standard-input with Stdin?

I'm using java on command lines, i want to write a programm that could filter and removes the duplicates of a sequence of integers but first of all i don't know how to use StdIn to read a sequnce of Integers.
The Programm should read values from Standard input until it reach the EOF-Sequence with the help of StdIn.
Input and Output example on Command line:
$ echo 1 1 2 2 1 1 3 4 6 2 1 | java RemoveDuplicates
1 2 1 3 4 6 2 1
I've tried to convert the Integers to an array
int[] n = StdIn.readAllInts();
but it doesn't work when tried to print it out.
can anybody give me some tips?
You should be able to catch it as a string with a normal scanner:
Scanner in = new Scanner(System.in);
String line = in.nextLine();
sometimes the second line don't work for some inputs, so you can also try:
String line = in.next();
to get the numbers as integers you can use inputStream, but I'm not sure how will work.
A possible solution could be:
int testNum;
Set<Integer> set = new HashSet<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("number of elements to be inserted");
testNum = in.nextInt();
//Add items
for ( int i = 0; i<testNum; i++)
{
set.add(in.nextInt());
}
//Print all element
Iterator it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
I hope to have helped you
Sample program below, this removes the duplicate entries but still retains the order.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sequence with spaces e.g. 1 3 5 3 1 1 3 5 ");
String input = sc.nextLine();
String[] numbers = input.split("\\s+");
List<String> result = new ArrayList<>();
for (int x = 0; x < numbers.length; x++) {
String item = numbers[x];
if (result.contains(item)) continue;
result.add(item);
}
System.out.println(String.join(" ", result));
}
And output sample is:
Enter the sequence with spaces e.g. 1 3 5 3 1 1 3 5
1 1 2 2 1 1 1 3 4 1 1 1 11 11 12 12 1 1 6 6 2 1 //sequence entered
1 2 3 4 11 12 6 // sample result
Stdin is not needed.
By calling
java RemoveDuplicates 1 1 2 2 1 1 3 4 6 2 1
It assigns String[] args to an array of all those values.
If you want to remove duplicates, put them in a Set
public static void main(String[] args) {
Set<String> uniq = new HashSet<>();
for (String s : args) {
uniq.add(s);
}
System.out.println(uniq);
}

Incrementing 2D Arrays vertically and horizontally?

I am trying to make a method where a 2D array is created in the main, which can be any dimension. After that, we are supposed to make 2 methods, one which increments each next value in the array by a given number labeled step. One method is supposed to increment the rows, and the other increments it by columns.
This is what I have:
public static void main (String [] args){
int [][] fillRightArray = new int [5][8];
fillRight(fillRightArray, 2);
int [][] fillDownArray = new int[5][8];
fillDown(fillDownArray, -2);
For the fill right method, this is the what the output should be:
2 4 6 8 10 12 14 16
18 20 22 24... //all the way to 80, since the array has 40 elements (40*2=80)
This is my method:
public static void fillRight (int [][] fillRightArray, int step){
for (int i = 0; i< fillRightArray.length; i++){
for (int j = 0; j< fillRightArray[i].length; j++){
fillRightArray[i][j] += step*(j+1);
System.out.print(fillRightArray[i][j] + " ");
}
System.out.print("\n");
}
But for some reason, my output is:
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
Any idea as to why this is happening? Same thing happens when I go with the fillDown method, the output is supposed to be:
2 12 22....
4 14 24....
6 16 26....
8 18 28....
10 20 30.... all the way to 80
But instead I get:
2 2 2 2 2
4 4 4 4 4
6 6 6 6 6
8 8 8 8 8
10 10 10 10 10
Your code doesn't work because you aren't taking into account the previous cell.
Your logic for determining the value of a specific cell is fillRightArray[i][j] += step*(j+1); .
This line only considers the value of j to determine the value of a cell within your array, when it should also consider the value of i (explicitly or implicitly).
You should add a counter that keeps track of how many cells you have set, and set the next cells value based on the number of cells that have already been set.
Your fillRight method should instead look like this:
public static void fillRight (int [][] fillRightArray, int step){
int count = 0;
for (int i = 0; i< fillRightArray.length; i++){
for (int j = 0; j< fillRightArray[i].length; j++){
count++;
fillRightArray[i][j] += step*count;
System.out.print(fillRightArray[i][j] + " ");
}
System.out.print("\n");
}
}
You're constantly repeating the same work and going back to 0 each time.
In your fillRight, each row is doing 2,4,6,8,10 because you're doing step*(j+1), where j resets to 0 after each iteration of the loop. You need to find a way to include i as well as j when setting the value, or just have a counting variable that is incremented each step
Like this:
step += 2
fillRightArray[i][j] = step
That way you don't need to worry about position.

Multiplication Table For Loop

This is the code I wrote; it's going into an infinite loop and I don't know why..
import java.io.*;
public class Multi{
public static void main(String args[])throws IOException{
int num;
BufferedReader inpt = new BufferedReader (new InputStreamReader (System.in));
System.out.print("Enter a number: ");
num=Integer.parseInt(inpt.readLine());
int z,x,y;
while (num>=1 || num<=11){
for(z=1; z<=num; z++){
for(x=1; x<=z; x++){
y=z*x;
System.out.print(y+" ");
}
System.out.println();
}
}
}
}
The output I want to show in this one is that when a person inputs a number it will display a multiplication table.
e.g.
Enter a number: 5
Result:
- 1 2 3 4 5
- 2 4 6 8 10
- 3 6 9 12 15
- 4 8 12 16 20
- 5 10 15 20 25
Enter a number: 3
- 1 2 3
- 2 4 6
- 3 6 9
Your while condition will never be false:
while (num>=1 || num<=11)
Every possible number is >= 1 or <= 11. I guess you meant "and" instead of "or".
Also, you need to put the code that sets num inside the while-loop.
//To get a multiplication table for the number get from user
#include<stdio.h>
int main() {
int i;
int num;
scanf("%d",&num);
for(i=1; i<=10; i++){
printf("%d\n",i*num);
}
return 0;
}

Categories

Resources