the ouptput of a function is always equal to the inital one - java

After getting an answer from this link, I tried to make a method that returns the oldest member from a list of arrays that contains name and age of each person.
So in the main method I added those lines:
char X;
X = stat.next().charAt(0);
if(X=='a')
System.out.println(X);
oldest(nameStr, ages);
if(X=='b')
System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
if(X=='c')
System.out.println(X);
And I created the following method oldest():
public static void oldest(String[] str, int[] ageInt)
{
int maxAge=0;
String maxName="";
for(int i=1; i<ageInt.length;i++)
{
int temporary=ageInt[0];
if(ageInt[i]>temporary)
{
maxAge = ageInt[i];
maxName = str[i];
}
}
System.out.println("The listener "+maxName+ " is the oldest with an age "+maxAge);
}
But I am getting the same result:
the listener is the oldest with an age of 0
Any help is appreciated.
EDIT
I changed the if into switch case and still the same problem:
System.out.println("Please choose a, b or C:");
Scanner stat = new Scanner(System.in);
char X;
X = stat.next().charAt(0);
switch(X){
case 'a':
//System.out.println(X);
oldest(nameStr, ages);
break;
case 'b':
System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
break;
case 'c':
System.out.println(X);
break;
}

You aren't doing the correct comparison. See corrected, commented code below.
public static void oldest(String[] str, int[] ageInt)
{
int maxAge=0;
String maxName="";
for(int i=0; i<ageInt.length;i++) // start from zero
{
if(ageInt[i]>maxAge) // compare to the current max
{
maxAge = ageInt[i];
maxName = str[i];
}
}
System.out.println("The listener "+maxName+ " is the oldest with an age "+maxAge);
}

Change
if(X=='a')
System.out.println(X);
oldest(nameStr, ages);
to
if(X=='a') {
System.out.println(X);
oldest(nameStr, ages);
}
and please stick to surround if with brackets every time.

In the event the first value of ageInt[] is the greatest value, then maxAge and maxName will never be changed, since those contents are only set in the event the value of ageInt[i] is greater than the temporary value. So instead of initializing your variables via the following.
int maxAge=0;
String maxName="";
Initialize them as such:
int maxAge = ageInt[0];
String maxName = str[0];
Furthermore, ensure that you are declaring
int temporary=ageInt[0];
Outside of the for loop, otherwise you will always be setting temporary to ageInt[0], which will produce an issue if say
ageInt[0] < ageInt[1], and
ageInt[0]< ageInt[2] < ageInt[1]
As your maxAge will be set to ageInt[2] on the its iteration through the for loop. A better way to write this to avoid such an issue would be to check against your current maxAge instead of temporary.
for(int i=1; i<ageInt.length;i++){
if(ageInt[i]>maxAge){
maxAge = ageInt[i];
maxName = str[i];
}
}

Related

Why we can't initialize and access a variable based on a condition even after we type all the possibilities? [duplicate]

This question already has answers here:
Variable might not have been initialized error
(12 answers)
Closed last year.
When I type this code,
import java.util.*;
public class Example{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Input an integer : ");
int num = input.nextInt();
int y;
if(num>100){
y=200;
}
if(num<100){
y=200;
}
if(num==100){
y=200;
}
System.out.println(y);
}
}
There is an error saying "variable y might not have been initialized." Why?
This error occurs when we are trying to use a local variable without initializing it. ( accessing it in the print statement)
In your example, you have only written the if statement and compiler will not be able to detect it. To help the compiler, you can either use , the if else block which covers all the cases and it convinces the compiler or you can initialize it with value 0.
int y;
if(num>100){
y=200;
}
else if(num<100){
y=200;
}
else{
y=200;
}
System.out.println(y);
In your code, you are declaring y as a "not initialized" variable int y;. At that point, y is not defined. If you change it to int y = 0; it will be fine.
The compiler knows that an if block may not be executed. So if the variable is only initialized inside the if block, it may not be initialized at all. And that is exactly the error message.
Scanner input = new Scanner(System.in);
System.out.print("Input an integer: ");
final int LIMIT = 100; // less magic numbers
int input = input.nextInt();
int result = 0;
if(input > LIMIT){
result = 200;
}
if(input < LIMIT){
result = 200;
}
if(input == LIMIT){
result = 200;
}
System.out.println(result);
I modified your code a bit to solve the "not initialized" part. Also added a final variable for the 100 value since it is considered a good practice to name every value (no magic numbers).
You can also reduce code on this by changing the if statements a bit:
final int LIMIT = 100;
if (input == LIMIT || input < LIMIT || input > LIMIT) {
result = 200;
}
import java.util.*;
class Example{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
System.out.print("Input an integer : ");
int num=input.nextInt();
int y=0;
if(num>100){
y=200;
}
if(num<100){
y=200;
}
if(num==100){
y=200;
}
System.out.println(y);
}
}

How can i initialize an array in Java?

This is my code in java. There is a problem at System.out.println(averager(A)); . Java said that the Local variable A may not have been initialized.
import java.util.Scanner;
public class Averager {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("How many numbers do you want to average?(2-4 only");
int x;
int[] A;
x = input.nextInt();
int Array4[]={input.nextInt(),input.nextInt(),input.nextInt(),input.nextInt()};
int Array3[]={input.nextInt(),input.nextInt(),input.nextInt()};
int Array2[]={input.nextInt(),input.nextInt()};
if (x=='2'){
A =Array2;
}
else if (x=='3'){
A = Array3;
}
else if (x=='4'){
A= Array4;
}
else{
System.out.println("Error!");
}
System.out.println(averager(A)); // Error
}
public static int averager(int...numbers){
int total=0;
for(int x:numbers){
total+=x;
}
return total/numbers.length;
}
}
Look at your code and consider what happens if x is not '2', '3', or '4'. What is A as of the
System.out.println(averager(A));
line?
Right! You've never given it a value. That's what the compiler is warning you about.
Arrays in java can be initialized = null because if the code doesn't enter an if statements A is never set. Also if by chance you already know the dimensions of the array you can initialize it like this:
int[] A = new int[numberofelements];
you can change your code as
int x = input.nextInt();
int[] A= new int[x];
Your code is wrong.
It reads 9 (4 + 3 + 2) numbers always from STDIN (in Array4 to Array2 part).
What you want to do probably is
int x = input.nextInt();
int[] A = new int[x];
for ( int i = 0; i < x; ++i ) A[i] = input.nextInt();
But if you want to solve only "Local variable A may not have been initialized." warning, return (end the program) after printing the error
else {
System.out.println("Error!");
return;
}
Change: int[] A = null;
Change : int x to int x = 0;. You need to initialize variables in java.

Java search if a string exists

I am trying to determine if the user entered value already exists in the current array, how to do that?
User entered value to check the variable is
accno and the array to compare to is accnums
This is what i am currently working on
public class Randomtopic {
static BigDecimal[] accbal = new BigDecimal[20];
static Integer[] accnums = new Integer[20];
public static void main(String[] args) {
displayMenu();
}
public static void displayMenu() {
int option, accno;
double accbal;
Scanner sc = new Scanner(System.in);
System.out.println(" Add an account");
System.out.println("Search an account with the given account number");
System.out.print("Enter Your Choice: ");
option = sc.nextInt();
switch (option) {
case 1:
System.out.println("You have choosen to add account");
addAccount();
break;
case 2:
System.out.println("You have choosen to search for an account");
System.out.print("Enter the Account Number: ");
accno = sc.nextInt();
System.out.println(search(accno, accnums));
break;
default:
System.out.println("Please choose an appropriate option as displayed");
}
displayMenu();
}
public static void addAccount() {
//String accno;
int i = 0;
int accno, input;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
//BigDecimal[] accbal= new BigDecimal[20];
Scanner sc = new Scanner(System.in);
//String[] accnums = new String[20];
int j;
System.out.print("Enter the account number: ");
accno = sc.nextInt();
if (String.valueOf(accno).matches("[0-9]{7}")) {
System.out.print("Enter account balance: ");
accbala = sc.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null )
break;
else if(accnums[j].equals(accno))
{
System.out.println("Account already exists");
}
}
//System.out.print(j);
if (j == accnums.length) {
System.out.print("Account storage limit has reached.");
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
}
input = accnums[0];
System.out.println("The value: " + input + " witha a balance of " + accbal[0].toString());
} else {
System.out.println("Wrong NRIC");
}
displayMenu();
}
public static String search(int accnum, Integer[] numbers) {
// Integer[] numbers;
//int key;
//numbers = accnums;
// System.out.print("Enter the Account Number: ");
for (int index = 0; index < numbers.length; index++) {
if (numbers[index].equals(accnum)) {
return String.valueOf(index);
// System.out.println("The account number exists in this array index :"+index);//We found it!!!
}
break;
}
return "-1";
}
}
So my problem?
When i enter the accnum for the first time itself i am getting NullPointerException. Tks
When you instantiate or create an array, the values are by default set to null; whenever you iterate over an array of possibly null values, it is required you skip these. For example,
for(loop conditions)
if (numbers[index] != null && (numbers[index].equals(accnum))) {
return String.valueOf(index);
//your text goes here;
}
break;//I suggest you take this line out of your original code. Your for loop will end this once you have iterated through the entire array, or you will automatically break out if you find the value.
}
If you must use an array, then this is the best way to iterate through it. The parenthesis and the && in the if clause prevent you from performing the .equals check if the value of numbers[index] == null - in turn, preventing the null error from being thrown. your only alternative would be to set every value in the numbers[ ] to 0, or some other value, and than skip that value when you iterate. Such would be done with a static final int. However, this is not ideal coding.
Ideally, you should use an ArrayList - you can then not only make this more efficient, but also, much more readable.
Your accnums is filled with null values. Check if they are not null. I suppose your NullPointerException is thrown from search method.
If I understood your code correctly you have a number of accounts with associated balance identified by an account number. In this case I would use a Map instead of fiddling with arrays.
when you run your method search first time, yours array accnums is filled with null value so when you call line if ( numbers[index].equals(accnum)) you are trying call equal method on null object
what you can do is change your accnums from array to list, and then size will depends on number elements, so it wont have fixed size like your arrays
The problem in your code without adding anything in your accnum you are searching.So your accnum contains NULL values.if you change your accnum array into list/hashmap the exception would not arise.

How to check if array indexes are empty and if so check the next?

Anybody got any idea on how I can check if an array indexes(not just one index) are empty and if is empty or zero put a value there. And also if all the indexes are all not empty print an error.
Sorry unfortunately I can't give rep.
import java.util.Scanner;
public class Myhash {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] myData = new int[17];
int [] newData = new int [17];
System.out.println("Please enter 16 integer numbers");
for(int i= 0; i<myData.length; i++){
//System.out.print("Please enter 16 numbers");
Scanner input = new Scanner(System.in);
int data =input.nextInt();
myData[i]=data;
int num3 = data % 17;
newData[num3]=data;
}
System.out.println("These are the numbers you entered\n");
System.out.printf("%s%8s \n", "Index", "Value");
for(int t=0; t<myData.length; t++){
System.out.printf("%5d%8d\n", t, myData[t]);
}
System.out.println("\n");
System.out.println("The Hash Function:\n\n");
System.out.printf("%5s%8s \n", "Index", "Value");
for(int s=0; s<newData.length; s++){
System.out.printf("%5d%8d\n", s, newData[s]);
}
}
}
on here:
for(int s=0; s<newData.length; s++){
System.out.printf("%5d%8d\n", s, newData[s]);
}
how do check for more than one index(if empty?
If the index is empty how do check for the next index and if that one is not empty how do i check the next one, etc?
Elements in primitive arrays can't be empty. They'll always get initialized to something
If you declare the array like so
int [] newData = new int [17];
then all of the elements will default to zero.
For checking if an element is not entered, you can use a simple loop :
for(int i=0;i<newData.length;i++)
{
if(newData[i]==0)
System.out.println("The value at " + i + "is empty");
}
Although , the above code will not work in your case, because the user might enter 0 as an input value and still this code will consider it to be empty.
What you can do is, initialize the array with all values as -1, and specify at the input prompt that only values >=0 can be entered .
The initialization can be done like this:
int[] newData = new int[17];
for(int i=0;i<newData.length;i++)
{
newData[i]= -1;
}
Then you can ask the user for input and do the processing. Then you can use this:
for(int i=0;i<newData.length;i++)
{
if(newData[i]==-1)
System.out.println("The value at " + i + "is empty");
}
Here:
for(int i = 0; i < array.length; i++)
{
if(array[i] == null)
continue;
}

CommandLine Java Calculator

I've just learned java but from my old experience coming from C++ I thought that I can write a commandline calculator which supports all 4 basic operators with just one line. But I am having a bit of problem.
This is my code:
import java.util.Scanner;
public class omg {
public static void main(String args[]) {
int fnum,snum,anum = 0;
String strtype; //The original calculation as string
char[] testchar; //Calculation as chararray
char currentchar; //current char in the char array for the loop
int machinecode = 0; //Operator converted to integer manually
String tempnumstr; //first and second numbers temp str to be converted int
int operatorloc = 0; //operator location when found
char[] tempnum = new char[256];
Scanner scan = new Scanner(System.in); // The scanner obviously
System.out.println("Enter The Calculation: ");
strtype = scan.nextLine();
testchar = strtype.toCharArray(); //converting to char array
for (int b = 0; b < testchar.length; b++) //operator locating
{
currentchar = testchar[b];
if (currentchar == '+') {
machinecode = 1;
operatorloc = b;
}
else if (currentchar == '-') {
machinecode = 2;
operatorloc = b;
}
else if (currentchar == '*') {
machinecode = 3;
operatorloc = b;
}
else if (currentchar == '/') {
machinecode = 4;
operatorloc = b;
}
}
for(int t = 0; t < operatorloc; t++) { //transferring the left side to char
tempnum[t] = testchar[t];
}
tempnumstr = tempnum.toString(); //converting char to string
fnum = Integer.parseInt(tempnumstr); //parsing the string to a int
for (int temp = operatorloc; temp < testchar.length; temp++) { //right side
for(int t = 0;t<(testchar.length-operatorloc);t++) {
tempnum[t] = testchar[temp];
}
}
tempnumstr = tempnum.toString(); //converting to char
snum = Integer.parseInt(tempnumstr); //converting to int
switch(machinecode) { //checking the math to be done
case 1:
anum = fnum + snum;
break;
case 2:
anum = fnum - snum;
break;
case 3:
anum = fnum * snum;
break;
case 4:
anum = fnum / snum;
}
System.out.println(anum); //printing the result
}
}
This is my code but when I run it it will ask me the calculation and then give this error.
Exception in thread "main" java.lang.NullPointerException
at omg.main(omg.java:38)
There might be a better and easier way of doing this. I would like to hear both a better way and a fix for my way. Thanks in advance
You declare:
char[] tempnum = null;
But where do you set it = to a non-null value? So any time you try to use it as if it were a fully actuated object, you'll get a NPE thrown.
Edit: there are other issues in your code including calling toString() on an array which will return array's default toString -- not what you want in that situation.
So rather than this:
tempnumstr = tempnum.toString();
You probably want something like this:
tempnumstr = new String(tempnum);
or possibly
tempnumstr = new String(tempnum).trim(); // get rid of trailing whitespace if needed
Edit 2: You appear to have two char arrays in your program, tempnum and testchar, one that you fill with chars and one you don't. What is the purpose of both of them? Consider peppering your code with some comments too so we can understand it better and better be able to help you.
Hovercraft Full Of Eels has already pointed you to the reason for the NullPointerException. In addition to that, I see quite a few things that could be improved in your code. Here's how I'd do it:
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
System.out.println("Please enter your calculation");
Scanner scanner = new Scanner(System.in);
int left = scanner.nextInt();
String op = scanner.next();
int right = scanner.nextInt();
System.out.println(compute(left, op, right));
}
private static int compute(int left, String op, int right) {
switch (op.charAt(0)) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
}
throw new IllegalArgumentException("Unknown operator:" + op);
}
}
Note that the Scanner assumes there is whitespace before and after the operator.
Example output:
Please enter your calculation
1 + 2
3
The improvements in detail:
Variables may be declared where you first use them. It is customary in Java to take advantage of that (shorter code size, no need to repeat the variable name.)
Scanner provides tokenizing in addition to reading the entire line. No need to reinvent the wheel.
char (being an integer type) can be switched on.
Your problem is this line:
tempnum[t] = testchar[t];
Which will throw a NullPointerException as you previously declared it as null: char[] tempnum = null;
You need to change it to char[] tempnum = new char[size]; which will initialise it to an empty array to hold type char. Where size is any integer.
char[] tempnum = null;
should be set to something like
char[] tempnum = new char[4];
basically it is null when used at line 38.
On line 38 you try to acces the variable tempnum which is initialized to null you have to initialize the variable tempnum like this:
tempnum = new char[n]
where n will be the length of the array
You forgot to allocate tempNum which results in a NUllPointerException when you try to use it in an array context.
char[].toString() won't do what you expect (it returns a hashcode for the array object), to create a string using the contents of the array use new String(char[]).
First of all, it error at this line: tempnum[t] = testchar[t];
Reason: tempnum have not point to any thing (null)
Fix: tempnum = testchar; or tempnum = new char[testchar.length]

Categories