How to use an array in for loop to calculate minimum? - java

I am trying to use an array, but I am not sure if that is the right way to do this.
I want the first and second integer input to compare with one another, then if there are more they compare with each other.
So here is the piece of the code.
for(int ii = 1, j = 0; j <= copySel ; ii++, j++) {
int x = 0;
int[x] check;
// Prompt as follows
System.out.print("Enter value " + ii + ": ");
try {
c = Get();
}
catch (InputMismatchException e) {
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
ii--; x--;
} check = c; x++;
System.out.print(check + " "+ x);
}
My actual format is not this bad. I need to try to find the minimum value depending on the number of integer the user has input
static int Get()
{
Scanner intFind = new Scanner(System.in);
int select;
select = intFind.nextInt();
return select;
}
This is Get() ^
cant I use min(x, y) continuously?

int min=a[0];
for(int i=1;i<n;i++)
{
if(a[i] < min)
min = a[i];
}
System.out.println("The min is "+min);

System.out.print("Enter value " + ii + ": ");
int min = Get();
int c = 0;
for(int ii = 1, j = 0; j < copySel ; ii++, j++) {
// Prompt as follows
System.out.print("Enter value " + ii + ": ");
try {
c = Get();
}
catch (InputMismatchException e) {
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
ii--;
} min = Math.min(min, c);
System.out.print("minimum is:"+ min);
}

if you have a integer array you could do as below
Integer [] arr = {5,2,3,4,5,6,7,8};
List<Integer> list = new ArrayList<Integer>(Arrays.asList(arr));
Collections.sort(list);
System.out.println("Minimum "+list.get(0)); ;

Scanner in = new Scanner(System.in);
System.out.println("Enter the integers: ");
String s = in.nextLine();
string[] str = s.plit(" ");
int[] a = new a[str.length];
for(int i =0; i< str.length; i++)
{
a[i] = Integer.parseInt(str[i]);
}
//Madar's code
int min=a[0];
for(int i=0;i<a.length;i++)
{
min = Math.min(a[i], min);
}
System.out.println("The min is "+min);

I didn't get what your trying to do exactly, but here's some errors you might consider to repair. If check is an array you have to initialize it as such:
int[] check;
Does get() give you back an array of integer, if so you cannot make check = c, you have to copy or clone the content of c into check as such:
check = (int[])c.clone();

Related

How to use try catch to replace invalid data of user input array instead of restarting code in Java?

Whenever invalid input is entered, such as a letter, the code starts from the beginning. How do I get it so that it keeps rebuilding the code from where invalid input was entered. I want it to kick out the invalid input, and prompt the user to re-enter a valid input, and keep building it.
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
int z = 1;
do {
try {
Scanner scanner = new Scanner(System.in);
double[] myArr1 = new double[10]; //Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x=0; x<myArr1.length; x++) {
myArr1[x] = scanner.nextDouble(); //Gets user input
} //end of for
double sum1 = 0;
for(double x=0; x<myArr1.length; x++) {
sum1 += myArr1[(int) x]; //Defines sum1
} //end of for
double[] myArr2 = new double[10]; //Creates array
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int y=0; y<myArr2.length; y++) {
myArr2[y] = scanner.nextDouble(); //Gets user input
} //end of for
double sum2 = 0;
for (double y=0; y<myArr2.length; y++) {
sum2 += myArr2[(int) y];
} //end of for
System.out.println("Sum of first 10 elements is: " + sum1); //Prints sum of first 10 elements
System.out.println("Sum of second 10 elements is: " + sum2); //Prints sum of last 10 elements
}/*end of try*/catch (Exception e) { //Catches errors in user input
System.out.println("Invalid input. Try again: ");
System.out.println("");
} //end of catch
}//end of do
while(z==1);
return;
}
}
You can craft a helper method for input. It will continually prompt with the messages provided until a correct type is entered. This tends to come in handy when inputs need to be taken from different locations within the program.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double v = nextDouble(input, "Please enter a value: ", "Improper type, try again: ");
System.out.println(v);
}
public static double nextDouble(Scanner input, String prompt, String error) {
System.out.print(prompt);
// loop forever
for(;;) {
try {
double v = input.nextDouble();
return v;
} catch (InputMismatchException ie) {
input.nextLine(); // clear input buffer
System.out.print(error);
}
}
}
Here is an example from your code.
Scanner scanner = new Scanner(System.in);
String prompt = "Please enter a number: ";
String error = "Invalid input, try again";
double[] myArr1 = new double[10]; // Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x = 0; x < myArr1.length; x++) {
myArr1[x] = nextDouble(scanner, prompt, error);
} // end of for
double sum1 = 0;
for (double x = 0; x < myArr1.length; x++) {
sum1 += myArr1[(int) x]; // Defines sum1
} // end of for
Get rid of your existing try/catch blocks. And I don't know why you have a do/while since you aren't looping more than once.
or you can using while loop and a boolean value to get a number
Scanner scanner = new Scanner(System.in);
boolean bool = true;
double d ;//= scanner.nextDouble();
while(bool){
try{
scanner = new Scanner(System.in);
d = scanner.nextDouble();
bool = false;
}catch(InputMismatchException e){
System.err.println("invalid input");
}
}
I've figured it out. I had to create a boolean, but also decrement the index of the array of where the bad input was being placed (i = i-1). I also made it just one array and set the first 10 values to x and the last 10 to y to make it a little bit simpler.
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
double[] array = new double[20]; //creates array
boolean on = true; //sets value "on"
while (on) { //starts while loop
System.out.println("Enter 20 numbers: ");
System.out.println("");
for (int i = 0; i < array.length; i++) { //creates user input prompt
Scanner input = new Scanner(System.in); //gets user input
try {
array[i] = input.nextDouble(); //assigns user input to array[i]
}/*end of try*/ catch (Exception e) { //catches invalid input
System.err.println("Invalid Input. Try again: ");
i = i - 1; //decrements index of re-entered number
} //end of catch
} //end of for
double x = 0;
for (int z = 0; z < 10; z++) {
x += array[z];
} //end of for
System.out.println("Sum of first 10 numbers = " + x); //adds first 10 numbers in array and assigns them to x
System.out.println("");
double y = 0;
for (int z = 10; z < 20; z++) {
y += array[z];
} //end of for
System.out.println("Sum of last 10 numbers = " + y); //adds last 10 numbers in array and assigns them to y
on = false; //breaks while loop
} //end of while
}
}

How do I find the number of occurences of repeating elements in array in Java EE?

I tried writing a code fragment to find the number of occurences of a repeating element in a 1 dimensional array in Java....the counter doesnt seem to go above 1...could someone help me please..
here is my code:
import java.util.*;
public class duplicate{
public static void main(String args[]){
int i,n,c,j,m=-1;
Scanner a = new Scanner(System.in);
System.out.println("Enter the value of length");
n=a.nextInt();
int b[] = new int[n];
System.out.println("Enter the elements of the array.");
for(i=0;i<n;++i)
b[i]=a.nextInt();
for(i=0;i<n;++i){
c=0;
if(b[i]==m)
continue;
else{
m=b[i];
for(j=0;j<=i;++j){
if(b[j]==b[i])
c++;
}
System.out.println("The element"+b[i]+" has occured "+c+" times.");
}
}
}
}
There are many things sketchy with your code snippet. First of all, I would advise you to properly format your code and maybe improve some variable naming.
I took the portion of your code to show it is buggy:
for (i = 0; i < n; ++i) {
c = 0;
if (b[i] == m) {
continue;
} else {
/*
* here you always set m to the current value of the array so in the next
* iteration, your check in the "if clause" will be true what means that the
* counter will never count up if there are 2 or more consecutive equal numbers
*/
m = b[i];
for (j = 0; j <= i; ++j) {
// also this logic is flawed, because you only count the values
// before the current one
if (b[j] == b[i])
c++;
}
System.out.println("The element" + b[i] + " has occured " + c + " times.");
}
}
What i would rather advise you to use for this kind of task, is to use a HashMap and count the occurrences for each value there.
Example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of length");
int size = scanner.nextInt();
int[] values = new int[size];
System.out.println("Enter the elements of the array.");
for (int i = 0; i < size; i++) {
values[i] = scanner.nextInt();
}
Map<Integer, Integer> map = new HashMap<>();
for (int key : values) {
if (map.containsKey(key)) {
int occurrence = map.get(key);
occurrence++;
map.put(key, occurrence);
} else {
map.put(key, 1);
}
}
for (Integer key : map.keySet()) {
int occurrence = map.get(key);
System.out.println(key + " occurs " + occurrence + " time(s).");
}
}

asking for a name of each customer with array size in for loop

I'm a beginner and I've been really stuck on this problem. I'm not really sure how I can display the number of customer(in an arraySize) (customer #1, customer #2...) and ask for their name in a for loop.
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + arraySize + ": "
}
I've tried dinerArray.length and then i, arraySize with i, (i=0;i<=arraySize;i++) with arraySize/i.. but nothing seems to work. It would either only print once with customer#0 or print nothing at all
You need to change arraySize to i. That way it will produce customer#1,customer#2 etc....
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + i+ ": ");
}
If you just want to read them from the console, you can use a Scanner:
Scanner input = new Scanner(System.in);
int arraySize = 10;
String[] dinerArray = new String[arraySize];
for(int i = 0; i < arraySize; ++i)
{
System.out.print("Enter the name of customer#" + (i + 1) + ": ");
dinerArray[i] = input.nextLine();
}
input.close();
im no Java dev but this is pretty basic.
The problem is that your for loop is just running if i is equal to arraySize, but this never happen.
So, try to change your '==' to a '<='
My solution:
Scanner scan = new Scanner(System.in);
int arraySize = 5;
String[] dinerArray = new String[arraySize];
for(int i = 1; i <= dinerArray.length; i++) {
ystem.out.print("pleas enter name for customer#" + i);
dinerArray[i - 1] = scan.nextLine();
}
Im not sure about the scanner think.

Last word/sentence on an Array Java

I have an assignment, it looks pretty easy however I cannot figure it out how to solve it.
It says:
a) Ask the user: How many words/sentences do you want to write (at
least 5) ? (Use while loop)
b) Use for loop to make the user write the words/sentences
c) After the user's written the words/sentences, output which
word/sentence comes last alphabetically (using .compareTo() method )
This is what I came up with:
import java.util.Scanner;
import java.lang.String;
import java.util.Arrays;
public class LastString {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
final short MIN_NUM = 2;
int num = 0;
int count = 0;
String [] sentence = new String [0];
String last = "";
while (num < MIN_NUM){
System.out.println("How many words/sentences do you want to put? " + "\t\t\t\t\t\t\t\t --- at least " + MIN_NUM);
num = input.nextInt();
sentence = new String [num];
}
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
System.out.println("The word/sentence is: " + sentence[i]);
}
int i = 0;
int max;
for (i=0;i<num-1 ;i++ ) {
if(sentence[i].compareTo(sentence[i+1]) > 0){
last = sentence[i];
count ++;
}else if (sentence[i].compareTo(sentence[i+1]) < 0) {
last = sentence[i+1];
count++;
}
}
System.out.println("\n\n------------" +
"\nLast word/sentence is: " + last);
System.out.println(Arrays.toString(sentence));
}
}
I compiles and runs. I have two problems:
nextLine >>> it is skiping the first Sentence
I don't know how to make the algorithm to calculate which word/sentence has the biggest value or, using the compareTo() method which word/sentence has the value > 0 compared to each and every other value on the array.
Thank you.
Answer to Q1 : num = input.nextInt(); takes a number as the input but doesn't also consume the new-line, and hence the nextLine consumes the empty new line ... you could use input.nextLine also to get the first number instead of num = input.nextInt(); by reading a line, then parsing the int value as num = Integer.parseInt(input.nextLine());
Answer to Q2 :
You re-set the value of last everytime but you don't compare the value of the next biggest candidate with the last before re-assigning last ...
for example, look at the following :
for (int i = 0; i < num - 1; i++) {
String thisLast = "";
if (sentence[i].compareTo(sentence[i + 1]) > 0) {
thisLast = sentence[i];
count++;
} else if (sentence[i].compareTo(sentence[i + 1]) < 0) {
thisLast = sentence[i + 1];
count++;
}
if (thisLast.compareTo(last) > 0)
last = thisLast;
}
it will solve your problem....
int count = 0;
String [] sentence = new String[6];
String last = "";
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
count++;
if(count >= 2){
if(sentence[i].compareTo(last) > 0){
last = sentence [i] ;
}
}else{
last = sentence [i];
}
System.out.println("The word/sentence is: " + sentence[i]);
}

storing an integer array into a list integer array and accessing those variables in order

okay so i have this code and i would like to store the values of an array of integers intwholef[x] and store those values in the array wholelist[y]. the only problem is that the way i have it set up is that im taking the first three values of the array and storing them in intwholef[x] and then x is resetting as it passes on the the next line. a graphical representation is below
This is the contents of the file stored in an array of strings
intwholef[0] = 1 3 10
intwholef[1] = 2 4 15
intwholef[2] = 3 6 8
intwholef[3] = 4 7 3
intwholef[4] = 5 9 12
now what i WANT is those values to be stored like this.
wholelist[] = 1,3,10,2,4,15,3,6,8,4,7,3,5,9,12
and be accessible like
wholelist[2] * wholelist[5] = 150;
the problem that im running into is that im not able to save the values in a list like this, any ideas?
here is the whole code, the part im talking about is at the bottom
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class project1
{
#SuppressWarnings("null")
public static void main(String[] args)
{
System.out.println("These are your following choices: ");
System.out.println("1. First-Come First-Served (FCFS): ");
System.out.println("2. Shortest Job Next (SJN): ");
System.out.println("3. Shortest Remaining Time (SRT): ");
System.out.println("4. Round Robin (RR) with time quantum = 4 ms: ");
System.out.println("please enter your choice by entering 1, 2, 3, 4");
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
if(choice ==1)
{
System.out.println("your choice was first come first serve");
}
else if(choice == 2)
{
System.out.println("your choice was shortest job next");
}
else if(choice == 3)
{
System.out.println("your choice was shortest job remaining");
}
else if(choice == 4)
{
System.out.println("your choice was round robin (rr) with time quantum = 4 ms");
}
else
{
System.out.println("you entered an invalid choice");
}
BufferedReader file = null;
System.out.println("Please enter the file path for your input");
Scanner fp = new Scanner(System.in);
String input = fp.nextLine();
String fileloc;
String[] wholef = null;
int fline = 0;
try
{
file = new BufferedReader(new FileReader(input));
fileloc = file.readLine();
fline = Integer.parseInt(fileloc); // this stands for file contents from the file to be read
wholef = new String[fline];
int i = 0;
while((fileloc = file.readLine()) != null)
{
wholef[i] = fileloc;
System.out.print("the contents of this file are: ");
System.out.println(fileloc);
i++;
}
System.out.println("This is the contents of the file stored in an array of strings");
for(int n = 0; n < fline; n++)
{
System.out.println(wholef[n]);
}
} catch (IOException er)
{
er.printStackTrace();
}
finally
{
try
{
if(file != null)
{
file.close();
}
} catch(IOException erx)
{
erx.printStackTrace();
}
}
System.out.println("This is the size of the contents of the file");
for(int n = 0; n < fline; n++)
{
System.out.println(wholef[n].length());
}
System.out.println("this is the input file converted and stored into an array of integers");
String[] parts = null;
int[] intwholef = null;
int[] wholelist =null;
for(int x = 0; x < fline; x++)
{
parts = wholef[x].split(" ");
intwholef= new int[parts.length];
for(int n = 0; n < parts.length; n++)
{
intwholef[n] = Integer.parseInt(parts[n]);
System.out.println(/*"intwholef[" + n + "] = " + */intwholef[n]);
for(int m = 0; m < parts.length; m++)
{
//wholelist[m]= intwholef[n];
}
}
}
System.out.println("this is the list of number from the conversion dumped into a singular array list");
for(int i = 0; i < 15; i++)
{
System.out.println("intwholef[" + i + "] = " + wholelist[i]);
}
/*
System.out.println("operations done with array of ints");
for(int i = 0; i < 20; i++)
{
System.out.println(intwholef[i]);
}
//System.out.println(intwholef[0] * intwholef[3]);
*/
}
}
I suggest you use a List (like ArrayList) instead of an array as the size of it can change. As such:
ArrayList wholeList = new ArrayList<Integer>();
for(int x = 0; x < fline; x++)
{
parts = wholef[x].split(" ");
for(int n = 0; n < parts.length; n++)
{
wholeList.add(Integer.parseInt(parts[n]));
}
}
Then you can access the different values with wholeList.get(index).
You can do it simply using an ArrayList. If you want to end up with an Array, use the toString method. Split the string with \\s, so that any whitespace can serve as delimiter. Also, you only need only loop, like this:
int[] myArray = new int[10];
List<Integer> list = new ArrayList<Integer>();
while ((fileloc = file.readLine()) != null) {
for (String s : fileloc.split("\\s+")) {
list.add(Integer.parseInt(s));
}
System.out.println(Arrays.toString(myArray));
}
int[] wholelist = list.toArray();

Categories

Resources