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.
Related
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);
}
class address
{
String address;
String newaddr = address.trim();
final int ziplength =4;
String input;
Scanner in = new Scanner(System.in);
String temp = in.next();
String zipcode = input.substring(input.length()-ziplength);
try **//illegal start type error**
{
Integer.parseInt(zipcode);
System.out.println("PO is: "+zipcode);
}
catch( Exception e) **//illegal start type error**
{
System.err.println("Last 4 chars are not a number.");
}
}
This code segment extract the last four characters from a string, and see if they are post code.
I have commented the point reporting "illegal start type error" in NetBeans.
I wonder, if I cannot use try-catch when creating a class? Or, do this class miss something?
I tried searching stackoverflow. But I am still confusing. Here are some links.
Java illegal start of type
Java error: illegal start of expression
java: Why does the program give "illegal start of type" error?
Java does not allow you to simply put statements in the body of a class. You always need an enclosing "block" around those statements.
In other words: the easiest way to a first working example would be to add a main method to your class and to move your code in there. Meaning a method with signature public static void main(String[] args)
Beside that: don't "wait" until several errors come together. Start with an empty class. Enter one new construct in there. Save; run the compiler. Go for the next "element" that you need.
For a beginner, your strategy (lets write 10, 20 lines of code; and then lets hope it works) will not work at all. You are wasting your time (and ours) by doing it like that. You see, this is so basic stuff that you should not turn to other people to explain them to you. You should start small and figure all these things yourself. Because that is the essence of learning programming.
class address
{
String address;
String newaddr = address.trim();
final int ziplength =4;
String input;
Scanner in = new Scanner(System.in);
String temp = in.next();
String zipcode = input.substring(input.length()-ziplength);
public address() //this is the only thing I add, but it eliminate "illegal start type error"
{
try
{
Integer.parseInt(zipcode);
System.out.println("PO is: "+zipcode);
}
catch( Exception e)
{
System.err.println("Last 4 chars are not a number.");
}
}
}
Special thank you for #Jägermeister . He gives me valuable hint.
Since I am a beginner, I am thinking a better way to improve my skills. I will try more.
I am making a decryption program and I'm not quite sure how to use the variable "cip" out side of my try catch block. I tried moving the 3 lines of where is asks user to input pattern but i ran into other problems.
my code is:
import java.util.*;
public class unscrambler //This class will encrpyt the program
{
public static void main (String [] args){
int cip= 0;
String user ="";
System.out.println("Please enter the code to unscramble");
Scanner inputScanner = new Scanner(System.in); //imports scanner reader
String userinput = inputScanner.next();
char[] charArray = userinput.toCharArray(); //sends userinput to charArray
int j=charArray.length;
Character [] array = new Character[j];
for(int w=0; w<j; w++){
array[w] = charArray[w];
}
int a=1;
System.out.println("Please enter the number cipher pattern (an integer)");
do{
try{
user = inputScanner.next();
cip = Integer.parseInt(user);
a=2;
System.out.println("your code is ");
for(int w =0; w<j;){
System.out.println(charArray[j]);
w+=cip;
}
if(cip<=0){
System.out.println("please enter number greater than zero");
a=1;
}
}catch(NumberFormatException f){
System.out.println("please enter a proper number");
}
}while(a==1);
}
}
You're only making the declarations in that block.
String user = inputScanner.next();
int cip = Integer.parseInt(user);
Add these to the start of the file, just after the main() line:
int cip = 0;
String user = "";
The errors after just moving (without the = stuff) indicate that you're using cip after the try block, so we need to initialise it with empty data in case the try fails.
Now just change the lines that you've currently got in the try block to:
// Remove the 'String' part.
user = inputScanner.next();
// Remove the 'int' part.
cip = Integer.parseInt(user);
And then you can move on to the next unrelated bug.
The solution is to either move the variable declaration outside of the loop, or move the place you want to use it inside the loop.
Java doesn't allow you to use a local variable outside of the scope in which it was declared. Period.
I tried moving the 3 lines of where is asks user to input pattern but i ran into other problems.
Well ... you need to solve those other problems!
Programming is like this. You need to work within the constraints of the programming language that you are using.
I can see what is causing your latest error, but I'm not going to tell you what it is. Instead, I'm going to tell you how to find it for yourself.
The "line upon line of output" is a Java Stacktrace. It contains A LOT of useful information, and you need to learn how to interpret it.
java.lang.ArrayIndexOutOfBoundsException: 5
at unscrambler.main(unscrambler.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Stacktraces typically report an exception that has been thrown somewhere in your running program.
Step 0: Find the stacktrace.
The first line gives the name of the exception, and the message. In this case, the name of the exception is ArrayIndexOutOfBounds and the message is (just) "5".
Step 1: If you don't recognize the name of the exception, look it up in the javadocs.
Here it is: link. Read it now.
Step 2: Try to understand the message. In this case, you just need to know that the message is the value of the index that was out of range. But you should be able to guess that ... based on the javadoc for the exception. (Usually the messages are a bit more informative, but this one is being thrown from compiled code, and for technical reasons a more informative error would be difficult to produce.)
The second line of the stacktrace tells you where the exception was thrown. In this case, line 35 of "unscrambler.java" ... in the main method.
Step 3: Open the source file in an editor or your IDE, and see what the code at that line says.
In this case it is (I think) this line:
System.out.println(charArray[j]);
Step 4: Now you have to start thinking. (Thinking is a very important part debugging!) How can that line have possibly thrown that exception? What could have caused that?
In this case, the first think to observe is that there is only one place on that line where you are doing array indexing, and it is the expression charArray[j]. So that means that ... (you fill in the details). But were did ... (you fill in the details) come from? Take a look at what happened before this statement. See it yet? (If no, then look again. It should be really obvious if you look carefully!)
The rest is for you to sort out ... :-)
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()
I am learning JAVA and trying to write my first loop. The loop should prompt the user to guess a defined name.
The code is not performing right. I have tried to search for help on different JAVA tuturials both not found any examples where you guess a name/string but a lot where you should guess a number.
This is my code:
/**
*
* #author mso_
*/
import java.util.Scanner;
public class GuessName {
/**
* #param args the command line arguments
*/
public static final int C_Max_Trials = 10;
public static void main(String[] args) {
//Define correct name
String name = "Morten";
String guessName;
//Create a scanner
Scanner guess = new Scanner(System.in);
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
String guessName = guess.next(); <-- ERROR
//Create loop
} while (guessName != name); <-- ERROR
System.out.println("Sorry, wrong guess, please enter another guess: ");
if (guessName = name); <-- ERROR
System.out.println("Right on! ");
}
}
What have I done wrong?
String comparison
You can't compare Strings like this. This will only compare the references. You must use the equals() method :
while (! guessName.equals(name));
A little explanation : http://www.zparacha.com/java-string-comparison/
Variable redeclaration
There is another error in your code, you try to redeclare guessName inside the loop. You must declare guessName only once outside of the loop (ie before the do {).
General mistakes
Thirdly, there's a some other errors in your code. I think all of them were pointed out in the others answer, but I'll do a quick list :
if (guessName = name); This is a useless statement as is, you must open a block : if(condition) { statement; }
Same line, your doing an assignment, not a comparison, and like said, with String you must use .equals()
The System.out.println() won't be executed when you think. Re-read the doc about do { } while() loop until you really understand them.
My advise : read carefully the error message of your compiler and read some doc before writing code.
What errors?
Use .equals when comparing strings
You are using the assignment operator and not the equivalence operator at
if (guessName = name)
you need to do
if(guessName.equals(name)) instead.
You're comparing references (well, with guessName = name, you're actually assigning a value to guessName). Use String.equals() instead of == and !=.
you are comparing two objects. Not two string values.
use equals
That won't compile for a start - you declare String guessName on the third line of the main method, and then declare the same variable again within the do loop. You should simply use the name of the variable to assign to it:
guessName = guess.next();
Because of this error, presumably your IDE's compiler doesn't see the variable at all, so the subsequent lines that refer to guessName are also flagged as errors. Fixing this first line should clear those up, unless there's another problem lying there that I've missed.
Among other things there is a wrong semicolon after the if:
if (name.equals(guessName)) //removed the semicolon and use .equals
System.out.println("Right on! ");
and it's an assignment instead of a comparison as other answers state by now.
Try this
public class GuessName {
/**
* #param args the command line arguments
*/
public static final int C_Max_Trials = 10;
public static void main(String[] args) {
//Define correct name
String name = "Morten";
String guessName = null;
//Create a scanner
Scanner guess = new Scanner(System.in);
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
guessName = guess.nextLine(); <-- ERROR
if(!guessName.equals(name))
{
System.out.println("Sorry, wrong guess, please enter another guess: ");
}
//Create loop
} while (!guessName.equals(name)); <-- ERROR
if (guessName.equals(name)) <-- ERROR
System.out.println("Right on! ");
}
}
The line String guessName = guess.next(); needs to be changed to:
guessName = guess.next();
Because "guessName" is already defined earlier.
Additionally, when you compare strings you need to use the method equals and not the operator ==. So } while (guessName != name); should be:
} while (!guessName.equals(name));
And if (guessName = name); should be changed to:
if (guessName.equals(name))
Here is what the javac compiler says:
GuessName.java:26: guessName is already defined in main(java.lang.String[])
String guessName = guess.next(); //<-- ERROR
^
GuessName.java:32: incompatible types
found : java.lang.String
required: boolean
if (guessName = name);// <-- ERROR
^
2 errors
For the first one, you should not declare another local variable: drop the String. For the second, use .equals to compare String objects, as the doc says.
You will obtain something like that:
...
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
guessName = guess.next(); //<-- FIXED
//Create loop
} while (!guessName.equals(name)) //<-- FIXED
if (guessName.equals(name))// <-- FIXED
System.out.println("Right on! ");
}
...
which works correctly.
The strings must be compared using the equals method.