This is my code
public int Test(int[]n){
if(n.length!=0){
int smallest = n[0];
for(int i = 0; i<n.length ; i++){
if(smallest > n[i]){
smallest = n[i];
return smallest;
}else{
return 0;
}
}
}
How do I change this code so that it throws an exception instead of returning zero if the list is empty?
you can simply achieve your goal:
public int Test(int[] n) {
if (n.length != 0) {
int smallest = n[0];
for (int i = 0; i < n.length; i++) {
if (smallest > n[i]) {
smallest = n[i];
}
}
return smallest;
} else {
throw new RuntimeException("List is empty!");
}
}
You can modify the else block as follows :
if(n.length!=0){
int smallest = n[0];
for(int i = 0; i<n.length ; i++){
if(smallest > n[i]){
smallest = n[i];
return smallest; // you might want to change this as well as suggested by #saeid
} else {
throw new CustomException();
}
}
}
where CustomException can extend any exception that you might want to throw.
You can simply check for the empty list, and if it's empty simply throw an exception.
throw new Exception("Your message that you want to show whenever the list is empty").
or else
Create a custom exception class.
class ListIsEmptyException extends Exception{
//create constructors as per your need
}
Now if list is empty
throw new ListIsEmptyException();
The return statement can not be in inner "if block" since it returns if first comparison success.But it depends on your requirement where you have to return the method. Try this code
create a custom exception
public class customException{
public customException(String msg) {
super(msg);
}
}
if(n.length!=0){
int smallest = n[0];
for(int i = 0; i<n.length ; i++){
if(smallest > n[i]){
smallest = n[i];
return smallest;
}else{
throw new customException("Its an empty list!!!");
}
}
Related
Okay so I have the following code and no matter what it returns to me a -1. I want to have it so that if the id matches then it returns and index but if it doesn't match after running through the whole data set it returns a negative one. Where am I going wrong here:
public class StudentCollection {
private String[] ids = new String[] {"Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty"}; // keeps identification numbers of students
private String [] names = new String[] {"Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty"};; // keeps the names of students
private int size = 0; // number of students currently in the collection
private int findIndex(String id) {
int noIndex = 1;
for (int i=0;i<ids.length;i++){
if((ids[i].equalsIgnoreCase(id))){
System.out.println("The index of this student is " +i);
}
else {
noIndex = -1;
System.out.println(noIndex);
break;}
}
return noIndex;
}
Here is the solution where if index is found then its number is returned, else if it isn't after checking whole array, -1 is returned and appropriate Strings are printed.
private int findIndex(String id) {
int noIndex = -1;
for (int i = 0; i < ids.length; i++) {
if (ids[i].equalsIgnoreCase(id)) {
System.out.println("The index of this student is " + i);
return i;
}
}
System.out.println(noIndex);
return noIndex;
}
You can also use Java 8 Stream:
private int findIndex(String id) {
OptionalInt index = IntStream.rangeClosed(0, ids.length-1)
.filter(i -> ids[i].equalsIgnoreCase(id))
.findFirst();
if(index.isPresent()) {
int i = index.getAsInt();
System.out.println("The index of this student is " + i);
return i;
}
System.out.println(-1);
return -1;
}
Right now you have it so when ids[i].equalsIgnoreCase(id)is true, it will set noIndexto -1 (in the else statement) and break the for loop which will make it return -1. When that is false, it will print out the index.
Like everyone else has already posted, here is the code to find the index.
private int findIndex(String id) {
for (int i=0;i<ids.length;i++){
if(ids[i].equalsIgnoreCase(id)){
return i;
}
}
return -1;
}
i think you need something like this :
private int findIndex(String id) {
for (int i=0; i<ids.length; i++){
if(ids[i].equalsIgnoreCase(id)){
System.out.println("The index of this student is " +i);
return i;
}
}
return -1;
}
I have a function that is searching for max number in the array. I want to make the function to search for more than one word that is entered from console.
As example I enter two words(car,ride) they're added to array and then "surasti" function is comparing them if they're in the array.
I have tried to do it on my own, but I'm a started and it seems too hard :(
Function that is searching:
public static produktas[] surasti (produktas G[], int n){
produktas A[] = new produktas[1];
produktas max = G[0];
for (int i=1; i<n; i++)
if (max.gautiSvori()<G[i].gautiSvori()) max = G[i];
A[0]=max;
return A;
}
The code that is calling that function (A is the array that you have to search in.):
case 5:
B = surasti(A, n);
System.out.println("Sunkiausias gyvunas yra:");
spausdinti_sar_ekrane(B, B.length);
break;
The produktas class:
class produktas {
private String pavadinimas;
private String salis;
private Double svoris;
private Double kaina;
produktas() {}
produktas(String pav, String salis, double svoris, double kaina){
pavadinimas = pav;
this.salis = salis;
this.svoris = svoris;
this.kaina = kaina;
}
public String gautiPav (){
return pavadinimas;
}
public String gautiSali (){
return salis;
}
public double gautiSvori (){
return svoris;
}
public double gautiKaina (){
return kaina;
}
}
When I try to change the function to this (don't know if its working fine, can't test it):
public static produktas[] surasti (produktas G[], int n){
try{
BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
produktas A[] = new produktas[5];
for (int j=0; j<5; j++){
System.out.println("Kokio produkto ieskosime?");
String found = in.readLine();
for (int i=1; i<n; i++){
if (found.equals(G[i].gautiPav())){
A[j] = G[i];
}
}
}
return A;
} catch(IOException ie){
ie.printStackTrace();
}
}
When I try this code I get this error at public static produktas[] surasti (produktas G[], int n){ line:
This method must return a result of type produktas[]
For the correctly complied code update your method to have a return in catch block as well.
public static produktas[] surasti(produktas G[], int n) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
produktas A[] = new produktas[5];
for (int j = 0; j < 5; j++) {
System.out.println("Kokio produkto ieskosime?");
String found = in.readLine();
for (int i = 1; i < n; i++) {
if (found.equals(G[i].gautiPav())) {
A[j] = G[i];
}
}
}
return A;
} catch (IOException ie) {
ie.printStackTrace();
return null; // Expected return from catch block
}
}
To understand the issue properly start using IDE like eclipse rather than simply using a notepad and compiling code through java/javac
A more suitable code would be like as below. Type q in console when u want to exit from the program.
public static produktas[] surasti(produktas G[], int n) {
BufferedReader consoleReader = null;
produktas produktasFound[] = new produktas[5]; // Initalize array to store the produkt found
try {
consoleReader = new BufferedReader(new InputStreamReader(System.in));
boolean exit = false;
produktas produktasFound[] = new produktas[5];
int j = 0;//current produktFound index
while (!exit) {
System.out.println("Kokio produkto ieskosime?");
String produktPav = in.readLine();
if ("q".equals(produktPav)) {
exit = true;
} else {
for (int i=1; i<n; i++){
if (found.equals(G[i].gautiPav())){
A[j] = G[i];
j++;
}
}
}
if(j == 5)
exit = true;
}
return produktasFound; // return all the 5 produktas found
} catch (IOException e) {
e.printStackTrace();
} finally {
if (consoleReader != null) {
try {
consoleReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return produktasFound; //If no produkt is found from the array returned is blank
}
Your comparison operator is not correct. Try the following code :
public static produktas surasti(produktas G[]) {
produktas max = G[0];
for (int i = 0; i < G.length; i++) {
if (max.gautiSvori() < G[i].gautiSvori()) {
max = G[i];
}
}
return max;
}
You need to pass the array and set the first element of the array as the maximum as by default first. Next iterate through the array and check whether there is a produktas with a higher value of svoris. If so, change the max to point to this new produktas. At the end of the for loop, you will now have the max set to the produktas with the highest value of svoris.
There are few things in the code that you can fix for better quality code.
You don't need to pass the array size to the surasti method. We can just do a G.length (in the code above I have done that).
Best practice is to user Camel case for Java classes. Therefore instead of produktas, use Produktas
Use meaningful names for variables instead of A, G, etc
Could someone help me understand where this time limited exceeding comes from? The context is that in this threeSum method, given an array, I'm trying to record all possible combinations of three numbers that add up to 0. The original question comes from : https://leetcode.com/problems/3sum/
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> retList = new ArrayList<List<Integer>>();
Arrays.sort(nums); // O(nlogn)
for (int i=0; i<nums.length-1; i++){
int pleft;
int pright;
if (i!=0){
pleft = i-1;
while((nums[pleft]==nums[i]) && (pleft-1 >=0)){
pleft--;
}
} else {
pleft = i;
}
if (i!=nums.length-2){
pright = i+1;
while((nums[pright]==nums[i]) && (pright+1 < nums.length-1)){
pright++;
}
} else {
pright = i;
}
int sum;
while (true){
sum = nums[pleft]+nums[pright]+nums[i];
if (sum==0){
List<Integer> temp = new ArrayList<Integer>();
temp.add(nums[pleft]);
temp.add(nums[pright]);
temp.add(nums[i]);
retList.add(temp);
if (pleft-1>=0) pleft--;
if (pright+1<nums.length-1) pright++;
} else if (sum>0){
if (pleft-1>=0) pleft--;
} else { // less than zero
if (pright+1<nums.length-1) pright++;
}
}
}
return retList;
}
}
You're not breaking out of your while(true) loop. That code will just run forever and you won't return a value. You need to add a break or change the while (true) to while (condition)
I have an action listener that calls some methods and one of those methods counts the number of times that a loop inside of another method is run. The problem I am having is that the counter just adds to itself (I understand why I just don't know how to fix it) rather than resetting back to 0.
Here is my action listener code.
public double computeIterative(double n) throws InvalidInput {
int a=1, b=2;
int result = 0;
if (n>=0) {
if(n==0)return 0;
if(n==1)return 1;
if(n==2)return 2;
for(int i = 3; i <= n; i++) {
result = a+(2*b);
a=b;
b = result;
this.getEfficiency();
}
} else{
throw new InvalidInput();
}
return result;
}
ActionListener that calls methods and sets text:
public void actionPerformed(ActionEvent e) {
int n = Integer.parseInt(nField.getText());
//Try Catch for Iterate Radio Button
if (iterateBtn.isSelected()){
try {
double result = sequence.computeIterative(n);
int efficiency = sequence.getEfficiency();
rField.setText(Double.toString(result));
eField.setText(Integer.toString(efficiency));
}
catch (InvalidInput ex) {
}
}
The getEfficiency method counts how many times the loop inside computeIterative method is run and then sets it to a textField.
Here is my getEfficiency method:
public int getEfficiency() {
efficiency++;
return efficiency;
}
Now obviously this will just keep adding onto itself, and I am sure that I am looking way too hard for a solution but I just cant figure it out.
Basically, after the try, catch, I need to set efficiency to 0 so that the next time the computeIterative(n) method is called, I get a proper reading.
You could simply add a method resetEfficiency():
public int resetEfficiency() {
efficiency = 0;
}
And then call it at the beginning of computeIterative():
public double computeIterative(double n) throws InvalidInput {
this.resetEfficiency();
//rest of code goes here
//....
}
(Of course I'm assuming this is not multi-threaded or anything).
public double computeIterative(double n) throws InvalidInput {
int a=1, b=2;
int result = 0;
this.resetEfficiencyCounter(); //Call Reset if Number Got Invalid.
if (n>=0) {
if(n==0)return 0;
if(n==1)return 1;
if(n==2)return 2;
for(int i = 3; i <= n; i++) {
result = a+(2*b);
a=b;
b = result;
this.getEfficiency();
}
} else{
throw new InvalidInput();
}
return result;
}
add new Function Named resetEfficiencyCounter().
private void resetEfficiencyCounter(){
this.efficiency = 0;
}
My assignment asks me to make a TV show program, where I can input shows, delete, modify and sort them. What I'm stuck on is the sorting part. With the show, it asks for the name, day a new episode premieres, and time. Those are the keys I need to sort it by.
The program prompts the user to input one of those keys, then the program needs to sort (sorting by day will sort alphabetically).
I made a class and used an array. Here is the class:
public class showInfo
{
String name;
String day;
int time;
}
And the method to sort by time in the code:
public static void intSort()
{
int min;
for (int i = 0; i < arr.length; i++)
{
// Assume first element is min
min = i;
for (int j = i+1; j < arr.length; j++)
{
if (arr[j].time < arr[min].time)
{
min = j;
}
}
if (min != i)
{
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < arr.length; i++)
{
System.out.println(arr[i].name + " - " + arr[i].day + " - " + arr[i].time + " hours");
}
}
When I call it and output it in the main, it only shows "TV Shows by Time" and not the list. Why is this?
Also, I need to make ONE method that I will be able to use to sort both the day AND the name (both Strings). How can I do this without using those specific arrays (arr[i].name, arr[i].day) in the method?
Any help would be greatly appreciated! Thanks in advance!
In this part of your code
if (min != i) {
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
You're just changing the time when you should move the whole object instead. To fix it, the code must behave like this:
if (min != i) {
//saving the object reference from arr[i] in a temp variable
showInfo temp = arr[i];
//swapping the elements
arr[i] = arr[min];
arr[min] = temp;
}
I̶t̶ ̶w̶o̶u̶l̶d̶ ̶b̶e̶ ̶b̶e̶t̶t̶e̶r̶ ̶t̶o̶ ̶u̶s̶e̶ ̶ Arrays#sort ̶w̶h̶e̶r̶e̶ ̶y̶o̶u̶ ̶p̶r̶o̶v̶i̶d̶e̶ ̶a̶ ̶c̶u̶s̶t̶o̶m̶ ̶̶C̶o̶m̶p̶a̶r̶a̶t̶o̶r̶̶ ̶o̶f̶ ̶t̶h̶e̶ ̶c̶l̶a̶s̶s̶ ̶b̶e̶i̶n̶g̶ ̶s̶o̶r̶t̶e̶d̶ ̶(̶i̶f̶ ̶y̶o̶u̶ ̶a̶r̶e̶ ̶a̶l̶l̶o̶w̶e̶d̶ ̶t̶o̶ ̶u̶s̶e̶ ̶t̶h̶i̶s̶ ̶a̶p̶p̶r̶o̶a̶c̶h̶)̶.̶ ̶S̶h̶o̶r̶t̶ ̶e̶x̶a̶m̶p̶l̶e̶:̶
showInfo[] showInfoArray = ...
//your array declared and filled with data
//sorting the array
Arrays.sort(showInfoArray, new Comparator<showInfo>() {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
//basic implementation
if (showInfo1.getTime() == showInfo2.getTime()) {
return showInfo1.getName().compareTo(showInfo2.getName());
}
return Integer.compare(showInfo1.getTime(), showInfo2.getTime());
}
});
//showInfoArray will be sorted...
Since you have to use a custom made sorting algorithm and support different ways to sort the data, then you just have to change the way you compare your data. This mean, in your current code, change this part
if (arr[j].time < arr[min].time) {
min = j;
}
To something more generic like
if (compare(arr[j], arr[min]) < 0) {
min = j;
}
Where you only need to change the implementation of the compare method by the one you need. Still, it will be too complex to create and maintain a method that can support different ways to compare the data. So the best option seems to be a Comparator<showInfo>, making your code look like this:
if (showInfoComparator.compare(arr[j], arr[min]) < 0) {
min = j;
}
where the showInfoComparator holds the logic to compare the elements. Now your intSort would become into something more generic:
public static void genericSort(Comparator<showInfo> showInfoComparator) {
//your current implementation with few modifications
//...
//using the comparator to find the minimum element
if (showInfoComparator.compare(arr[j], arr[min]) < 0) {
min = j;
}
//...
//swapping the elements directly in the array instead of swapping part of the data
if (min != i) {
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
//...
}
Now, you just have to write a set of Comparator<showInfo> implementations that supports your custom criteria. For example, here's one that compares showInfo instances using the time field:
public class ShowInfoTimeComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
return Integer.compare(showInfo1.getTime(), showInfo2.getTime());
}
}
Another comparator that uses the name field:
public class ShowInfoNameComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
return showInfo1.getName().compareTo(showInfo2.getName());
}
}
Now in your code you can call it like this1:
if (*compare by time*) {
genericSort(showInfoArray, new ShowInfoTimeComparator());
}
if (*compare by name*) {
genericSort(showInfoArray, new ShowInfoNameComparator());
}
if (*another custom rule*) {
genericSort(showInfoArray, new ShowInfoAnotherCustomRuleComparator());
}
where now you can implement a custom rule like compare showInfo objects using two or more fields. Taking as example your name and day fields (as stated in the question):
public class ShowInfoNameAndDayComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
int nameComparisonResult = showInfo1.getName().compareTo(showInfo2.getName());
if (nameComparisonResult == 0) {
return showInfo1.getDay().compareTo(showInfo2.getDay());
}
return nameComparisonResult;
}
}
1: There are other ways to solve this instead using lot of if statements, but looks like that's outside the question scope. If not, edit the question and add it to show another ways to solve this.
Other tips for your current code:
Declare the names of the classes using CamelCase, where the first letter of the class name is Upper Case, so your showInfo class must be renamed to ShowInfo.
To access to the fields of a class, use proper getters and setters instead of marking the fields as public or leaving the with default scope. This mean, your ShowInfo class should become into:
public class ShowInfo {
private String name;
private String day;
private int time;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
//similar for other fields in the class
}
Use selection sort algorithm which is easy to implement,
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i].time > arr[j].time) // Here ur code that which should be compare
{
ShowInfo temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
no need to check min element. go through this wiki http://en.wikipedia.org/wiki/Selection_sort
Why not you use a Collection for this sort of a thingy to work. Moreover, in your added example, you are simply changing one attribute of a given object, while sorting, though you not changing the position of the object as a whole, inside the given list.
Create a List which will contain the references of all the Shows, now compare each attribute of one Show with another, in the List. Once the algorithm feels like, that swapping needs to be done, simply pick the reference from the List, save it in a temp variable, replace it with a new reference at this location, and set duplicate to the one stored in the temp variable. You are done, List is sorted :-)
Here is one small example for the same, for help :
import java.io.*;
import java.util.*;
public class Sorter {
private BufferedReader input;
private List<ShowInfo> showList;
public Sorter() {
showList = new ArrayList<ShowInfo>();
input = new BufferedReader(
new InputStreamReader((System.in)));
}
private void createList() throws IOException {
for (int i = 0; i < 5; i++) {
System.out.format("Enter Show Name :");
String name = input.readLine();
System.out.format("Enter Time of the Show : ");
int time = Integer.parseInt(input.readLine());
ShowInfo show = new ShowInfo(name, time);
showList.add(show);
}
}
private void performTask() {
try {
createList();
} catch (Exception e) {
e.printStackTrace();
}
sortByTime(showList);
}
private void sortByTime(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
if (showList.get(j).getTime() <
showList.get(min).getTime()) {
min = j;
}
}
if (min != i) {
ShowInfo temp = showList.get(i);
showList.set(i, showList.get(min));
showList.set(min, temp);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
public static void main(String[] args) {
new Sorter().performTask();
}
}
class ShowInfo {
private String name;
int time;
public ShowInfo(String n, int t) {
name = n;
time = t;
}
public String getName() {
return name;
}
public int getTime() {
return time;
}
}
EDIT 2 :
For sorting By Name you can use this function :
private void sortByName(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
int value = (showList.get(j).getName()).compareToIgnoreCase(
showList.get(min).getName());
if (value < 0)
min = j;
}
if (min != i) {
ShowInfo temp = showList.get(i);
showList.set(i, showList.get(min));
showList.set(min, temp);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
EDIT 3 :
Added Comparable<?> Interface, to the existing class to perform sorting based on specified input. Though one can improve on the logic, by using Enumeration, though leaving it for the OP to try his/her hands on :-)
import java.io.*;
import java.util.*;
public class Sorter {
private BufferedReader input;
private List<ShowInfo> showList;
private int command;
public Sorter() {
showList = new ArrayList<ShowInfo>();
input = new BufferedReader(
new InputStreamReader((System.in)));
command = -1;
}
private void createList() throws IOException {
for (int i = 0; i < 5; i++) {
System.out.format("Enter Show Name :");
String name = input.readLine();
System.out.format("Enter Time of the Show : ");
int time = Integer.parseInt(input.readLine());
ShowInfo show = new ShowInfo(name, time);
showList.add(show);
}
}
private void performTask() {
try {
createList();
} catch (Exception e) {
e.printStackTrace();
}
System.out.format("How would you like to sort : %n");
System.out.format("Press 0 : By Name%n");
System.out.format("Press 1 : By Time%n");
try {
command = Integer.parseInt(input.readLine());
} catch (Exception e) {
e.printStackTrace();
}
sortList(showList);
}
private void sortList(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
showList.get(j).setValues(command);
int value = showList.get(j).compareTo(showList.get(min));
if (value < 0) {
min = j;
}
}
if (min != i) {
Collections.swap(showList, i, min);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
public static void main(String[] args) {
new Sorter().performTask();
}
}
class ShowInfo implements Comparable<ShowInfo> {
private String name;
private int time;
private int command;
public ShowInfo(String n, int t) {
name = n;
time = t;
}
public String getName() {
return name;
}
public int getTime() {
return time;
}
public void setValues(int cmd) {
command = cmd;
}
public int compareTo(ShowInfo show) {
int lastCmp = 1;
if (command == 0) {
lastCmp = name.compareTo(show.name);
} else if (command == 1) {
if (time < show.time) {
lastCmp = -1;
} else if (time == show.time) {
lastCmp = 0;
} else if (time > show.time) {
lastCmp = 1;
}
}
return lastCmp;
}
}