Sorting Arrays. The first element is length of array - java

Question :
Sorted?) Write the following method that returns true if the list is already sorted in increasing order. public static boolean isSorted(int[] list) Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list.
My try:
import java.util.Scanner;
public class Problem6_19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number. for the length of the list: ");
int listLength = input.nextInt();
int[] number = new int[listLength];
for(int i = 0; i < number.length; i++) {
System.out.println("Enter a value: ");
number[i] = input.nextInt();
}
if (isSorted(number)) {
System.out.println("The list is sorted!");
} else {
System.out.println("The list is NOT sorted!");
}
}
public static boolean isSorted(int[] list) {
for(int i = 0; i < list.length; i++) {
if (list[i] > list[i + 1]) {
return false;
} else {
return true;
}
}
return false;
}
}
But there's one problem. In the question it prompts the user to enter list and the first element is length of that list. This means that we need to prompt the user only one time. So please explain how is this possible that first element becomes the size of an array??

The Scanner class uses whitespace, any white space, as the delimiter between tokens by default. This means that if the user pressed return between entering numbers then you need to handle that case and ask the user for another number, or the end user would just be on a new line and not know what to do. If the user doesn't press return between entering the numbers but separates them with a space, for example:
1 2 3 4 5
then the scanner would separate that in to 5 separate tokens that would be returned one at once when you call nextInt().
If you run your program and enter something like:
4 2 1 3 4
It should out put four questions asking you to enter inout (that you have already given to it) but then perform the function you want anyway and print "The list is NOT sorted!".
PS. the program doesn't quite work as I imagine you want it to because you as it only checks if the first two values are in ascending order and then returns. Instead you should check to see if the first two are correct, set a flag to keep track of them if they are and then carry on with the loop without exiting. Or only return in the case where the list isn't sorted and if you get to the end of checking the array and you haven't exited it must be sorted and therefore you should return true (as in the code example below). The return statements force your method isSorted to exit as soon as it hits that line, without going through the whole loop. You should also check for going off the end of the array before trying to access i+1. Something like
import java.util.Scanner;
public class ScannerClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number. for the length of the list: ");
int listLength = input.nextInt();
int[] number = new int[listLength];
for(int i = 0; i < number.length; i++) {
System.out.println("Enter a value: ");
number[i] = input.nextInt();
}
if (isSorted(number)) {
System.out.println("The list is sorted!");
} else {
System.out.println("The list is NOT sorted!");
}
}
public static boolean isSorted(int[] list) {
for(int i = 0; i < list.length - 1; i++) {
if (list[i] > list[i + 1]) {
return false
}
}
return true;
}
}

Related

How do I fix my duplicate detection code? Java

I have here a scanner in which collects series of numbers. I want it to scan the list every time user inputs a number so if the user inputs a number that is already in the list the new input will be disregarded/ignored and at the same time not adding increment to the loop.
The problem is the code can't seem to identify the duplicates. It continues to register the duplicate number even after few tries.
My code so far:
public class Number {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How Many Numbers You want to Enter:");
int n = input.nextInt();
List<Integer> number = new ArrayList<>();
for(int s=0;s<n;s++) {
int t = input.nextInt();
for (int j = 1; j < number.size(); j++) {
if (t == number.get(j)) {
System.out.print("Duplicate!");
s--;
continue;
} else {
number.add(t);
}
}
}
}
}
At the moment nothing at all is being saved in the number list, so the first thing to do is add debugging to work out why, or better yet, we can make use of the ArrayList.contains(...) method to solve this quite easily without needing the nested loop that that is causing your issue, for example the following works:
for(int s=0;s<n;s++) {
int t = input.nextInt();
if(number.contains(t)){
System.out.print("Duplicate!\r\n");
s--;
continue;
} else {
number.add(t);
}
}
//Print the result
System.out.println(Arrays.deepToString(number.toArray()));
And an output for a length of 5 and this number sequence 2,3,7,3,5,1 is:
How Many Numbers You want to Enter:5
2
3
7
3
Duplicate!
5
1
[2, 3, 7, 5, 1]

Store user input in array multiple times

I'm working on a project which...
Allows the user to input 4 numbers that are then stored in an array for later use. I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values.
The code is not done and I know there are some things that still need some work. I just provided the whole code for reference.
I'm just looking for some direction on the arrays part.
*I believe I am supposed to be using a 2-D array but I'm confused on where to start. If I need to explain more please let me know. (I included as many comments in my code just in case.)
I tried converting the inputDigit(); method to accept a 2-D array but can't figure it out.
If this question has been answered before please redirect me to the appropriate link.
Thank you!
package littleproject;
import java.util.InputMismatchException;
import java.util.Scanner;
public class littleProject {
public static void main(String[] args) {
// Scanner designed to take user input
Scanner input = new Scanner(System.in);
// yesOrNo String keeps while loop running
String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
double[][] arrayStorage = inputDigit(input, "Enter a number: ");
System.out.println();
displayCurrentCycle();
System.out.println();
yesOrNo = askToContinue(input);
System.out.println();
displayAll();
System.out.println();
if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
System.out.println("You have exited the program."
+ " \nThank you for your time.");
}
}
}
// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double array[][] = new double[arrayNum][4];
for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
// For loop that stores each input by user
for (int counter = 0; counter < array.length; counter++) {
System.out.print(prompt);
// Try/catch that executes max and min restriction and catches
// a InputMismatchException while returning the array
try {
array[counter] = input.nextDouble();
if (array[counter] <= 1000){
System.out.println("Next...");
} else if (array[counter] >= -100){
System.out.println("Next...");
} else {
System.out.println("Error!\nEnter a number greater or equal to -100 and"
+ "less or equal to 1000.");
}
} catch (InputMismatchException e){
System.out.println("Error! Please enter a digit.");
counter--; // This is designed to backup the counter so the correct variable can be input into the array
input.next();
}
}
}
return array;
}
// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
int averageValue = 23; // Filler Variables to make sure code was printing
int highestValue = 23;
int lowestValue = 23;
System.out.println(\n--------------------------------"
+ "\nAverage - " + averageValue
+ "\nHighest - " + highestValue
+ "\nLowest - " + lowestValue);
}
public static void displayAll() {
int fullAverageValue = 12; // Filler Variables to make sure code was printing
int fullHighestValue = 12;
int fullLowestValue = 12;
System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
+ "\n--------------------------------"
+ "\nAverage Value - " + fullAverageValue
+ "\nHighest Value - " + fullHighestValue
+ "\nLowest Value - " + fullLowestValue);
}
// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
boolean loop = true;
String choice;
System.out.print("Continue? (y/n): ");
do {
choice = input.next();
if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
System.out.println();
System.out.println("Final results are listed below.");
loop = false;
} else {
System.out.print("Please type 'Y' or 'N': ");
}
} while (loop);
return choice;
}
}
As far as is understood, your program asks the user to input four digits. This process may repeat and you want to have access to all entered numbers. You're just asking how you may store these.
I would store each set of entered numbers as an array of size four.
Each of those arrays is then added to one list of arrays.
A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays.
We store the digits that the user inputs in array of size 4:
public double[] askForFourDigits() {
double[] userInput = new double[4];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = /* ask the user for a digit*/;
}
return userInput;
}
You'll add all each of these arrays to one list of arrays:
public static void main(String[] args) {
// We will add all user inputs (repesented as array of size 4) to this list.
List<double[]> allNumbers = new ArrayList<>();
do {
double[] numbers = askForFourDigits();
allNumbers.add(numbers);
displayCurrentCycle(numbers);
displayAll(allNumbers);
} while(/* hey user, do you want to continue */);
}
You can now use the list to compute statistics for numbers entered during all cycles:
public static void displayAll(List<double[]> allNumbers) {
int maximum = 0;
for (double[] numbers : allNumbers) {
for (double number : numbers) {
maximum = Math.max(maximum, number);
}
}
System.out.println("The greatest ever entered number is " + maximum);
}

arraylist that stores the entered number

My program is that the ArrayList stores the entered number, and when the user enters the number -1, the program will stop end print out all the entered number in ascending order. My program runs, but let the number enters, it doesn't print the numbers out. it seems like if statement doesn't working. how to call the ArrayList in if statement to work right?
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;
public class testArrayList {
public static void main(String[] args) {
Scanner inputs = new Scanner(System.in);
ArrayList <Integer> nums = new ArrayList<Integer>();
System.out.println("Enter a number(-1 to end): ");
while(inputs.hasNextInt()) {
nums.add(inputs.nextInt());
}
// it looks like it runs until here.
for (Integer n : nums) {
if (n == -1) {
Collections.sort (nums);
System.out.println("Here is the list of numbers : ");
System.out.println(n);
}
}
}
}
System.in will block and wait for a new input, and as long as you continue entering numbers, hasNextInt() will always be true. Instead, you should check for -1 in the initial input (while) loop:
while(inputs.hasNextInt()) {
int num = inputs.nextInt();
if (num == -1) {
break;
}
nums.add(num);
}
nums.sort();
System.out.println("Here is the list of numbers : ");
System.out.println(nums);
Your loop adding numbers to the list don't check for the value -1 to stop the loop. -1 is an int, so it's continuing.
After you've fixed that you will run into the next problem. You're iterating over the elements of the list and do a sort each time the user entered 1. I haven't checked but this will most likely lead to an exception because iterators get not amused if you change the underlying list while iterating over it. According to your description, you should call sort before the loop and then just do the System.out.println within the loop.
My program runs, but let the number enters, it doesn't print the
numbers out. it seems like if statement doesn't working.Trying
performing once step at a time:
In your code, it would do so only is n a value from the list nums is equal to -1.
Instead you should try to put your code as:
// Accept user input
Integer input = inputs.nextInt();
// check if it is not -1
while(input != -1) {
nums.add(input);
input = inputs.nextInt()
}
// sort the arraylist
Collections.sort (nums);
// print the elements
System.out.println("Here is the list of numbers : ");
for (Integer n : nums) {
System.out.println(n);
}
The if statement is never reached, you can check this by adding a println just before it which is never printed if because the scanner ignores whitespace. It will keep trying to take input until you enter a letter. To get the desired effects, I would probably just do n = inputs.nextInt(); then if n is -1 use break. Also your whole for loop and if condition is unnecessary, just sort the list and print it -using .toString because otherwise it will just be a memory address-because you do that in every case (although you may want to remove the -1).
i know there is a few answers, but here's my version :
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;
public class testArrayList
{
public static void main(String[] args)
{
Scanner inputs = new Scanner(System.in);
ArrayList <Integer> nums = new ArrayList<Integer>();
System.out.println("Enter a number(-1 to end): ");
while(inputs.hasNextInt())
{
//check if the next value is -1
int nextVal = inputs.nextInt();
if(nextVal == -1)
{
break; //then exit the loop
}
else
{
nums.add(inputs.nextInt()); //else add to the list
}
}
//since we exited the loop, we can sort the list, and print header
Collections.sort (nums);
System.out.println("Here is the list of numbers : ");
for (int i = 0 ; i < nums.size(); i++)
{
System.out.println(nums.get(i)); // print every sorted int from
// the list
}
}
}
There was a problem with the logic of your code when printing, and also when reading for the -1 exit code. Now it's in the read loop, and then we print the whole sorted list.
tested here :
https://www.jdoodle.com/online-java-compiler
I have reorganized the code and make it much more simpler, as you are trying to exit the map when -1 value is entered.
public class TestArrayList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList <Integer> nums = new ArrayList<Integer>();
while(true ) {
System.out.println("Enter a number(-1 to end): ");
int value = scanner.nextInt();
/*read until your input is -1*/
if ( value != -1 ){
nums.add(value);
}else {
Collections.sort (nums);
System.out.println("Here is the list of numbers : ");
for ( int i : nums){
System.out.println(i);
}
break;
}
}
scanner.close();
}
}
Scanner inputs = new Scanner(System.in);
ArrayList nums = new ArrayList();
System.out.println("Enter a number(-1 to end): ");
while (inputs.hasNextInt()) {
//Accepts the inputs
int input = inputs.nextInt();
//Checks condition
if (input == -1) {
break;// breaks out of the loop is fails
}
nums.add(input);// else keep adding
}
System.out.println("Here is the list of numbers : ");
Collections.sort(nums);
for (Integer n : nums) {
System.out.println(n);
}

Arrays with user input

I am trying to write a program that repeatedly asks the user to supply scores (out of 10) on a test.It needs to continue until a negative value is supplied. Values higher than 10 should be ignored. I also calculated the average of the inputs. After the scores have been inputted, i need to use a single array to produce a table that automatically fills the test scores and the number of occurrences of the certain test score.
I wanted it to look something like this:
Score | # of Occurrences
0 3
1 2
2 4
3 5
4 6
and so on.. P
I am a beginner and this is my first question, so i am sorry if i made a mistake in posting the question or something.
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main()
{
Scanner kbReader= new Scanner (System.in);
int score[] = new int [10];//idk what im doing with these two arrays
int numofOcc []= new int [10];
int counter=0;
int sum=0;
for (int i=0;i<10;i++)// Instead of i<10... how would i make it so that it continues until a negative value is entered.
{
System.out.println("Enter score out of 10");
int input=kbReader.nextInt();
if (input>10)
{
System.out.println("Score must be out of 10");
}
else if (input<0)
{
System.out.println("Score must be out of 10");
break;
}
else
{
counter++;
sum+=input;
}
}
System.out.println("The mean score is " +(sum/counter));
}
}
You could use a do...while loop like this:
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main(String args[]) {
Scanner kbReader= new Scanner (System.in);
int scores[] = new int [10];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 10 or negative to break.");
input=kbReader.nextInt();
if (input<0) {
break;
} else if (input>10) {
System.out.println("Score must be out of 10");
} else {
scores[input]++;
counter++;
sum+=input;
}
} while (input>0);
System.out.println("Score\t# of occur...");
for(int i =0; i<10; i++) {
System.out.println(i + "\t" + scores[i]);
};
System.out.println("The mean score is " +(sum/counter));
}
}
The formatting can certainly be done better (without c-style tabs) but I don't remember the syntax at the moment.
I think what you need is a List Array! Create ArrayList from array
Think of it as a dynamic array, you don't need to specify the size of the array and it is expanded/made smaller automatically.
What you're missing is a while loop. Here is a nice way to loop through a Scanner for input. It also catches numbers greater than 10 and provides an error message:
public static void main() {
Scanner s = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
int response = 0;
while (response >= 0) {
System.out.print("Enter score out of 10: ");
response = s.nextInt();
if (response > 10) {
System.out.println("Score must be out of 10.");
} else if (response >= 0) {
list.add(response);
}
}
// Do something with list
}

Using a single-dimensional array, ask the user for input and display only NON-duplicate values

in my java class we were learning about arrays and this question came up. I have tried to solve it and can't seem to fulfill the requirements. I can read in the user inputs and have it limited to only 5 elements (one of the other requirements), also the values have to be between 10 and 100 I have also done that. But I cannot seem to "not print" the duplicate values. The array accepts the duplicate values. They don't have to be taken out, just not printed. Here is my code so far:
import java.util.Arrays;
import java.util.Scanner;
public class ArrayTest {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int size = 5;
int InpNum[] = new int[size];
for (int i = 0; i < InpNum.length; i++){
while (InpNum[i] <= i){
System.out.println("Please type a number between 10 and 100: ");
InpNum[i] = in.nextInt();
while (InpNum[i] < 10 || InpNum[i] > 100){
System.out.println("Error: Please type an integer between 10 and 100: ");
InpNum[i] = in.nextInt();
}
Arrays.sort(InpNum);
System.out.println(Arrays.toString(InpNum));
}
while (Search(InpNum, i) == true){
System.out.println("ERROR: Please enter a number that is not a duplicate of the other numbers you have entered");
InpNum[i] = in.nextInt();
}
}
}
// I can't seem to implement the method below in a useful manner.
public static boolean Search(int InpNum[], int searchedNum) {
for(int i : InpNum) {
if (i == searchedNum) {
return true;
}
}
return false;
}
}
I would consider restructuring your application.
Instead of placing the number the user inputs into the array immediately, store it in a local variable. Then run all the checks you need to run, and add it to the array only if it passes all of them.
You should only have one while loop in the whole program (the outer one). All those others are greatly confusing the issue and making the problem much harder than it has to be.
So, in psudo-code:
int index = 0;
while (true)
{
int num = in.nextInt();
// if not between 10 and 100, continue
// if it would make the array larger than 5, continue
// (or perhaps break out of the loop, since we've filled the array)
// if it is already in the array, continue
// all the checks passed, so add it to the array!
InpNum[index++] = num;
}
As a side note, what you really need is a Set. This is a collection which is guaranteed to have no duplicates and allows you to answer the question "do I contain this value?" in an efficient manner using the method Set.contains( Object ).
So I would create a TreeSet or HashSet and put every number the user types into it. Your Search function would then simply be a one liner calling contains( searchedNum ) on your set.
A lazy way is to just create a second array that can hold the values as you go.
Loop through the input array and put the current element into the new array IF that array doesn't have that element already.
Then replace the old array with the weened out one.
Easiest way
So what I do is first ask the number. Then save the number in a variable before entering it inside the array. Then I check if that number is already in it wih search. If it is I ask for a new number. If it is not I check if it is between 10 and 100, if it is not I ask for a new. I fit is I enter It inside the array. I have to check where an empty place is because the sort mixes up the array everytime
import java.util.Arrays;
import java.util.Scanner;
public class ArrayTest
{
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int size = 5;
int InpNum[] = new int[size];
for (int i = 0; i < InpNum.length; i++){
System.out.println("Please type a number between 10 and 100: ");
int number = in.nextInt();
//while (InpNum[i] <= i){
while (Search(InpNum, number) == true){
System.out.println("ERROR: Please enter a number that is not a duplicate of the other numbers you have entered");
number = in.nextInt();
}
while (number < 10 || number > 100){
System.out.println("Error: Please type an integer between 10 and 100: ");
number = in.nextInt();
}
int counter = 0;
for (int j = 0; j < InpNum.length && counter == 0; j++){
if(InpNum[j] == 0){
InpNum[j] = number;
counter++;
}
}
Arrays.sort(InpNum);
System.out.println(Arrays.toString(InpNum));
//}
}
}
// I can't seem to implement the method below in a useful manner.
public static boolean Search(int InpNum[], int searchedNum) {
for (int i = 0; i < InpNum.length; i++){
if (InpNum[i] == searchedNum) {
return true;
}
}
return false;
}
}

Categories

Resources