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]
Related
I was given the task of splitting my program which which allows the user to enter an array of numbers and after an odd number between 1 and 10 to check whether the odd number is a factor of each of the 5 numbers in the array. I keep on trying out different ways but none seem to work. Could someone help me out or send a sample of how I should sort it? This is the program:
import java.util.Scanner;
public class CheckboxExample{
public static void main(String args[]) {
CheckBox c = new CheckBox();
new CheckboxExample(); // links to checkbox class
Scanner s = new Scanner(System.in);
int array[] = new int[10];
System.out.println ("Please enter 10 random numbers"); // prompts the user to enter 10 numbers
int num; // declares variable num
try{
for (int i = 0; i < 10; i++) {
array[i] = s.nextInt(); // array declaration
}
}catch (Exception e){
System.out.println ("You have an error");
}
System.out.println ("Please enter an odd number between 1 and 10");
try{
num = s.nextInt ();
if (num % 2 == 0){
do{
System.out.println ("\nYour number is even, enter an odd one");
num = s.nextInt ();
}while (num % 2 == 0);
}
if (num < 0 | num > 10){
do{
System.out.println ("Your number is outside of the range, try again");
num = s.nextInt ();
}while (num < 0 | num > 10);
}
for (int i = 0; i < 5 ; i++){
if (array[i] % num == 0) {
System.out.println("Your number is a factor of " + array[i] );
}
}
}catch (Exception e){
System.out.println ("error");
}
}
}
A method should ideally be responsible for one task. In your case you should think about the different things your code try to do and organize them in a sense that each of the methods you call does one thing of the list of things you try to do.
As an example: As far as I understand your code does the following things:
Read an array of 10 values
Read an odd number
Verify the number is odd
Verify the number is in range
Calculate if the number is a factor of one of the 10 numbers in the array
Now one possible approach would be to separate your code in 5 methods that do exactly these things.
At first you call the method that reads the 10 numbers.
Then you call the method to read the odd number.
3. and 4. are actually part of reading the number, since you need to retry on an invalid input, so you could write your method for inputting the odd number in a way that it uses the methods for verifying the input.
Finally when you have all the valid input, you call the method which produces your result (ie. if the number is a factor of the numbers in the list).
A general outlier for your code could look like:
public class CheckboxExample {
public static void main(String args[]) {
CheckBox c = new CheckBox();
new CheckboxExample(); // links to checkbox class
Scanner s = new Scanner(System.in);
int array[] = readInputArray();
int number = readOddValue();
calculateFactors(array, number);
}
private int[] readInputArray() {...}
private int readOddValue() {...}
private void calculateFactors(int[] array, int number) {...}
//additional methods used by readOddValue which verify if the value is actually odd
}
Please note that this is just one way to split your code into methods and there are several ways to design and implement each of these methods.
I have a question to do in my Java class, and it asks me to write a program that takes in n numbers from the user and outputs the average of them. I know I could do it a much simpler way, just by asking the user to enter the amount of values (s)he needs to enter at the beginning, but I want to create the program so the user doesn't necessarily have to know the number of values at the beginning.
So for this, I create an array of 100 length (which hopefully covers the amount the user needs to enter) inside a for loop (rendering that 100 length array null after the loop, so the program doesn't become too memory heavy) and running a counter trough each iteration. Once the user enters stop, the loop ends, and the values entered into the 100 length array gets transferred to an array the size of the count.
Here is the code:
import java.util.*;
import java.lang.*;
public class main
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
//Question 1
System.out.println("Enter your numbers. (Enter 'Stop' when you're done)");
int temp = 0;
String uInput = "";
char stopper;
int count = 0;
double total = 0;
int a = 0;
boolean inStop = true;
for (boolean stop = false; stop != true;)
{
int array [] = new int [100];
if (inStop == true)
{
System.out.println("point 5");
System.out.print("Input: ");
uInput = input.nextLine(); //reads user input
}
try //empty input repeater
{
System.out.println("point 1");
try //dealing with letters in string instead of numbers
{
System.out.println("point 2");
temp = Integer.parseInt(uInput); //converts string to int
array[count] = temp;
count++;
System.out.println(inStop);
if (inStop == false) //executes when stop has been reached
{
System.out.println("point 3");
int numberArray [] = new int [count]; //fills final array
for (int i = 0; i < count; i++)
{
numberArray[i] = array[i];
}
for (a = 0; a < numberArray.length; a++)
{
total = total + numberArray[a];
}
total = total / a;
stop = true; //ends parent loop
}
}
catch (NumberFormatException e) //catches letters in string and checks for stop
{
System.out.println("point 4");
stopper = uInput.charAt(0);
stopper = Character.toUpperCase(stopper);
if (stopper == 'S')
{
inStop = false;
System.out.println("point 6");
}
}
}
catch (StringIndexOutOfBoundsException e)
{
}
}
System.out.println("The average of the values entered is: " + total + ".");
}
}
The problem is, as you can see there are numerous numbered printouts that indicate (to me) where the program is at the moment. All runs fine, except for point 3. Point 3 for some reason doesn't execute whatsoever. No matter what I do. Now, the problem lies on line 34, temp = Integer.valueOf(uInput); //converts string to int
If I put in a print function directly after that line, that position doesn't print onto the screen. I believe there are no syntax or logic errors with that part, and so does my lecturer, however the code still doesn't execute and the program loops infinitely afterwards. Something is breaking either temp or uInput in that line and we cannot figure out what. I have compiled and ran the code through a different compiler to what I initially used and even tried in the Command Prompt with the same results (so it is not the IDE causing the issue).
Any insight we may have missed would be appreciated. Thanks.
p.s.: don't knock my lecturer, he didn't write the code, and it isn't that easily readable. He could easily know what the problem is, if not for any error in my explanations or his interpretations of how my program is meant to run.
I think that the reason you are having a problem identifying the issue is because of your code structure.
You have mixed the logic for informing the use, with the logic for reading the inputs, and calculating.
If your main method only deal with informing the user, and relies on another method to calculate the average,and another to read the user's input everything will be easier to read, follow and see that you are parsing "stop" as an int.
public static void main(String[] args) {
System.out.println("instructions");
int[] all = readUserInputs();
double ave = calculateAverage(all);
System.out.println("message " + ave);
}
private static double calculateAverage(int[] numbers) {
// I will leave it to you to fill this out
return yourValue;
}
private static String readUserInputs() {
Scanner input;// as above
int[] values; // is an array best? What about a List?
for (int i = 0; ; i++) {
String line = input.nextLine();
if ("stop".equals(line) {
break;
}
//try to parse and put into array/list
}
return values;
}
Hopefully you will find this easier to read and work with,I have left a few gaps for you to fill in.
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;
}
}
I am a newbie and i have no idea what is wrong with my code here. I am going to write both the questions and my code here. Please if anyone can help me.
So the question says:
You have to tell the total number of chores the person can perform in the given time.
The first input is the total number of time the user got.
The second input is the total number of chores the user wants to perform.
The final inputs is the time it will take to complete each task.
and here goes my code:
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int totalmins, chores=0, eachtime, totalchores, counter=0;
// getting the input
System.out.println("Enter the total time:");
totalmins=scan.nextInt();
while (totalmins>100000) {
System.out.println("Enter again. Less than 100000:");
totalmins=scan.nextInt();
}
System.out.println("Enter the total chores:");
chores=scan.nextInt();
int [] time = new int[chores];
for (int i=1; i<chores; i++) {
System.out.println("Enter time:");
eachtime=scan.nextInt();
time[i]=eachtime;
}
// arranging in ascending order
for (int i=0;i<time.length; i++) {
if (time[i] > time[i+1]) {
int temp = time[i];
time[i]=time[i+1];
time[i+1]=temp;
}
}
for (int i=0;i<time.length; i++) {
totalchores=time[i] + time[i+1];
counter++;
if (totalchores>totalmins) {
counter=counter-1;
System.out.println(counter);
}
}
}
I think the point that you're missing is that in an array of length 3, the entries are numbered 0, 1 and 2. If you try to use entry number 3, you'll get that exception. But that's exactly what you're doing - all of your loops continue until i = 2 (including that case), but then you go ahead and try to use entry i + 1 of the array.
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;
}
}