Can you please help me with this. I need to find a value in array and if there is no such a value make an exception about it.
i did wth if else in a loop it is print 4 time NOT FOUND. Thank you very much.
public class Search {
public static int arraySearch(int [] array, int value){
for(int i = 0; i < array.length; i++){
if(array[i] == value){
System.out.println(value);
}
}
}
public static void main(String[] args) {
int [] array = { 23, 6, 9, 10};
arraySearch(array, 6);
}
}
As I pointed out in the comments, throwing an exception when searching for a missing element in an array is not really the best solution, but in another comment you say this is a requirement, so here it goes.
There are a couple of things we need to do
A custom exception we're going to throw, because there's no exception in the standard library for "I have not found an element in an array", and for good reason;
The arraySearch method needs to declare it throws the exception
The arraySearch method should return a value, not print it
If no value is returned (i.e. if we reached the end of the loop and have not returned yet) arraySearch should throw our custom exception
main needs to catch the exception and act accordingly
Here's the code. Be sure to understand it, don't just copy and paste it.
public class Search {
private static class ElementNotFoundException extends Throwable {}
public static int arraySearch(int [] array, int value) throws ElementNotFoundException {
for(int i = 0; i < array.length; i++){
if(array[i] == value){
return value;
}
}
throw new ElementNotFoundException();
}
public static void main(String[] args) {
int [] array = { 23, 6, 9, 10};
try {
System.out.println(arraySearch(array, 60));
} catch (ElementNotFoundException e) {
System.out.println("Element not found");
}
}
}
Finally, I suspect you misunderstood your homework and you actually need to return the index of the element you found, not its value (which is not very useful). I'll leave that as an exercise for you to solve.
This is one approach. The actual exception throwing can be built in.
public class Search {
public static int arraySearch(int[] array, int value) {
int result = -1;
for (int i = 0; i < array.length && result < 0; i++) {
if (array[i] == value) {
// Found! We want to know the index. We know the value
result = i;
}
}
return result;
}
public static void main(String[] args) {
int[] array = { 23, 6, 9, 10 };
System.out.println(arraySearch(array, 6));
}
}
Related
I'm trying to implement a java code to test linear search on a sorted array and this is my code
public class ArrayTest {
public static void main(String [] args) {
int []x= {12,8,6,23,6,5,17,20,9};
int y =linearSearch(x,23);
}
public static int linearSearch(int []ar,int value) {
int searchedIndex=-1;
for(int i=0;i<ar.length;i++) {
if (ar[i]==value) {
searchedIndex=i;
break;
}
}
return searchedIndex ;
}
}
The problem is that this doesn't generate any output also no errors were generated. Can anyone explain the reason for this.
In order to print something to the output,you must use System.out.println() function.The answer is returned to the variable y.Just print the variable to the console output.Moreover,the array is not sorted.But,that doesn't make any problem to it.
Something like this:
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args) {
int[] x = {12, 8, 6, 23, 6, 5, 17, 20, 9};
// Arrays.sort(x);
int y = linearSearch(x, 23);
System.out.println("" + y);
// int z = Arrays.binarySearch(x, 23);
// System.out.println("" + z);
}
public static int linearSearch(int[] ar, int value) {
for (int i = 0; i < ar.length; i++) {
if (ar[i] == value) {
return i;
}
}
return -1;
}
}
Note the commented out lines are for if you actually wanted a sorted array instead of an unsorted array
I'm recently having an issue with adding values to an array.
The array contains only multiple last values added.
I was looking on Stack Overflow but all answers said either that a static field is used or there is the same object. But none of these are my case.
Here's my code:
Main class:
public class Main {
public static void main(String[] args) {
Foo[] FooColection = new Foo[5];
for (int i = 0; i < 5; i++) {
Foo Bar = new Foo(i);//making a new Object everytime
FooColection[i] = Bar;
for (int j = 0; j < i;j++ ) {
System.out.println(FooColection[i].getValue());
}
}
}
}
Foo class:
public class Foo {
private int value;//non-static field
public Foo(int value) {
this.value = value;
}
public void change(int newVal) {
this.value = newVal;
}
public int getValue() {
return value;
}
}
Output:
1
2
2
3
3
3
4
4
4
4
You are printing objects that many times. It is in j loop and you're printing with respect to i
System.out.println(FooColection[i].getValue());
You should remove that j loop as your Foo is not a collection, it's a single object.
This behaviour is because of your nested loop, nothing else. Consider removing the nested loop and just print as you iterate.
There's nothing wrong with your array. Just remove the j loop and you're good.
public class Main {
public static void main(String[] args) {
Foo[] FooColection = new Foo[5];
for (int i = 0; i < 5; i++) {
Foo Bar = new Foo(i);//making a new Object everytime
FooColection[i] = Bar;
System.out.println(FooColection[i].getValue());
}
}
}
}
Output
1
2
3
4
I want to replace all multiples of 2 in my array with the value 0 and I felt as though this code did this but 4,6 and 8 stay the same in the output.
Am I doing something stupidly wrong?
public static void markOfMultiples(int[]listOfNumbers, int number)
{
for(int i = 0; i<listOfNumbers.length; i++)
{
if (listOfNumbers[i]%number == 0)
{
listOfNumbers[i] = 0;
}
}
}
In mycase your method was working fine,It solely depends how you are invoking your method
You should invoke your method like
public static void main(String[] args)
{
int num[]={2,4,6,11,13,8};
markOfMultiples(num,2);
}
Your method remains the same
public static void markOfMultiples(int[]listOfNumbers, int number)
{
for(int i = 0; i<listOfNumbers.length; i++)
{
if (listOfNumbers[i]%number == 0)
{
listOfNumbers[i] = 0;
}
System.out.println(listOfNumbers[i]);//added by me to track what's going on
}
and its working fine!
class max{
public int buy;
public int sell;
public max(int n){
buy=0;
sell=0;
}
}
public class MaxProfit{
public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
int i=0,count=0;
while(i<n-1){
while((i<n-1)&&(a[i+1]<=a[i]))
i++;
if(i==n-1)
break;
//System.out.println(sol[count].buy=i++);
sol[count].buy=i++;
i++;
while((i<n)&&(a[i]>=a[i-1]))
i++;
sol[count].sell=i-1;
count++;
}
for(int k=0;k<count;k++)
System.out.println(sol[k].buy +sol[k].sell);
}
public static void main(String []args){
MaxProfit f=new MaxProfit();
int arr[]={20,100,260};
f.stock(arr,arr.length);
System.out.println("Hello World");
}
}
A Exception is coming which is exception in thread "main" java.lang.NullPointerException
at MaxProfit.stock(MaxProfit.java:15)
at MaxProfit.main(MaxProfit.java:32)
I am not able to solve this I have initialized array of max still I am getting null pointer exception Please help
You should initialize the elements of max[] sol maybe in a loop.
for(int i=0;i<sol.length;i++){
sol[i]=new max(aValue);
}
You are declaring an array (sol) but you are not filling your array with objects max. before using your array fill it first. Just add this to initialize your array:
max[] sol=new max[n/2+1];
for(int i = 0; i < sol.length; i++) {
sol[i] = new max(i /* or whatever the value that must be here */);
}
max[] sol=new max[n/2+1];
just defines and array with no (null) contents. You must put valid max objects in it. Like
max[i] = new max(/*param*/);
sol[count].buy=i++;
is throwing the NPE
public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
for (int k = 0; k < sol.length; k++) {
sol[k]= new max(k);
}
int i=0,count=0;
while(i<n-1){
I am trying to write a class that will remove a column from a 2d array, but I keep running into errors that I don't understand. I think I am misunderstanding something very basic here, any help would be appreciated
public class CollumnSwitch
{
int[][] matrix;
int temp;
public static void coldel(int[][] args,int col)
{
for(int i =0;i<args.length;i++)
{
int[][] nargs = new int[args.length][args[i].length-1];
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
int temp = args[i][j];
}
nargs[i][j]= temp;
}
}
}
public void printArgs()
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j]);
}
System.out.println();
}
}
}
You cannot access a non-static variable from a static context, you need to change int temp; to static int temp; or you can remove static from your method declaration.
You declare your nargs array in the coldel method, so it is not accessible from other methods. Meaning this doesn't work:
for(int i =0;i<nargs.length;i++) //You try to access nargs which is not possible.
{
for(int j =0;j<nargs[i].length;j++)
...
Maybe you want it to be the matrix array you have in your class? Like this:
in coldel:
matrix= new int[args.length][args[i].length-1];
and in printArgs
for(int i =0;i<matrix.length;i++)
{
for(int j =0;j<matrix[i].length;j++)
...
This require matrix to be static also (again, you can also remove static from coldel)
you can try like this:
static int[][] nargs;
public static void deleteColumn(int[][] args,int col)
{
if(args != null && args.length > 0 && args[0].length > col)
{
nargs = new int[args.length][args[0].length-1];
for(int i =0;i<args.length;i++)
{
int newColIdx = 0;
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
nargs[i][newColIdx] = args[i][j];
newColIdx++;
}
}
}
}
}
public static void printArgs()
{
if(nargs != null)
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j] + " ");
}
System.out.println();
}
}
}
Your difficulties are arising due to using variables outside of their scope. In java, variables basically only exist within the most immediate pair of braces from which they were declared. So, for example:
public class Foo {
int classVar; // classVar is visible by all code within this class
public void bar() {
classVar = classVar + 1; // you can read and modify (almost) all variables within your scope
int methodVar = 0; // methodVar is visible to all code within this method
if(methodVar == classVar) {
int ifVar = methodVar * classVar; // ifVar is visible to code within this if statement - but not inside any else or else if blocks
for(int i = 0; i < 100; i++) {
int iterationVar = 0; // iterationVar is created and set to 0 100 times during this loop.
// i is only initialized once, but is not visible outside the for loop
}
// at this point, methodVar and classVar are within scope,
// but ifVar, i, and iterationVar are not
}
public void shoo() {
classVar++; // shoo can see classVar, but no variables that were declared in foo - methodVar, ifVar, iterationVar
}
}
The problem you are having is because you are declaring a new 2-d array for each iteration of the for loop and writing one column to it, before throwing that away, creating a new array, and repeating the process.