Exception in thread "main" java.lang.Error : String[] not initialized - java

i want to write a program as it takes input strings from the user(for example bhas1234#gmail.com) and it prints as bhas1234(leaves the characters after #) when i write the below code it shows the following error:
import java.util.*;
import java.util.Scanner;
public class Name {
public static void main(String[] args) {
Scanner take =new Scanner(System.in);
int j=0;
String[] sh;
String gmail;
for(j=0;sh[j]!="exit";j++)
{
sh[j]= take.nextLine();
int i=sh[j].indexOf('#');
gmail= sh[j].substring(0,i);
System.out.println(gmail);
}
}
}
it shows the error as
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The local variable sh may not have been initialized

You have to initialize your String array.
String[] sh = new String[numbefOfIndexes];
In Java, there is no way to use an array before having it initialized.
Keep in mind that, even if you initialize it like I did, the values by default are null as it is an array of objects, to avoid this, you can fill the array directly like below
String[] sh = {"valueOne", "valueTwo"};

Basically you want to
do endless loop (while)
read in a line of input
if it equals "exit", quit
otherwise either split at "#" and print the first part OR
find the "#" char's index and print a substring (what you did). The effects of the two methods are the same. It's only a matter of favor.

You are getting error at for loop where you are using sh[j] before it is initialized.
You should change your code to get input from user and check that as string only instead of array of string. I am giving solution as per your code only though. Update your code to:
Scanner take =new Scanner(System.in);
int j=0;
String sh;
String gmail;
while(!(sh = take.nextLine()).equals("exit"))
{
int i=sh.indexOf('#');
gmail= sh.substring(0,i);
System.out.println(gmail);
}

Related

Can anybody tell what error or where am i going wrong in code?

I am getting error while taking input with Integer.parseInt(args[0]); error is in args section i know i can change it to scanner but i want to know this method.
Can anybody point out or show the solution to my problem?
class NegativeOutputException extends Exception{
private final int ex;
NegativeOutputException(int a){
ex = a;
}
public String toString(){
return "NegativeOutputException!("+ex+")";
}
}
public class practice6_creating_custom_exception {
public static void main(String args[]){
int x = Integer.parseInt(args[0]);//Error Here argument at position one
int y = Integer.parseInt(args[1]);//argument at position two
//argument at position twenty one which doesn't exsist
int a;
try{
a = x * y;
if(a < 0)
throw new NegativeOutputException(a);
System.out.println("Output >>" + a);
}
catch(NegativeOutputException e){
System.out.println("Caught >>" + e);
}
}
}
Output::
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at practice6_creating_custom_exception.main(practice6_creating_custom_exception.java:21)
Process finished with exit code 1
It gives you a java. lang.ArrayIndexOutOfBoundsException because you are trying to access a position in an empty array.
parseInt() is not used for taking inputs in such a case you need to use Scanner
For your case, you need first take input (by using Scanner) and then assign it to an integer variable, directly parsing the argument array will not provide the input.
Scanner sc = new Scanner();
int x = sc.nextInt(); //Scans the next token of the input as an int
parseInt() function -
The parseInt() method parses a value as a string and returns the first integer.
Source
Scanner Class -
Scanner object holds the address of InputStream object present in the
System class. Input Stream object of system class reads data from the
keyboard which is byte stream/byte form. The Scanner class converts
this read byte into a specific data type.
Source
The parseInt() function cannot read data from the input stream which is byte stream/byte form, hence you cannot directly parse the args[] array and assign it to an integer variable as it is empty since it is not yet scanned.
If you are looking for different ways of taking input in Java then here they are:
Using Buffer Reader Class,
Using Scanner Class,
Using Console Class,
Using Command Line Argument,
Source
Most probably you are simply not passing any arguments.
One way to pass arguments to the main method in Java is with the command to run the application in terminal. You can simply add the arguments after the java command to run the application separating them with a space. If you want the user to input the data, then you should use Scanner instead.
In your case, navigate to the folder where your java file sits and run the following:
java practice6_creating_custom_exception 0 1
In this example, 0 and 1 are the arguments you are passing.
If you are using an IDE then this can usually be done in the run configurations.
Side note, you might need to compile the application before running it and the command for that is the following:
javac practice6_creating_custom_exception.java

How to fix ArrayIndexOutOfBoundsException in this code?

So I am trying to split my String input by /, -, and space, and within the dateConversion method, I am trying to call upon the third term in my String array called terms. If my array only has 2 elements, I receive an error, and I understand why; the issue is that even if I declare the third element of the array before I split my original input, the program still crashes. It should print out the last if statement instead.
Scanner in=new Scanner(System.in);
System.out.println(message);
String input=in.nextLine();
if(input.equals("quit"))
{
System.out.println("Bye!");
return null;
}
else
return input;
public static void dateConversion(String input){
String[] terms=new String[2];
terms[2].equals(null);
terms=input.split("-|/| ");
if(terms[2].equals(null))
System.out.println("Wrong format. Enter again.\n");
}
The program should either continue if the third term of the array exists (and it does just fine when I test it), but if it intentionally doesn't exist, the last if statement should print instead of the program crashing. Is there some other way I can declare terms[2] so it doesn't crash?
If you declare an array with two spaces like you have done --> String terms = new String[2]. Then there will be tow spaces created: terms[0] and terms[1]. The indexing starts at 0, not 1.

java error java.lang.NullPointerException

i wrote this method that will add a object to the array
but it get me this error
Exception in thread "main" java.lang.NullPointerException
i check all the variables and i think there is nothing null :((
this is my add method
}
}
the error is in the add_b() method
Exception in thread "main" java.lang.NullPointerException
at Kindergarten.add_b(Kindergarten.java:39)
at ClientClass.main(ClientClass.java:22)
You have error in Kindergarten constructor, instead of initializing arr, you are creating local variable, it should look like this:
public Kindergarten(String name, int numOfbaby) {
this.name = name;
arr = new BABY[numOfbaby];
currnt = 0;
}
secondly, you have an ininite loop, move instruction and reading of input into loop.
another issue is that you have invalid format parameters, just use plain concatenation
last, but not least you are missing System.out.println in display_all method.
loop should start like this:
Kindergarten k = new Kindergarten("baby", 10);
while (true) {
System.out
.println("what do you want to do? \n a-add a baby. \n b-search for a baby \n c-Delet a baby. \n d-Display all babys.\n e-how many babys need inoculation \n f-exit");
char f = read.next().charAt(0);
//(...)
}
First of all, initialization of arr happens only in the second Kindergarten constructor.
In the first Kindergarten constructor, arr is a local variable.
BABY arr[]=new BABY[numOfbaby];
Also, methods like setarr, setname, setcurrnt are not being used. It will be good if you can clean them up if not used.

Error using Scanner.nextLine(): Type mismatch: cannot convert from String to int

Doing some homework here (second assignment, still extremely green...). The object is to read in number x and y and provide the number in the hundreds position.
For this, I need to use int's I'd assume, as a requirement is to utilize value-returning methods.
I'm just starting to code this, however I'm hitting compile errors already:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems:
Illegal modifier for parameter anum; only final is permitted
Illegal modifier for parameter bnum; only final is permitted
Type mismatch: cannot convert from String to int at Hundreds.main(Hundreds.java:6)
Where am I going wrong?
Here is the code so far:
import java.util.Scanner;
public class Hundreds {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
private int anum,bnum;
System.out.println("Hello, for this assignment we are going to require the user to enter two distinct numbers of their choosing");
System.out.println("Please ensure the numbers are between 100 and 9999");
System.out.println("\n");
System.out.println("Please enter your first Number: ");
anum = input.nextLine();
Since those variables are local, you can't set visibility scopes to them like private, public, protected.
Move them out of the main function if you intend their scope to be larger.
anum = Integer.valueOf(input.nextLine());
You can also test to see if the next element is an int, and then give feedback to the user if it's not:
if(input.hasNextInt()) {
anum = input.nextInt();
}
Make anum string instead of int. nextLine return a string. don't use private either while defining your string within main.
Try this instead:
anum = input.nextInt();
This will still error out if you input a non-integer (try it to see the fun stack trace), but will get you past where you're at currently.
(i) Remove invalid modifiers.
(ii)Convert string to integer. So make use of anum=input.nextInt() instead of anum=input.nextLine()

readCharArray() Method is not working

I have a problem with a method which i want to use to read a complete line of characters.
First of all i'm using the following package for my method:
package chararray;
import java.util.*;
import java.util.regex.*;
import java.text.*;
public class Console
{
private static Scanner sc;
private Console()
{
}
public static char[] readCharArray()
throws NoSuchElementException, IllegalStateException
{
sc = new Scanner(System.in);
String text = sc.nextLine();
return text.toCharArray();
}
}
And that's the main code where i include the package. My compiler (BlueJ) is telling me: "incompatible types - found char[] but expected char". But normally my method should work for char[]? Any suggestions what i'm doing wrong here?
import chararray.Console;
public class kundenverwaltung
{
public static void main (String args[])
{
int nk;
System.out.print("Wie viele Kunden möchten Sie erfassen?: ");
nk = Console.readInt();
char [][] kundenregister;
kundenregister = new char [nk][4];
for (int i = 0; i < nk; ++i)
{
System.out.print("Kundennummer: ");
kundenregister [i][0] = Console.readCharArray();
System.out.print("Name des Kunden: ");
kundenregister [i][1] = Console.readCharArray();
System.out.print("Vorname des Kunden: ");
kundenregister [i][2] = Console.readCharArray();
System.out.print("Adresse des Kunden: ");
kundenregister [i][3] = Console.readCharArray();
}
}
}
Look at this line:
kundenregister[i][0] = Console.readCharArray();
The expression kundenregister[i][0] refers to a char variable - not a char array.
It's not clear what you're trying to do - and in particular why you need the values as char arrays rather than as strings - but this would make it work:
char[][][] kundenregister = new char[nk][4][];
Having a 3-dimensional array is almost always a mistake. I would strongly suggest that you refactor the code to:
Use strings instead of char arrays
Encapsulate the 4 values into a type with properties for the number, name, first name and address
Create a List<Customer> or whatever... perhaps using ArrayList<T> as the implementation. Then you don't even need to know the number of customers beforehand... the user could just hit return (or whatever) to indicate that they'd finished.
Your variable kundenregister is declared as an array of arrays of chars. That means that for each x and y, kundenregister[x][y] is a single char (the yth character of the xth array of characters). Yet you are trying to assign it an entire array of characters.
I'm not sure what your goal is here so I can't suggest an easy fix. You either want to assign the result to some index of kundenregister or declare kundenregister as a 3-dimensional array.
I'm not exactly sure what you're trying to do here so I can't offer a full solution, but the immediate problem causing the error is in your kundenverwaltung class, in the for loop.
You're trying to assign Console.readCharArray() to kundenregister[i][0], which is where the type mismatch occurs since Console.readCharArray() returns a char[], and kundenregister[i][0] is of type char.
To help you understand this: kundenregister is essentially a 2d grid, where each slot is a single char. kundenregister[i][0] refers to one of those slots, so when you write kundenregister[i][2] = x, x has to be a char otherwise it won't work.

Categories