Validate a user's integer input? - java

I need to ensure that a user enters a number between 10 and 100. If they do not, I want them to enter a new number. In between the asterisks is where my problem is (I think). Thanks in advance.
import java.util.Scanner;
public class Duplicate
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] array = new int[5];
System.out.println("Enter 5 integers between 10 and 100 (inclusive):");
for (int i = 0; i < array.length; i++)
****if ((input.nextInt() <= 100) || (input.nextInt() >= 10))
{
array[i] = input.nextInt();
}
****else { System.out.print("Please enter a number greater than 9 and less than 101."); }
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + ", ");
System.out.println();
System.out.println("Unique values are: ");
for (int i = 0; i < array.length; i++) {
boolean show = true;
for (int j = 0; j < i; j++)
if (array[j] == array[i]) {
show = false;
break;
}
if (show)
System.out.print(array[i] + ", ");
}
}
}

if ((input.nextInt() <= 100) || (input.nextInt() >= 10))
array[i] = input.nextInt();
You are calling nextInt three times which reads the next three integers. So if the user enters 5 then 150, then -1, this will be the same as
if (5 <= 100 || 150 >= 10)
array[i] = -1;
which succeeds when it should not.
You are also using || (or) instead of && (and) so if the user entered 1 after the problem above is fixed, it would look like
if (1 <= 100 ||/* or */ 1 >= 10)
array[i] = 1;
which succeeds because 1 <= 100.
Instead, just read one int and use &&.
int userEnteredInt = input.nextInt();
if (10 <= userEnteredInt && userEnteredInt <= 100)
array[i] = userEnteredInt;

Related

Array program not running correctly. How do I fix it?

Trying to write a program that asks the a user for 10 integers as input. The program
places the even integers into an array called evenList, the odd integers into
an array called oddList, and the negative numbers into an array called
negativeList. The program displays the contents of the three arrays after
all of the integers have been entered.
This is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int countNeg = 0;
int countOdd = 0;
int countEven = 0;
int[] list = new int[10];
System.out.println("Please enter 10 integers:");
for(int i = 0; i < list.length; i++)
{
list[i] = scan.nextInt();
if(list[i] < 0)
{
countNeg++;
}
if(list[i] % 2 == 0 && list[i] > 0)
{
countEven++;
}
if(list[i] % 2 == 1 && list[i] > 0)
{
countOdd++;
}
}
int[] oddList = new int[countOdd];
int[] evenList = new int[countEven];
int[] negativeList = new int[countNeg];
for(int i = 0; i < list.length; i++)
{
if(list[i] < 0)
{
for(int j = 0; j < countNeg; j++)
{
negativeList[j] = list[i];
}
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 0 && list[i] > 0)
{
for(int j = 0; j < countEven; j++)
{
evenList[j] = list[i];
}
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 1 && list[i] > 0)
{
for(int j = 0; j < countOdd; j++)
{
oddList[j] = list[i];
}
}
}
for (int i : negativeList)
{
System.out.print(i + " ");
}
System.out.println();
for (int i : evenList)
{
System.out.print(i + " ");
}
System.out.println();
for (int i : oddList)
{
System.out.print(i + " ");
}
}
}
The program prints the Arrays with the correct amount of values but the wrong numbers. It prints only the last negative, even, or odd number to be input. ex input is 1, 2, 3, 4, 5, 6, -1, -2, -3, -4. For negativeList it prints -4 -4 -4 -4. Im guessing something is wrong in the loops after the arrays are created. Please help!!
you can very much simplify your code with using ArrayList instead of array. For example:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length = 10;
System.out.println("Please enter 10 integers:");
List<Integer> oddList = new ArrayList<>();
List<Integer> evenList = new ArrayList<>();
List<Integer> negativeList = new ArrayList<>();
for (int i = 0; i < length; i++) {
int n = scan.nextInt();
if (n < 0) {
negativeList.add(n);
} else if (n % 2 == 0) {
evenList.add(n);
} else {
oddList.add(n);
}
}
for (int i : negativeList) {
System.out.print(i + " ");
}
System.out.println();
for (int i : evenList) {
System.out.print(i + " ");
}
System.out.println();
for (int i : oddList) {
System.out.print(i + " ");
}
}
there are a few issues with the code you provided.
First, in the for loops that initialize the negativeList, evenList, and oddList arrays, you are overwriting the values at each iteration. This means that the final arrays will only contain the last value that was assigned to them. To fix this, you can use a counter variable to keep track of the next index to be filled in each array, like this:
int negCounter = 0;
int evenCounter = 0;
int oddCounter = 0;
for(int i = 0; i < list.length; i++)
{
if(list[i] < 0)
{
negativeList[negCounter] = list[i];
negCounter++;
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 0 && list[i] > 0)
{
evenList[evenCounter] = list[i];
evenCounter++;
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 1 && list[i] > 0)
{
oddList[oddCounter] = list[i];
oddCounter++;
}
}
Second, you are not checking if the input values are integers. If the user enters a non-integer value, the program will throw an exception. You can add a check to make sure that the input is an integer like this:
if(scan.hasNextInt())
{
list[i] = scan.nextInt();
// ... rest of the code
}
else
{
System.out.println("Please enter an integer.");
// If the input is not an integer, discard it and move to the next
input
scan.next();
}

How can I make my code lose the white space at the beginning?

main problem: extra whitespace in output
I want my code to print out a step of numbers from my input which I have gotten down. My main problem is the whitespace. I need the out put to be one less whitespace at the beggining.
Removing ' ' from my System.out.print();
changing the loop
Reversing the loop
segmentation
import java.util.Scanner;
public class PatternTwo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number 1...9 : ");
int num = scan.nextInt();
for(int i = 1; i <= num; ++i) {
for(int j=2*(num-i); j>=0; j--)
{
if (num <= 1)
System.out.print("");
else if (num > 1)
System.out.print(" ");
}
for(int j = i; j >= 1; --j) {
System.out.print(" " + j);
}
System.out.println();
}
}
}
}```
I would like the result to be
Please enter a number 1...9 : 2
1
2
Instead of:
Please enter a number 1...9 : 2
1
2
Two problems here:
j >= 0 should be changed to j > 0
You should avoid printing an empty space when j == i
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number 1...9 :");
int num = scan.nextInt();
scan.close();
for (int i = 1; i <= num; i++) {
for (int j = 2*(num-i); j > 0; j--)
if (num > 1)
System.out.print(" ");
for (int j = i; j >= 1; j--) {
if (j != i)
System.out.print(" ");
System.out.print(j);
}
System.out.println();
}
}
I received the following output with num = 5:
Please enter a number 1...9 :
5
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
Try in adding an if statement that skips the whitespace at the first time like:
for(int j = i; j >= 1; --j)
{
if(j == i)
System.out.print(j);
else
System.out.print(" " + j);
}

How to fix printing the even and odds when typing the same number

My code is working when i input different amount of numbers, but the issue is when i enter the same amount of number it wont show up in the ODD and EVEN section.
I tried manipulating it on //Getting the odd & even Section, but it ends up with no print output. I use the equation if (c[i] % 2 != 0) of getting the odd and if (c[i] % 2 == 0) for getting the even.
import java.util.Scanner;
public class Sample {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int a[] = new int[100];
int b[] = new int[100];
int c[] = new int[100];
int j, temp;
int i;
// Entering Class Size A
System.out.print("Enter class size: ");
int firstarraysize = in.nextInt();
// Input number A
for (i = 0; i < firstarraysize; i++) {
System.out.print("Enter Number: ");
a[i] = in.nextInt();
}
// Sorting Array A
for (i = 0; i < firstarraysize; i++) {
for (j = i + 1; j < firstarraysize; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
// Output A
i = 0;
System.out.print("A: ");
while (i < firstarraysize) {
System.out.print(a[i] + " ");
i++;
}
System.out.println();
System.out.println();
// Entering Class Size B
System.out.print("Enter class size: ");
int secondarraysize = in.nextInt();
// Input number B
for (i = 0; i < secondarraysize; i++) {
System.out.print("Enter Number: ");
b[i] = in.nextInt();
}
// Sorting Array B
for (i = 0; i < secondarraysize; i++) {
for (j = i + 1; j < secondarraysize; j++) {
if (b[i] > b[j]) {
temp = b[i];
b[i] = b[j];
b[j] = temp;
}
}
}
// Output B
i = 0;
System.out.print("B: ");
while (i < secondarraysize) {
System.out.print(b[i] + " ");
i++;
}
System.out.println();
System.out.println();
// Mixing Output A + B
int totalinputs = firstarraysize + secondarraysize;
for (i = 0; i < firstarraysize; i++) {
c[i] = a[i];
}
for (i = 0; i < secondarraysize; i++) {
c[i + firstarraysize] = b[i];
}
// Sorting C
for (i = 0; i < totalinputs; i++) {
for (j = i + 1; j < totalinputs; j++) {
if (c[i] > c[j]) {
temp = c[i];
c[i] = c[j];
c[j] = temp;
}
}
}
// Output C
i = 0;
System.out.print("C: ");
while (i < totalinputs) {
System.out.print(c[i] + " ");
i++;
}
System.out.println();
System.out.println();
// Getting the ODD numbers of C
System.out.print("Odd: ");
for (i = 0; i < c[i]; i++) {
if (c[i] % 2 != 0) {
System.out.print("" + c[i] + " ");
}
}
// Getting the EVEN numbers of C
System.out.println();
System.out.print("Even: ");
for (i = 0; i < c[i]; i++) {
if (c[i] % 2 == 0) {
System.out.print("" + c[i] + " ");
}
}
// Getting the Sum of the ODD numbers of C
System.out.println();
System.out.println();
System.out.print("Odd Sum: ");
int oddssum = 0;
for (i = 0; i < totalinputs; i++) {
if (c[i] % 2 != 0) {
oddssum = oddssum + c[i];
}
}
System.out.print(oddssum);
// Getting the SUM of the even numbers of C
System.out.println();
System.out.print("Even Sum: ");
int evensum = 0;
for (i = 0; i < totalinputs; i++) {
if (c[i] % 2 == 0) {
evensum = evensum + c[i];
}
}
System.out.print(evensum);
//Getting the Average of Oddssum + evensum
System.out.println();
System.out.print("Average: ");
double average = oddssum + evensum;
System.out.print(average/2);
}
}
Output:
Enter class size: 3
Enter Number: 2
Enter Number: 3
Enter Number: 1
A: 1 2 3
Enter class size: 3
Enter Number: 1
Enter Number: 2
Enter Number: 3
B: 1 2 3
C: 1 1 2 2 3 3
Odd: 1
Even:
Odd Sum: 8
Even Sum: 4
Average: 6.0
==============================================================================
*IF I INPUT DIFFERENT NUMBERS*
Enter class size: 3
Enter Number: 2
Enter Number: 3
Enter Number: 1
A: 1 2 3
Enter class size: 3
Enter Number: 8
Enter Number: 5
Enter Number: 6
B: 5 6 8
C: 1 2 3 5 6 8
Odd: 1 3 5
Even: 2 6 8
Odd Sum: 9
Even Sum: 16
Average: 12.5
When printing your even and odd numbers, you loop unil c[i] which is 1 when entering your provided input. Instead you should use the total quantity of numbers as limit:
for (i = 0; i < totalinputs; i++) {
if (c[i] % 2 != 0) {
System.out.print("" + c[i] + " ");
}
}
You have to do the same for your even numbers.
The problem with Odd and even numbers are the for-Loops:
for (i = 0; i < c[i]; i++) {
if (c[i] % 2 == 0) {
System.out.print("" + c[i] + " ");
}
You want to iterate trough c to find the odd and even numbers but what you actual doing is limiting the for loop ever round because you use c[i] as border which is 1 in first round and so stops immediately.
Try this loop:
int[] a = {1,2,3};
for(int i : a){
if(i%2 != 0){
//odd
} else {
//even
}

How to make hollow box with increasing and decreasing number at the side?

I have attempted a java program that includes hollow in the middle and numbers decrease and increase at the sides based on user's input.
Let say the user's input is 4, so the output should be like this:-
1 2 3 4
2 3
3 2
4 3 2 1
and i managed to do it until its like this:-
1 2 3 4
2
3
4 3 2 1
by using this code:
import java.util.*;
public class Exercise2 {
public static void main(String args[])
{
System.out.print("Enter an integer >0 and <21: ");
Scanner input = new Scanner (System.in);
int num = input.nextInt();
for (int i = 0; i < num; i++)
{
System.out.print((i+1) + " ");
}
System.out.println();
for (int j = 1; j < num-1; j++)
{
System.out.println((j+1) + " ");
}
// for (int j = num-1; j > 1; j--)
// {
// System.out.print(j + " ");
// }
for (int j = num; j > 0; j--)
{
System.out.print((j) + " ");
}
System.out.println();
if (num > 21 || num < 0)
{
System.out.println("Wrong number range");
}
}
}
I dont know how to do the other side of it to become 4 3 2 1 downwards. I tried uncommenting the commented codes and it gave 3 2 which is what i wanted but not in a straight line. I dont know where my error is. And i dont how to insert blank space (System.out.print(" ")) so that the hollow is actually something printed, not just blank.
Here's one way of doing it:
for (int i = 0; i < num; ++i) {
for (int j = 0; j < num; ++j) {
if (i == 0) {
System.out.print((j + 1) + " ");
} else if (i == num-1) {
System.out.print((num - j) + " ");
} else if (j == 0) {
System.out.print((i + 1) + " ");
} else if (j == num-1) {
System.out.print((num - i) + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}

initialize only some elements of array in java

So I want to skip the first and last elements of the array to initialize. What am I doing wrong?
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Columns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Here is my output:
Input Rows:
3
Input Columns:
3
Entered Values:
0 0 0
0 0 0
0 0 0
You need to change the if condition inside the loop like following:
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if ((i == 0 && j==0) || (i == m -1 && j == n -1)) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
In this line:
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
You are testing for the equality of values within your array. You should be comparing whether the indices you are looking at are the beginning or end of the array.
That is to say, you want to compare whether (in pseudo code):
i==0 and j==0, OR i==max index in its dimension and j==max index in its dimension
I have deliberately omitted the literal answer, because this looks a tiny bit like homework.
You compare the value of arr[i][j] with the value of arr[0][0]. You should instead compare i==0 && j==0 || i==m -1 && j==n -1
As your array was empty, and as you start the loop, arr[i][j] was equal to arr[0][0], skipping the first element. but for the next loop, arr[i][j] was still empty, and as you compare it to a non-initialised value, it's always true, skipping in each step
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Coloumns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i==0 && j==0 || i==m-1 && j==n-1) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
You don't need to check whether the array items are equal, you just want to check whether the row and column are equal to the last and first.

Categories

Resources