I am trying to search for an int value in an array that has random numbers
this is what I have so far:
String names[]={"Peter","John","Rudy"};
int number[]=new int[3];
for(int z=0;z<3;z++)
{
number[z]=(int)(1+Math.random()*200);
}
int option=Integer.parseInt(JOptionPane.showInputDialog("choose and option:\n1.names\n2.sorting according to alphabet\n3.search number\n4.J"));
switch(option)
{
case 1:
{
for(int l=0;l<names.length;l++)
{
jTextArea1.append(""+names[l]+"\t"+number[l]+"\n");
}
}
break;
case 2:
{
String temp="";
for(int ii=0;ii<names.length;ii++)
{
for(int j=0;j<names.length;j++)
{
if(names[ii].compareToIgnoreCase(names[j])<0)
{
temp=names[ii];
names[ii]=names[j];
names[j]=temp;
}
}
}
for(int x=0;x<names.length;x++)
{
jTextArea1.append(""+names[x]+"\n");
}
}
break;
case 3:
{
boolean found=false;
int searchvalue=Integer.parseInt(JOptionPane.showInputDialog("number?"));
for(int i=0;i<number.length;i++)
{
if(number[i]==searchvalue)
{
found=true;
}
}
if(found==true)
{
jTextArea1.append("number is found"+"\n");
}
else
{
jTextArea1.append("number is not found"+"\n");
}
}
break;
case 4:
{
for(int q=0;q<names.length;q++)
{
if(names[q].startsWith("J"))
{
jTextArea1.append(names[q]);
}
}
}
}
Even when I type the correct answer it gives me the "number is not found" message.I'm dumbfounded on what to do.Any help will be greatly appreciated.
Try something like this. I am not sure if this is exactly what you are looking for...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean found = false;
int searchvalue;
int[] lottoNumber = new int[6];
lottoNumber[0] = (int) ((56 * Math.random()) + 1);
lottoNumber[1] = (int) ((56 * Math.random()) + 1);
lottoNumber[2] = (int) ((56 * Math.random()) + 1);
lottoNumber[3] = (int) ((56 * Math.random()) + 1);
lottoNumber[4] = (int) ((56 * Math.random()) + 1);
lottoNumber[5] = (5);
System.out.print("number?");
searchvalue = input.nextInt();
for (int i = 0; i < lottoNumber.length; i++) {
if (lottoNumber[i] == searchvalue) {
found = true;
}
}
if (found == true) {
System.out.print("number is found" + "\n");
} else {
System.out.print("number is not found" + "\n");
}
}
}
This does not have GUI imports in this by the way.What exactly are you trying to do with this? Can you add the whole code?
Well the answer above works for me! So the answer is your :
int searchvalue=Integer.parseInt(JOptionPane.showInputDialog("number?"));
That line is probably causing the problem.
Try adding:
System.out.println("The number entered was:"+searchvalue);
and then compare it to the number you entered.
Related
public class Testfor
{
public static int ArrayChallenge(int[] arr)
{
int[] temp = new int[arr.length - 1];
int diff = 0;
for (int i = 0; i < arr.length - 1; i++)
{
diff = Math.abs(arr[i] - arr[i + 1]);
temp[i] = diff;
}
arr = temp;
for (int i:arr)
{
System.out.println(i);
}
if (arr.length > 1)
{
ArrayChallenge(arr);
}
else
{
diff = arr[0];
System.out.println("diff" + diff);
}
return diff;
}
public static void main(String[] args)
{
// keep this function call here
//Scanner s = new Scanner(System.in);
System.out.println("answer:" + ArrayChallenge(new int[] { 5, 7, 16, 1, 2 }));
}
}
Here the input is an array of integers finally the array should be reduced to the size of one element by finding the absolute difference between two elements.
I am using recursion to solve this but I am getting 1 as the answer can someone please someone help to solve it?
input:[5,7,16,1,2]
[2,9,15,1]
[7,6,14]
[1,8]
[7]--->the array should reduce in the following manner to get an answer and finally should return the last element
output:7
Just preserve the return value
public class Testfor
{
public static int ArrayChallenge(int[] arr)
{
int[] temp = new int[arr.length - 1];
int diff = 0;
for (int i = 0; i < arr.length - 1; i++)
{
diff = Math.abs(arr[i] - arr[i + 1]);
temp[i] = diff;
}
arr = temp;
for (int i:arr)
{
System.out.println(i);
}
if (arr.length > 1)
{
diff = ArrayChallenge(arr);
}
else
{
diff = arr[0];
System.out.println("diff" + diff);
}
return diff;
}
public static void main(String[] args)
{
// keep this function call here
//Scanner s = new Scanner(System.in);
System.out.println("answer:" + ArrayChallenge(new int[] { 5, 7, 16, 1, 2 }));
}
}
I am taking CS50, and I completed the first week problem of implementing the Luhn Check algorithm. Although my solution works, I feel it's very sloppy and not efficient. Can someone please suggest how I can improve my solution. (It's a first week problem; you are not intended to use arrays or functions.)
Here is the code:
#include<stdio.h>
#include<stdlib.h>
#include<cs50.h>
int main()
{
long long x,j=0;
int len,i,len_flag,flag=0,flag_val=0,sp_len=0,check_flag=0; //basic integers related to loop etc
int res,sum,fin_sum=0,h=0,d2_sum=0,d1_sum=0,ff_num=0; // variables related to extracting numbers
int sum_len=0,in_sum=0,in_fsum=0,len_sum=0,m=0; // extraing numbers from more than single sum result
int sum_f=0,sum_final=0;
do{
x = get_long("enter a valid card number \n");
j=x;
len_flag = 0;
len = 0;
while(len_flag!=1)
{
x = x / 10;
if(x==0)
{
len_flag = 1; //finding the lenght of the number
}
len++;
}
if(len==15||len==16||len==13)
{
flag = 1;
sp_len =1;
}
else
{
flag=1;
}
}while(flag!=1);
for(i=0;i<len;i++)
{
res = j % 10;
j = j / 10;
if(i%2!=0)
{
sum = res * 2;
//printf("multi_res : %d \n",sum);
len_flag = 0;
sum_len = 0;
len_sum = sum;
while(len_flag!=1)
{
len_sum = len_sum / 10;
if(len_sum==0)
{
len_flag=1; // checking if the sum is more than single digit
}
sum_len++;
//printf("trig\n");
}
if(sum_len>1)
{ x=0;
while(x<sum_len)
{
in_sum = sum % 10;
sum = sum/10;
in_fsum = in_fsum + in_sum;
//printf("double sum : %d \n",in_fsum);
x++;
}
}
fin_sum = fin_sum + sum;
}
if(i==len-1)
{
for(h=0;h < 1;h++)
{
fin_sum = fin_sum + in_fsum;
}
d1_sum = res;
}
else if(i%2==0)
{
sum_f = sum_f + res; // adding up the number that where not x2
}
if(i==len-2)
{
d2_sum = res; //5555555555554444
}
}
sum_final = sum_f + fin_sum;
//printf("sum_final : %d\n",sum_final);
//printf("sum_f_final : %d\n",sum_f);
//printf("sum_in_final : %d\n",fin_sum);
if(sum_final%10==0)
{
flag_val=1; // checking if the number is valid
}
if(ff_num == 0)
{
ff_num = (d1_sum*10) + d2_sum; //flip
}
do
{
if(sp_len==0)
{
printf("INVALID\n");
check_flag=1;
break;
}
if((flag==1&&flag_val==1&&ff_num==34)||ff_num==37)
{
printf("AMEX\n");
check_flag=1;
break;
}
else if(flag==1&&flag_val==1&&ff_num>50&&ff_num<56)
{
printf("MASTERCARD\n");
check_flag=1;
break;
}
else if(flag==1&&flag_val==1&&d1_sum==4)
{
printf("VISA\n");
check_flag=1;
break;
}
else
{
printf("INVALID\n");
check_flag=1;
break;
}
}while(check_flag!=1);
return 0;
}
I felt like I was fixing a leak while writing the code. I would try to correct one thing, and another thing would go wrong, and this is the final result.
I need to write a function that receives the number generated in fillArray and determine if it has already been generated. I need to return a true or false thus determining if the random number must be put into the array.
Here's what I am working on. Thanks for any help. I've searched for anything similar but unfortunately cannot find anything.
public class RandomGenerator {
int Arr[] = new int[6];
int size;
public void fillArray() {
int randNum = (int) (Math.random() * 49) + 1;
for (int i = 0; i < size; i++) {
Arr[i] = randNum;
alreadyThere(randNum);
}
size++;
}
public int alreadyThere(int randNum) {
int find = randNum;
boolean found = false;
int i = 0;
while (!found && i < size) {
if (Arr[i] == find) {
found = true;
}
i++;
}
if (!found) {
}
return randNum;
}
The purpose of this code is is to define the root of the sum of the squares.
I cant figure out how to put i into j. Please help.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int input, som, i=0;
int j = 0;
double answer;
Boolean gaDoor= true;
int [] array = new int [24];
while (gaDoor)
{
Console.Write("Specify a positive integer");
input = Convert.ToInt32(Console.ReadLine());
if (input == -1)
{
gaDoor = false;
}
else
{
if (input >= 0)
{
array[i] = input;
i++;
}
else
{
Console.WriteLine("Specify a positive integer ");
}
}
}
while (j<i)
{
sum = array [j] ^ 2;
answer = Math.Sqrt(sum);
Console.Write(answer);
}
Console.ReadKey();
}
}
}
using System;
namespace Test
{
class MainClass
{
public static void Main (string[] args)
{
int[] invoer = new int[24];
double[] resultaat = new double[24];
double totaal = 0;
double wortel = 0;
int commando = 0;
int teller = -1;
try {
// Keep going until a negative integer is entered (or a 0)
while ((commando = Convert.ToInt32 (Console.ReadLine ())) > 0) {
teller++;
invoer [teller] = commando;
}
} catch (FormatException) {
// Not a number at all.
}
teller = -1;
foreach (int i in invoer) {
teller++;
resultaat [teller] = Math.Pow (invoer [teller], 2);
totaal += resultaat [teller];
if (invoer [teller] > 0) {
Console.WriteLine ("Invoer: {0}, Resultaat: {1}", invoer [teller], resultaat [teller]);
}
}
wortel = Math.Sqrt (totaal);
Console.WriteLine ("Totaal: {0}, Wortel: {1}", totaal, wortel);
}
}
}
I am planning to make an airline system. I have initialized the array using initSeats but it still throws back the NPE error. It happens when i call the seatChecker() from bookMenu.
public void initSeats(){
for(int b = 0; b < seatList.length; b++)
{
initC.setName("null");
initC.setEmail("null");
initC.setCreditNo(0);
initC.setAddress("null");
initC.setPassportNo("null");
seatList[b] = new Seat('A', 0, "null", 0.0, "Available", initC);
}
for(int d = 0; d <= 24; d++)
{
seatList[d].setSeatLetter('A');
seatList[d].setSeatNo(d);
}
for(int n = 25; n <= 48; n++)
{
seatList[n].setSeatLetter('B');
seatList[n].setSeatNo(n);
}
for(int m = 49; m <= 72; m++)
{
seatList[m].setSeatLetter('C');
seatList[m].setSeatNo(m);
}
for(int t = 73; t <= 96; t++)
{
seatList[t].setSeatLetter('D');
seatList[t].setSeatNo(t);
}
for(int q = 97; q <= 120; q++)
{
seatList[q].setSeatLetter('E');
seatList[q].setSeatNo(q);
}
for(int v = 121; v < 144; v++)
{
seatList[v].setSeatLetter('F');
seatList[v].setSeatNo(v);
}
for(int x = 0; x <= 48; x++)
{
seatList[x].setSection("Front");
seatList[x].setPrice(500);
}
for(int j = 49; j <= 96; j++)
{
seatList[j].setSection("Middle");
seatList[j].setPrice(250);
}
for(int u = 97; u < 144; u++)
{
seatList[u].setSection("Back");
seatList[u].setPrice(100);
}
}
public void seatChecker(int index)
{
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available")){
System.out.println("Seat is Available.");
}else{
System.out.println("Seat is not Available. Please Pick Another Seat.");
bookMenu();
}
}
public void bookMenu()
{
int choice1 = 0;
int index;
System.out.println("Where do you want to be seated?");
System.out.println("[1] Front");
System.out.println("[2] Middle");
System.out.println("[3] Back");
choice1 = sc.nextInt();
sc.nextLine();
if(choice1 == 1){
System.out.print("Choose a seat number (0 - 48): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 2){
System.out.println("Choose a seat number (49 - 96): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 3){
System.out.println("Choose a seat number (97 - 144): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else
{
System.out.println("Invalid Choice. Going back to Menu.");
MainMenu();
}
}
Null Pointer Exception Code
Exception in thread "main" java.lang.NullPointerException
at pkg.Airlines.AirlineUI.seatChecker(AirlineUI.java:132)
Seat Class
public class Seat{
private char seatLetter;
private int seatNo;
private String section;
private double price;
private String status;
private Customer customerDetails;
public Seat(char seatLetter, int seatNo, String section, double price, String status, Customer details)
{
this.seatLetter = seatLetter;
this.seatNo = seatNo;
this.section = section;
this.price = price;
this.status = status;
this.customerDetails = details;
}
public Customer getCustomerDetails() {
return customerDetails;
}
public void setCustomerDetails(Customer customerDetails) {
this.customerDetails = customerDetails;
}
public char getSeatLetter() {
return seatLetter;
}
public void setSeatLetter(char seatLetter) {
this.seatLetter = seatLetter;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSeatNo() {
return seatNo;
}
public void setSeatNo(int seatNo) {
this.seatNo = seatNo;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
}
Probably the problems are this two line :
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available"))
First thing could be seatList[index] is not initialized . Once you declare an array of references as :
Seat[] array = new Seat[10];
The array contains 10 null references for Seat object . You need to instantiate them before using them :
Seat[0] = new Seat();
Second potential problem will be, this check :
if(status.equalsIgnoreCase("Available"))
Replace it to :
if("Available".equalsIgnoreCase(status))
to avoid any NullPointerException in case status is null.
P.S. Please show us the Seat class to understand your problem better.
Well is quite simple resolve a Null Pointer Exception.
Probably in one of the index of seatList there isn't a value.