Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 Error [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I am new to programming, so just consider my mistakes. I am writing a program where the user gives two input numbers in one line separated by whitespace. I have to assign the first input to an integer variable and second to a double and have to perform some mathematics and show the result. Following is my code:
import java.util.Scanner;
public class foo{
public static void main(String[] args){
String b = null;
Scanner sc = new Scanner(System.in);
b = sc.next();
String[] split = b.split(" ");
int i = Integer.parseInt(split[0]);
double d = Double.parseDouble(split[1]);
System.out.println(i+20);
System.out.println(d-1.50);
}
}
And following is the error i am getting while running it.
F:\java\work\codechef>javac foo.java
F:\java\work\codechef>java foo
20 300.50
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at foo.main(foo.java:9)
First I tried making it with b=sc.readLine(); but there i got the following error while compiling:
error: cannot find symbol
b = sc.readLine();
^
symbol: method readLine()
location: variable sc of type Scanner
1 error
Why I am getting these errors and how to solve the above problem.

You used sc.next() which returns the next token (a token is something that had delimiter before and/or after) so it contains only the 20 or 300.50 in your case.
You should use sc.nextLine() to use split later on, this will return the full line.
Or use:
int i = Integer.parseInt(sc.next());
double d = Double.parseDouble(sc.next());
And get rid of lines:
b = sc.next();
String[] split = b.split(" ");

Related

Java scanner.nextDouble() gives an exception [duplicate]

This question already has answers here:
nextDouble() throws an InputMismatchException when I enter a double
(2 answers)
Closed 5 months ago.
I am learning Java and i have met some problems with scanner.nextDouble and I can`t find any response for me.
import java.util.Scanner;
public class Hypotenuse {
public static void main(String[] args){
double a;
double b;
double c;
Scanner scanner = new Scanner(System.in);
System.out.println("Type first side: ");
a = scanner.nextDouble();
System.out.println("Type second side: ");
b = scanner.nextDouble();
c = Math.sqrt((a*a) + (b*b));
System.out.println("The c side is: " + c);
scanner.close();
}
}
The problem is when I`m trying to type number with dot like 1.2 for example which is double type. The exception code is:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:943)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2569)
at Hypotenuse.main(Hypotenuse.java:10)
How do I can fix it ? Thanks for help
It depends on your system. But if you really want to use the dot, you can change the Locale to make a Scanner read dots in this way:
new Scanner(System.in).useLocale(Locale.US);
For example:
Scanner scanner = new Scanner(System.in).useLocale(Local.US); will
use the dot
Scanner scanner = new Scanner(System.in).useLocale(Local.ITALY); will use the comma.

String array out of bounds [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am trying to make an array of type string of which the size and strings are inputted by the user and i keep getting error ArrayIndexOutOfBoundsException There is similar threads i found pertaining to this but none of which have solved this error. in my for statement if i take out the equal to and just do less than i receive no errors but i can only input one name less than the number i input. If i leave the code as is everything appears to work as it should minus the error. I understand i am getting this fault because my array is going out of bounds but i cant figure out why. please help! thank you!
package sales;
import compare.*;
import java.util.*;
public class Sales {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter number of employees to compare:");
int numEmp = scan.nextInt();
while(numEmp < 2){
System.out.println("Has to be at least 2 employees:");
numEmp = scan.nextInt();
}
String[] names = new String[numEmp];
System.out.println("Enter employees name:");
for(int i=0;i<=names.length;i++){
names[i]=scan.nextLine();
}
}
}
Change the condition of the for to i<names.length instead of i<=names.length.
scan.nextLine(); //add this
for(int i=0;i<names.length;i++){
names[i]=scan.nextLine();
}

Java String automatically assigned null value [duplicate]

This question already has answers here:
Java calculator not executing if-statement [duplicate]
(3 answers)
Closed 9 years ago.
In the code below, in the first iteration of the first for loop, boxes[a] is automatically assigned a null value.
The remainder of the iterations are fine (user input is accepted). Only the first has the issue where a null value is automatically assigned.
Does anyone know why this may be? Thank you.
package testing;
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
int boxNumber;
boxNumber = in.nextInt();
String[] boxes = new String[boxNumber];
System.out.println(boxNumber);
for(int a=0; a <= boxes.length - 1; a++){
boxes[a] = in.nextLine();
System.out.println(boxes[a]);
}
int packageNumber;
packageNumber = in2.nextInt();
String[] packages = new String[packageNumber];
System.out.println(packageNumber);
for(int n=0; n <= packageNumber - 1; n++){
packages[n] = in.nextLine();
System.out.println(packages[n]);
}
}
}
The scenario fitting the description of what occurs is when you type in a number on the first line, then the rest of the lines are strings for the boxes.
But the nextInt() method doesn't advance past the first newline character, so the first time you call nextLine(), it matches on the rest of the line until the first newline character, "" ( not null).
After the call to nextInt(), insert a call to newLine() before the for loop to bypass the first newline character.
String firstNewLine = in.nextLine();
for(int a=0; a <= boxes.length - 1; a++){
when you did hit enter after entring the first number you also have and empty line that's why nextLine() return empty string, you can use this boxNumber = in2.nextInt(); instead but I would suggest to think of another way, normally you don't need two Scanner instances

error: '.class' expected [duplicate]

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 4 years ago.
Hi friends while compiling the below error is coming
error: '.class' expected
I'm not able to find what is the error. I checked in many websites but not able to find why this error is coming. Plz Help
Thanks in advance.
import java.io.*;
class Test
{
boolean isGoodEmployee(boolean ismarried,int noofchild,String middlename,String childnames[])
{
boolean child,letter,last,child;
if (noofchild <= 2)
child=true;
boolean firstletter = middlename.startsWith("k");
boolean lastletter = middlename.endssWith("e");
if (firstletter && (!lastletter))
letter = true;
int lastnameletterscount = lastname.length();
if (lastnameletterscount > 4)
last = true;
String name = raju;
for (int i=0; i < noofchild; i++)
if(name.equalsIgnoreCase(childnames[i]))
{
child = true;
break;
}
}
}
class GoodEmployee
{
public static void main(String args[]) throws IOException
{
String firstname, middlename, lastname;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the first name of employee");
firstname = br.readLine();
System.out.println("enter the middle name of employee");
middlename = br.readLine();
System.out.println("enter the last name of employee");
lastname = br.readLine();
//System.out.println("full name of employee is:"+first+middle+last);
System.out.println("enter employee is married or not");
boolean ismarried = Boolean.parseBoolean(br.readLine());
if (ismarried)
System.out.println("enter number of childrens");
int noofchild = Integer.parseInt(br.readLine());
String childnames[] = new String[noofchild];
System.out.println("enter children names");
for (int i=0; i < noofchild; i++)
childnames[i] = br.readLine();
Test t = new Test();
t.isGoodEmployee(ismarried,noofchild,middlename,childnames[]);
}
}
I'm using "javac GoodEmployee.java" to compile the program
You have a mis-matching method call in isGoodEmployee.
The childnames argument is defined as an array, so you can simply pass in the argument, replace:
t.isGoodEmployee(ismarried,noofchild,middlename,childnames[]);
with
t.isGoodEmployee(ismarried,noofchild,middlename,childnames);
Aside from that, do not ignore other compilers errors such as
middlename.endssWith("e");
^---------extra 's'
Familiarize yourself with the javadocs.
there's plenty wrong with this code:
you've declared boolean child twice in isGoodEmployee() (1st line)
endssWith should be endsWith()
and so on, but nont of them are the issue you stated. what command line are you using for compiling this class?
#Reimeus has nailed it.
The strange compilation error can be explained as follows. In this line:
t.isGoodEmployee(ismarried,noofchild,middlename,childnames[]);
the childnames[] phrase is supposed to be a Java expression. But in fact, the syntax most closely resembles a type ... in fact an array of some (non-existent) class called childnames. The Java compiler's syntax error recovery code has decided that if it inserts .class after the typename (i.e. childnames[].class) that will give a syntactically valid expression.
Of course, the correction that the compiler is suggesting is nonsensical ... not least because there won't be a class or interface named childnames in your application.
The moral of the story is that unusual syntax errors sometimes cause a compiler to produce peculiar error messages that only make sense if you can figure out how the parser would have parsed the erroneous input.
Make the class with the main method public if you are using an IDE.
In case you are trying to run it using command window I don't think a '.class' file is required for compiling rather it would be required for execution. So after you have a .class file by entering javac GoodEmployee and you have no errors enter java GoodEmployee which will execute the .class file you have.

cannot find the symbol method console(); [duplicate]

This question already has answers here:
java.lang.System error in Console() [closed]
(3 answers)
Closed 4 years ago.
This is my code :---
import java.lang.*;
class Console
{
public static void main(String args[])
{
char i;
i=System.console().readLine("this is how we give he input to the string");
System.out.println("this is what we want to print:0)");
System.out.println(i);
}
}
and the output I am getting is this:-
Output:-
.java:7: cannot find symbol
symbol : method console()
location: class java.lang.System
i=System.console().readLine("this is how we give he input to the string");
^
1 error
Tool completed with exit code 1
If anyone can help me out...
Mistake with the jdk version, because it must be jdk1.6 or later, and when changed to a newer jdk,
there's a compilation problem, System.console().readLine() returns a String, but you assigned char
Also, some IDE's have trouble with the console class (possibly because they are using it themselves to redirect output to a window/dialog)
So a really good work around is using:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readline();
//or if you want a char
char i = str.charAt(0);
Hope that helps

Categories

Resources