I've been coding this program but I've got a little bit stuck and would like some advice. This is what I've got so far:
import java.util.Scanner;
public class SmallestInArray
{
public static void main(String[] args)
{
int[] array = new int[10];
input(array);
output(array);
}
public static void input(int[] array)
{
Scanner kybd = new Scanner(System.in);
System.out.println("Enter 10 integers: ");
for (int i = 0; i < array.length; i++) {
array[i] = kybd.nextInt();
}
}
public static int findSmallest(int[] array, int first)
{
int smallestPos = first;
for (int i = first + 1; i < array.length; i++) {
if (array[i] < array[smallestPos]) {
smallestPos = i;
}
}
return smallestPos;
}
public static void output(int[] array)
{
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
Everything is fine other than the findSmallest method, as I'd like to output the smallest value and the index of it, but I'm not quite sure what to pass as the parameters in the main method?
Please find the refactored code which gets you both the value and index of smallest element in the array.
import java.util.Scanner;
public class SmallestInArray
{
int index_of_smallest_element;
public static void main(String[] args)
{
int[] array = new int[10];
input(array);
SmallestInArray smallestInArray = new SmallestInArray();
System.out.printf("Smallest Value:%d corresponding Index:%d\n",smallestInArray.findSmallest(array), smallestInArray.index_of_smallest_element);
output(array);
}
public static void input(int[] array)
{
System.out.println("Enter 10 integers: ");
try (Scanner kybd = new Scanner(System.in))
{
for (int i = 0; i < array.length; i++)
{
array[i] = kybd.nextInt();
}
}
}
public int findSmallest(int[] array)
{
int smallestValue = array[0];
index_of_smallest_element = 0;
for (int i = 1; i < array.length; i++) {
if (smallestValue > array[i]) // it doesn't accounts for duplicate values
{
smallestValue = array[i];
index_of_smallest_element = i;
}
}
return smallestValue;
}
public static void output(int[] array)
{
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}}
Hope this helps
Try this
public static void main(String[] args)
{
int[] array = new int[10];
input(array);
output(array);
int smallestPos = findSmallest(array, 0 /* P.S. this parameter seem to be useless */);
int smallestVal = array[smallestPos];
// output the two
}
Related
As a homework, i was supposed to find the min number of steps needed to reach the last value in the array, assuming each step can only be a maximum of 50.
So, i did this :
import java.util.*;
class RabbitJumps {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rocks: ");
int size = sc.nextInt();
System.out.print("Enter locations of " +size+ " rocks: ");
int[] rocks = new int[size];
for (int i = 0; i<size; i++) {
rocks[i] = sc.nextInt();
}
if (countJumps(rocks)==-1) {
System.out.println("Impossible");
} else {
System.out.println(countJumps(rocks)+" jumps");
}
}
public static int countJumps(int[] rocks) {
for (int i = 0; i<rocks.length-1; i++) {
if (rocks[i+1]-rocks[i]>50) {
return -1;
}
}
int count = 0;
int distjumped = 0;
while (distjumped < rocks[rocks.length-1]) {
int whichrock = nextStep(rocks);
distjumped += rocks[whichrock];
adjustArray(rocks, whichrock);
count++;
System.out.println("count = "+count); //check
}
return count;
}
public static int nextStep(int[] rocks) {
int dist = 0;
int whichrock = 0;
for (int i = 0; i<rocks.length; i++) {
if (rocks[i]>dist && rocks[i]<=50) {
dist=rocks[i];
whichrock = i;
System.out.println(dist); // check
}
}
System.out.println("whichrock = "+whichrock); //check
return whichrock;
}
public static void adjustArray(int[] rocks, int whichrock) {
int dist = rocks[whichrock];
for (int i = 0; i<rocks.length; i++) {
rocks[i]-=dist;
}
for (int i = 0; i<=whichrock; i++) {
rocks[i]=0;
}
}
}
I'm not quite sure why the count's kinda wonky? like this: I'm not sure why the count's starting from 1 again midway. This happens with other inputs as well :(
Would appreciate some help!! thanks guys!!
I am new to java kindly help me why I am getting this error.
I already have searched against this but found no help.
It will be really appreciated!
Code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main{
private class AdjMatrix{
public AdjMatrix(){
System.out.println("No parameters were given to class AdjMatrix");
}
void printAdjMatrix(int[][] arr){
System.out.println("Elements are :");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print("|" + arr[i][j] + "|" + "\t");
}
System.out.println("_______________");
}
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the vertices of graphs: ");
int ver = sc.nextInt();
int [][] arr = new int[ver][ver];
AdjMatrix objMatrix = new AdjMatrix();
objMatrix.printAdjMatrix(arr);
}
}
I'm getting error on this line: AdjMatrix objMatrix = new AdjMatrix();
Perhaps think in terms of memory management. non-static methods refer to an instance of the object i.e memory has been allocated and will be managed some place like a stack. static methods are not bound to any specific instance - memory for them is allocated just one - some place like a heap.
You can move the class AdjMatrix out of the Main class. And remove the private keyword:
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the vertices of graphs: ");
int ver = sc.nextInt();
int [][] arr = new int[ver][ver];
AdjMatrix objMatrix = new AdjMatrix();
objMatrix.printAdjMatrix(arr);
}
}
class AdjMatrix{
public AdjMatrix() {
System.out.println("No parameters were given to class AdjMatrix");
}
void printAdjMatrix(int[][] arr){
System.out.println("Elements are :");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print("|" + arr[i][j] + "|" + "\t");
}
System.out.println("_______________");
}
}
}
This is the preferred way. Another way to avoid the error is to add the class to the main method. This is technically correct, while not as useful because you can't use the AdjMatrix class anywhere outside the method.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the vertices of graphs: ");
int ver = sc.nextInt();
int [][] arr = new int[ver][ver];
class AdjMatrix{
public AdjMatrix() {
System.out.println("No parameters were given to class AdjMatrix");
}
void printAdjMatrix(int[][] arr){
System.out.println("Elements are :");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print("|" + arr[i][j] + "|" + "\t");
}
System.out.println("_______________");
}
}
}
AdjMatrix objMatrix = new AdjMatrix();
objMatrix.printAdjMatrix(arr);
}
}
I was trying to do a Insertion Sort Program that accepts any Data Type (Int, Double, String) then print's the sorted array. I know that my code work's but i can't figure out the real problem.
import java.util.*;
public class MyInsertionSort
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter anything you want");
String insertionSort = in.nextLine();
int num=Integer.parseInt(insertionSort);
String array[] = new String [num];
for (int i = 0; i < array.length; i++)
{
System.out.print("Input the Number at array index "+i+": ");
array[i] = in.nextLine();
}
public static void insertionSort(int array[])
{
int n = array.length;
for (int j = 1; j < n; j++)
{
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) )
{
array [i+1] = array [i]; i--;
}
array[i+1] = key;
printNumbers(array);
}
}
}
Generic type Insertion Sort
I did a quick check and fixed all of the errors. Just compare your code and this one in a comparing tool. So that you can learn what you missed. This code is capable of doing sorting with Multiple data types like String, double, int as of now. It can be altered for any object that implements comparable.
Below is working code
import java.util.Scanner;
public class MyInsertionSort
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter data type to sort : ");
String type = in.nextLine();
System.out.print("Enter number of elements : ");
String insertionSort = in.nextLine();
int num=Integer.parseInt(insertionSort);
String array[] = new String[num];
for (int i = 0; i < array.length; i++)
{
System.out.print("Input the Number at array index "+i+": ");
array[i] = in.nextLine();
}
MyInsertionSort.insertionSortByType(array,type);
in.close();
}
public static void insertionSortByType(String array[], String type)
{
switch (type) {
case "double":
Double[] ConvertedArrayDouble = new Double[array.length];
for (int i = 0; i<array.length; i++) ConvertedArrayDouble[i] = Double.parseDouble(array[i]);
MyInsertionSort.insertionSort(ConvertedArrayDouble);
break;
case "int":
Integer[] ConvertedArrayInt = new Integer[array.length];
for (int i = 0; i<array.length; i++) ConvertedArrayInt[i] = Integer.parseInt(array[i]);
MyInsertionSort.insertionSort(ConvertedArrayInt);
break;
default:
MyInsertionSort.insertionSort(array);
}
}
public static <E extends Comparable<? super E>> void insertionSort(E array[])
{
int n = array.length;
for (int j = 1; j < n; j++)
{
E key = array[j];
int i = j-1;
while ( (i > -1) && ( array[i].compareTo(key) > 0 ) )
{
array [i+1] = array [i]; i--;
}
array[i+1] = key;
}
printNumbers(array);
}
public static <E> void printNumbers(E array[]) {
for (E i : array) {
System.out.println(i);
}
}
}
I have to write a program that sorts names alphabetically while removing duplicates and counting the amount of times the names appear and capitalizes all of it. My partner and I have been working on this and have found no way to have the sorting method work properly and have the program find and count the times the names appear. We have to use certain methods to do this...which I linked the pdf down at the bottom. I really want to understand what's wrong and why the output is not coming out right.
public class Names {
/**
* #param args the command line arguments
*/
static ArrayList<String> fnArray = new ArrayList<String>();
static ArrayList<String> lnArray = new ArrayList<String>();
public static void main(String[] args) throws IOException {
// TODO code application logic here
getNames(fnArray, lnArray);
sort(lnArray);
find(fnArray,1);
capitalize(fnArray,lnArray);
}
public static void getNames(ArrayList<String> fn, ArrayList<String> ln) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.println("What file would you like to read from ?: ");
String n = kb.next();
File inputFile = new File(n);
Scanner in = new Scanner(inputFile);
while (in.hasNext()) {
String firstName = in.next();
fn.add(firstName);
String lastName = in.next();
ln.add(lastName);
}
for (int i = 0; i < fnArray.size(); i++) {
System.out.println(lnArray.get(i) + " " + fnArray.get(i));
}
}
public static void capitalize(ArrayList<String> fnArray, ArrayList<String> lnArray) {
String capfn = " ";
String capln = " ";
int i = 0;
int j = 0;
System.out.println("****************Names***************");
while (i < fnArray.size() && j < lnArray.size()) {
capfn = fnArray.get(i);
capln = lnArray.get(j);
String capFname = capfn.substring(0, 1).toUpperCase() + capfn.substring(1).toLowerCase();
String capLname = capln.substring(0, 1).toUpperCase() + capln.substring(1).toLowerCase();
fnArray.set(i, capFname);
lnArray.set(i, capLname);
System.out.println(lnArray.get(j) + ", " + fnArray.get(i));
i++;
j++;
}
}
public static void display(ArrayList<String> names) {
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
}
public static int find(String s, ArrayList<String> a) {
int count = 0;
for (String str : a) {
if (str.equalsIgnoreCase(s))
count++;
}
return count; }
public static void removeDuplicates(ArrayList<String> s) {
for (int j = 0; j < s.size(); j++) {
int i = -1;
while ((i = find(s, j)) >= 0) {
s.remove(i);
}
}
}
public static void backwards(ArrayList<String> names) {
for (int i = names.size() - 1; i > 0; i--) {
names.get(i);
for (int j = 0; j < names.size(); i++) {
if ((names.get(i).equals(names.get(j)))) {
names.remove(i);
}
}
}
}
public static void sort(ArrayList<String> array) {
for (int i = 1; i < array.size(); i++) {
// find the index of the ith smallest value
int s = i - 1;
for (int j = i; j < array.size(); j++) {
if (array.get(j).compareTo(array.get(s)) < 0) {
s = j;
}
}
// swap the ith smallest value into entry i-1
String temp = array.get(i - 1);
array.set(i - 1, array.get(s));
array.set(s, temp);
}
}
public static void showUnique(ArrayList<String> names){
System.out.println("Unique name list contains:");
for(int i=0 ;i< names.size() ;i++){
System.out.println(lnArray.get(i) + " " + fnArray.get(i));
}
}}
You can use the Collections.sort() method to sort an array list; once it is sorted, you will have entries like this:
ArrayList = { "Alpha", "Beta", "Beta", "Gamma", "Theta", "Theta" ... }
The important point to note, however, is that the duplicates will be next to each other in the sorted array.
Finally, if you want to remove duplicates, you can put all the elements of the ArrayList into a Set: set is a data-structure which removes duplicates.
Example:
Set<String> foo = new HashSet<String>( yourArrayList );
EDIT: Use this approach which is both: easy and simple-to-comprehend.
for( int i = 0; i < array.size() - 1; i++ )
{
for( int j = i + 1; j < array.size(); j++ )
{
if( array[i] > array[j] )
{
// Swap the contents of array[i] and array[j].
}
}
}
correct[], student[], and numIncorrect have already been initialized but missedArray keeps showing as an empty arrray.
public static int[] missedArray(char[] correct, char[] student, int numIncorrect)
{
int[] missedArray = new int[numIncorrect];
for( int i = 0, j = 0; i < correct.length; i++)
{
if (student[i] != correct[i])
{
missedArray[j] = i+1;
j++;
}
}
return missedArray;
it is working fine.Here is the code which i tried.
public class Test {
public static void main(String[] args) {
char []c={'a','b','c','d','e'};
char []s={'a','b','c','c','c'};
int a[]= missedArray(c,s,2);
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
public static int[] missedArray(char[] correct, char[] student, int numIncorrect)
{
int[] missedArray = new int[numIncorrect];
for( int i = 0, j = 0; i < correct.length; i++)
{
if (student[i] != correct[i])
{
missedArray[j] = i+1;
j++;
}
}
return missedArray;
}
}