How to reject characters/ letters in a java program - java

When the program asks the user to input 10 elements (numbers), but the user entered any letter or word, I want the program to display "INVALID INPUT". I tried an if statement but it doesn't work. Any help is much appreciated!
This is my code:
int [] Array = new int[10];
int index;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 elements:");
for (int i = 0; i < 10; i++) {
Array[i] = input.nextInt();
}
System.out.print("Enter an index you want to retrieve: ");
index = input.nextInt();
System.out.print("Element at index "+index+" is " + Array[index]);
}
}

You can use a try-catch and catch a InputMismatchException, where you can then handle it accordingly.
Like so:
try{
int [] Array = new int[10];
int index;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 elements:");
for (int i = 0; i < 10; i++) {
Array[i] = input.nextInt();
}
System.out.print("Enter an index you want to retrieve: ");
index = input.nextInt();
System.out.print("Element at index "+index+" is " + Array[index]);
}catch(InputMismatchException e){
System.out.println("INVALID INPUT");
}
For example, when I input:
spectric is not cool
I get:
INVALID INPUT
Because spectric is cool

Try the following: You need to catch the input mismatch and then continue taking input. It is important to update the loop counter to allow for all 10 inputs to be taken.
int [] Array = new int[10];
int index;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 elements:");
for (int i = 0; i < 10; i++) {
try {
Array[i] = input.nextInt();
} catch(InputMismatchException ie) {
System.out.println("Bad input - please re-enter");
i--; // update loop;
input.nextLine();// clear bad input from buffer scanner.
}
}
System.out.print("Enter an index you want to retrieve: ");
index = input.nextInt();
System.out.print("Element at index "+index+" is " + Array[index]);

Related

The task is to write a java program to test if an array contains a specific value in java

I got confused and didn't know what to add or change the loops.
Can someone please help me and tell me what I should do in order to run my code? It would be a big help to me. I'm only a beginner in Java...
**here's my code: **
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
System.out.println("Enter "+ size + " values: \n");
for(i=0; i < num.length; i++){
x = input.nextInt();
num[i]=x;
if ( num [i] == x );
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
if ( num[i] == search){
System.out.println (search + " is found in the array!");
}
else{
System.out.println ("Your number is not in the array.");
}
}
}
The sample output of my task is (using scanner):
Input the size of the array: 4
Enter the values:
14
15
16
17
Enter the search value: 14
14 is found in your input array.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
// System.out.println("Enter "+ size + " values: \n");
for(i=0; i < num.length; i++){
System.out.println("Enter Number to add at index "+i+" : ");
x = input.nextInt();
num[i]=x;
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
boolean condition=false;
for(i=0; i < num.length; i++){
if ( num[i] == search){
condition=true;
break;
}
}
if(condition==true){
System.out.println("Number is Array!");
}
else{
System.out.println("Number is not in array");
}
}
your code is to be like this
there is logical error's in your code
to find an element you must traverse through array which can be achieved using loop so the last if else statement in your code must be in a loop
as due to the post increment in first loop after the completion of loop the value of i is one greater than last index of array so in if else statement at if ( num[i] == search) index is not found in array due to which it generates error.
for example I enter array size 3 and at num[0] I enter 1 at num[1] I enter 2 and at num[2] I enter 3 after the loop finishes the value of i become 3 when it come to conditional statement (if else) so it become if(num[3] == search ) but 3 index is not present in array so it generates error.
You need a loop to compare each element of the array with the search value.
boolean found = false;
for (int x : num)
if (x == search) {
found = true;
break;
}
System.out.println(found ? search + " is found in the array!" : "Your number is not in the array.");
Alternatively, with streams:
System.out.println(Arrays.stream(num).anyMatch(x -> x == search) ?
search + " is found in the array!" : "Your number is not in the array.");
Scanner input = new Scanner (System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
System.out.println("Enter "+ size + " values: \n");
for (i = 0; i < num.length; i++)
{
x = input.nextInt();
num[i] = x;
if (num[i] == x);
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
boolean flag=false;
for( i=0;i<num.length;i++)
{
if (num[i] == search) {
flag = true;
System.out.println(num[i]+" is found in your input array");
break;
}
}
if (flag==false)
{
System.out.println("Your number is not in the array.");
}
}
[Screenshot][1]

How to Get back/Return to a loop after catching a exceptional

I have this code that computes an Exponential example 3⁴ = 81.0 and the codes ask the user on how many numbers and exponent he wants to enter and when the user inputs numbers and exponents and he input an invalid input a letter the code will catch the java.util.InputMismatchException and stop. Are there any codes that can go back to the input numbers and exponent to enter again?
I've tried the boolean thing but it's not working and I'm searching about this thing but no one work.
try {
String[] unicode = {"\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079"};
System.out.print("Enter how many Numbers and Exponent you want to enter: ");
int userNum = new Scanner(System.in).nextInt();
ArrayList<Integer> num = new ArrayList<>();
ArrayList<Integer> nums = new ArrayList<>();
for (int i = 0; i < userNum; i++) {
System.out.print("Enter a Number: ");
int userNumber = new Scanner(System.in).nextInt();
num.add(userNumber);
System.out.print("Enter the exponent: ");
int userExponent = new Scanner(System.in).nextInt();
nums.add(userExponent);
}
for (int i = 0; i < userNum; i++) {
double answer = num.get(i);
for (int x = 0; x < nums.get(i) - 1; x++) {
answer *= num.get(i);
}
System.out.print(num.get(i));
for (int x = 0; x < String.valueOf(nums.get(i)).length(); x++) {
char g = String.valueOf(nums.get(i)).charAt(x);
String h = String.valueOf(g);
System.out.print(unicode[Integer.parseInt(h)]);
}
System.out.println(" = " + answer);
}
} catch (InputMismatchException exception) {
System.out.println(exception+" Invalid Input. Numbers Only.");
}
}
What I expect to this is when the user inputs an invalid input the program will catch java.util.InputMismatchException and print it and go back to inputs to input again
Ex.
Enter Num:12
Enter Exponent:asd
java.util.InputMismatchException
Enter Exponent:123
You should create some validation methods that will return boolean that means the validation was successful. Than you can use do while loop for asking for the input once again in case of a ValidationError. Something like this:
do {
System.out.print("Enter a Number: ");
String userInput = new Scanner(System.in).next();
} while (!validate(userInput));
num.add(Integer.parseInt(userInput));
You can also use the Scanner.hasNextInt() mtehod before trying to read int if the only restriction is to have valid int number.

Enter multiple numbers in console

So i have the following chuckj of code and what i want it do is for the user to enter 5 numbers in the netbeans console.The way i want to do it is he either can enter some by being separting the numbers with a space or line by line for exmaple like the following
But what i want is to "Enter a string of numbers" to be only visiable when it is needed to, for example when he needs to enter the next number. Is it possible to do this?
The following is done by the following code
Scanner reader = new Scanner(System.in);
int number;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 5; i++) {
System.out.println("Enter a string of numbers");
number = reader.nextInt();
numbers.add(number);
}
System.out.println("size" + numbers.size());
for(int takenNumber : numbers){
System.out.println(takenNumber);
}
You could do something like this:
Scanner reader = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();
int numbersEntered = 0; // Stores how many numbers the user has entered so far
while (numbersEntered < 5) { // Keep asking if they have not entered 5 numbers yet
System.out.println("Enter a string of numbers");
String[] input = reader.nextLine().split(" "); // Split the input by spaces into an array
numbersEntered += input.length; // Add the number of numbers they entered to the variable
for (int i = 0; i < input.length; i++) {
if (numbers.size() < 5) { // Only add the numbers if the list is not full
numbers.add(Integer.parseInt(input[i])); // Add each number they entered to the numbers list
}
}
}
You can use the hasNext() function of Scanner to keep reading while there is more input without doing another prompt. Try:
Scanner reader = new Scanner(System.in);
int number;
ArrayList<Integer> numbers = new ArrayList<Integer>();
int i = 0;
while((i < 5))
{
System.out.println("Enter a string of numbers:");
if(reader.hasNextLine())
{
String[] numbersRead = reader.nextLine().split("\\s");
System.out.print("Read:");
for(int n = 0; n < numbersRead.length; n++)
{
numbers.add(Integer.parseInt(numbersRead[n]));
i++;
}
System.out.println();
}
}

Java - summing up Array list values

I am building an array that ask how many different inputs you have, then allowing you to enter each input. At the end I want to sum them up, but I keep getting an error.
Also when I go above 5 inputs, I lose one..... For example when I respond to the first question: Enter "10". When I start adding different numbers in it stops at nine. Please help.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int[] numArr = new int[size];
System.out.println("Enter the number of CUs for each course: ");
for (int i=0; i<numArr.length; i++)
{
numArr[i] = input.nextInt();
}
int totalSum = numArr + totalSum;
System.out.print("The sum of the numbers is: " + totalSum);
Change your logic and code to the following:
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
System.out.println("Enter the number of CUs for each course: ");
int totalSum = 0;
for (int i = 0; i < size; i++) {
totalSum+=input.nextInt();
}
System.out.print("The sum of the numbers is: " + totalSum);
try
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int totalSum = 0;
for (int i=0; i< size; i++)
{
System.out.println("Enter the number of CUs for each course: ");
int cuNum = input.nextInt();
totalSum += cuNum ;
}
System.out.print("The sum of the numbers is: " + totalSum);
Pretty sure your intended result is
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int[] numArr = new int[size];
int totalSum = 0;
System.out.println("Enter the number of CUs for each course: ");
for (int i=0; i<numArr.length; i++)
{
numArr[i] = input.nextInt();
totalSum += numArr[i];
}
System.out.print("The sum of the numbers is: " + totalSum);
}
Your other code didn't work mainly because of
int totalSum = numArr + totalSum;
You can't define totalSum to defines itself! And you can't just use numArr... numArr is an array - you have to access indexes, not the array as a whole!

How can I limit the amount of strings printed on a single line

I want to be able to enter a string s and an integer n, then print the string s n times. I have done this, but I want there to be only 2 strings per line.
Here is my code so far:
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n; j++){
System.out.println(s);
}
if(n<0){
System.out.println("error: number must be positive");
}
}
Let's say the string was java and the number was 6. I need it to output:
java java
java java
java java
Use the modulo operator (%) to check if your loop index is evenly divisible by 2.
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=1; j<n+1; j++){
System.out.print(s);
if (j%2==0)
System.out.println("\n");
else
System.out.print(" ");
}
if(n<0){
System.out.println("error: number must be positive");
}
}
EDIT I changed the output to use print() instead of println() and added an empty space so the output is formatted as the example in your question. Also changed the for loop index to be one based so the mod works correctly.
Create a simple counter that counts to two inside your for loop. After it reaches two. Add a return character.
int count = 0;
for(int j=0; j<n; j++){
System.out.print(s);
count++;
if (count == 2) {
System.out.print("\n");
count = 0;
}
}
for(int j=0; j<n/2; j++){
System.out.println(s+" "+s);
}
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n; j++){
// modified
if(j%2==0 && j!=0){
System.out.println("\n");
}
System.out.print(s); // Should this not be print and not println
System.out.print(" ");
// end of modification
}
if(n<0){
System.out.println("error: number must be positive");
}
}
Try this code
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n/2; j++){
System.out.print(s + " " + s + "\n");
}
if(n%2 == 1){
System.out.print(s);
}
if(n<0){
System.out.println("error: number must be positive");
}
}

Categories

Resources