How can I only accept integer input without try catch in Java - java

Scanner keyboard = new Scanner(System.in);
System.out.println("Enter number of bars(min 1 / max 6): ");
int barNumbers = keyboard.nextInt();
while (barNumbers <= 0 || barNumbers >= 7) {
System.out.println("Enter number of bars(min 1 / max 6): ");
barNumbers = keyboard.nextInt();
}
int barHeights[] = new int[barNumbers];
int countForBars = 1;
for (int i = 0; i <= barNumbers - 1; i++) {
System.out.println(
"Enter height of bar " + countForBars + " of " + barNumbers + "(min 1 / max 7): ");
barHeights[i] = keyboard.nextInt();
while (barHeights[i] <= 0 || barHeights[i] >= 8) {
System.out.println(
"Enter height of bar " + countForBars + " of " + barNumbers + "(min 1 / max 7): ");
barHeights[i] = keyboard.nextInt();
}
countForBars += 1;
}
Hi guys, I need some help which can be very easy for you because I'm a beginner of Java.
Anyway, I'm now trying to control a robot arm to convey stuff through Java.
The problem is that as you see there, I set some conditions to only get integer numbers between 1-6. So rest of inputs must be restricted especially string. So how can I restrict string input instead of using try catch stuff? If there is any helpful solution, I would appreciate of it. Cheers! And sorry for the code indication. I don't know how to make it like a code :(

May be you can try the following code:
public static boolean isInteger(String str) { //pass your "keyboard" string here.
if (str == null) { // if there is nothing entered in the String
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
}
for (i = 1; i < length; i++) {
char c = str.charAt(i);
if (c < '0' || c > '6') {
return false;
}
}
return true;
}

Related

While loop repeating too many times

I'm a first year in Computer Science Engineering, and I'm currently taking a Java programming course. It's the first programming language I've ever tried learning and I'm completely stuck. I had to design a program for class that takes a credit card number input from the user and determines whether or not it is valid. I've somehow messed up my loops, and now the whole thing keeps repeating at least 5 times more than I need it to. How could I fix this? It's due by 3:00 and I'm freaking out. Here is my code:
package osu.cse1223;
import java.util.Scanner;
public class Project07 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("Enter a credit card number (enter a blank line to quit):");
String cardNumber = in.nextLine();
int length = cardNumber.length();
if (length != 16 && length > 0) {
System.out.print("ERROR! Number MUST have exactly 16 digits");
}
else if (length <= 0) {
System.out.println("Goodbye!");
}
else {
char checkDigitChar = cardNumber.charAt(15);
int checkDigit = Character.getNumericValue(checkDigitChar);
int pos = 0;
while (pos < 16) {
char digit = cardNumber.charAt(pos);
int number = Character.getNumericValue(digit);
int doubled = number * 2;
pos = pos + 2;
int sum = 0;
if (doubled > 9) {
String sub = Integer.toString(doubled);
char one = sub.charAt(0);
char two = sub.charAt(1);
int numOne = Character.getNumericValue(one);
int numTwo = Character.getNumericValue(two);
int doubleAdjusted = numOne + numTwo;
sum = sum + doubleAdjusted;
}
else {
}
int newPos = 1;
int newSum = 0;
while (newPos < 16) {
char digitForSum = cardNumber.charAt(newPos);
int individualNum = Character.getNumericValue(digitForSum);
newPos = newPos + 2;
newSum = individualNum + newSum;
}
int total = sum + newSum;
String subTwo = Integer.toString(total);
char onesPlace = subTwo.charAt(1);
int ones = Character.getNumericValue(onesPlace);
int realCheckDigit = 10 - ones;
System.out.println("Check digit should be: " + realCheckDigit);
System.out.println("Check digit is: " + checkDigit);
if (checkDigit == realCheckDigit) {
System.out.println("Number is valid");
}
else {
System.out.println("Number is not valid");
}
}
}
}
}
You are not ending your first loop in the right place.
int doubleAdjusted = numOne + numTwo;
sum = sum + doubleAdjusted;
}
else {
}
}// ADD THIS TO END THE FIRST WHILE LOOP
And remove a } from the bottom of the code.
This loop repeats 8 times, but in fact it should be stoped after the first cycle. There are two ways to do this. First, you can add "break;" in the end of the last cycle. Second, you can not use "while (pos < 16) {}" loop at all. Both variants will give you the same result.
Here is the variant:
public class Various {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Enter a credit card number (enter a blank line to quit):");
String cardNumber = in.nextLine();
int length = cardNumber.length();
if (length != 16 && length > 0) {
System.out.print("ERROR! Number MUST have exactly 16 digits");
}
else if (length <= 0) {
System.out.println("Goodbye!");
}
else {
char checkDigitChar = cardNumber.charAt(15);
int checkDigit = Character.getNumericValue(checkDigitChar);
int pos = 0;
// while (pos < 16) {
char digit = cardNumber.charAt(pos);
int number = Character.getNumericValue(digit);
int doubled = number * 2;
// pos = pos + 2;
if (doubled > 9) {
String sub = Integer.toString(doubled);
char one = sub.charAt(0);
char two = sub.charAt(1);
int numOne = Character.getNumericValue(one);
int numTwo = Character.getNumericValue(two);
int doubleAdjusted = numOne + numTwo;
sum = sum + doubleAdjusted;
}
else {
}
int newPos = 1;
int newSum = 0;
while (newPos < 16) {
char digitForSum = cardNumber.charAt(newPos);
int individualNum = Character.getNumericValue(digitForSum);
newPos = newPos + 2;
newSum = individualNum + newSum;
}
int total = sum + newSum;
String subTwo = Integer.toString(total);
char onesPlace = subTwo.charAt(1);
int ones = Character.getNumericValue(onesPlace);
int realCheckDigit = 10 - ones;
System.out.println("Check digit should be: " + realCheckDigit);
System.out.println("Check digit is: " + checkDigit);
if (checkDigit == realCheckDigit) {
System.out.println("Number is valid");
}
else {
System.out.println("Number is not valid");
}
// break;
// }
}
}
}

I am trying to make a program which accepts two numbers and finds the prime, even and odd numbers in between

I am trying to make a program which will accept a starting number and ending number (int) and find the prime, even and odd numbers in between. I am not able to set my if and else conditions properly. It would be great if someone could even tell me a simpler method.
package proj2;
import java.util.Scanner;
public class Proj2
{
public void number(int sn,int en)
{
if (sn <= en)
{
int number = 2;
if (sn > number && sn % number != 0)
{
System.out.println(sn + " : " + "Prime");
number++;
sn++;
number(sn++,en);
}
else if (sn % 2 == 0)
{
System.out.println(sn + " : " + "Even");
sn++;
number(sn++,en);
}
else
{
System.out.println(sn + " : " + "Odd");
sn++;
number(sn,en);
}
}
}
public static void main(String [] abc)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the starting number:");
int x = sc.nextInt();
System.out.println("Enter the ending number:");
int y = sc.nextInt();
Proj2 p = new Proj2();
p.number(x,y);
}
}
Being prime and odd are not mutually exclusive, your primality test is incorrect, and you are recursively calling number(). Instead use:
private boolean isPrime(int num){
// assuming positive ints
if( num <= 2 || num % 2 == 0)
return false;
for(int divisor = 3; divisor <= (int)Math.pow(num, 0.5); divisor+=2)
if( num % divisor == 0)
return false;
return true
}
public void number(int start, int end){
if( start <= end ){
for( int curr = start; curr <= end; curr++ ){
if( curr % 2 == 1 ) {
System.out.println(curr + " : Odd");
if(isPrime(curr))
System.out.println(curr + " : Prime");
} else System.out.println(curr + " : Even");
}
}

Creating a Palindrome identifier

How can I add a statement that allows me to check if the credit card number inputted by the user is a palindrome? I am checking for the appropriate length already so how can i Input the new palindrome checker into this code:
import java.util.Scanner;
public class DT18 {
public static void main(String[] args) {
String number;
Boolean debug = false;
if (args.length == 0) { // no command line
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a Credit Card number to validate.");
number = keyboard.next();
} else { // command line input
number = args[0];
}
if (debug) System.out.println("String Length " + number.length());
if (number.length() < 10) {
System.out.println("Not Valid");
}
int sum = 0;
int oddDigit = 0;
for (int i = number.length() - 1; i >= 0; i--) {
if (debug) System.out.println("i = " + i);
if ((Character.getNumericValue(number.charAt(i)) < 0) || (Character.getNumericValue(number.charAt(i)) > 9)) {
System.out.println("Not Valid");
break;
}
if (i % 2 == 0) { //Even Digit
sum += Character.getNumericValue(number.charAt(i));
} else { //Odd Digit
oddDigit = (2 * Character.getNumericValue(number.charAt(i)));
if (oddDigit > 9) oddDigit = (oddDigit % 10) + 1;
sum += oddDigit;
}
if (debug) System.out.println(sum);
}
if (sum % 10 == 0) {
System.out.println("Valid");
} else {
System.out.println("Not Valid");
}
}
}
From an answer I once gave here:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}
This post should give you for loop logic:
http://www.programmingsimplified.com/java/source-code/java-program-check-palindrome
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
You can write a simple function to check if a string is a palindrome or not.
private static boolean checkPalindrome(String input) {
int i = 0, j = input.length() - 1;
for (; i < j; i++) {
if (i == j) {
return true;
}
if (input.charAt(i) == input.charAt(j)) {
j--;
}
else
return false;
}
return true;
}
This is a crude method; you may want to modify it according to your requirement, but it will get the job done in most of the cases.
I've looked over the other answers and all of them have bad performance and working with String instead of just using the given number. So I'll add the version without conversion to String:
public static boolean isPalindrome(int n) {
int[] digits = new int[length(n)];
for (int i = 0; n != 0; ++i) {
digits[i] = n % 10;
n /= 10;
}
for (int i = 0; i < digits.length / 2; ++i) {
if (digits[i] != digits[digits.length - i - 1]) {
return false;
}
}
return true;
}
public static int length(int n) {
int len = 0;
while (n != 0) {
++len;
n /= 10;
}
return len;
}
Not sure, if that's the best implementation, but I got rid of Strings :-)

Arithmetic Exception in Java, how to deal with it?

I'm making a program that counts the frequency of letters from a user-entered string, and have recently encountered the 'Arithmetic Exception' error.
I cannot for the life of me figure out what's causing it, even though I know it's because something is being divided by 0.
Here's my code:
package day1.examples;
import java.util.Scanner;
public class rl_frequency_count {
public static int input;
public static void main(String[] args) {
System.out
.println("Please enter some text that you would like to work out the occurence for.");
System.out
.println("However, do remember that any other characters outside of the alphabet will NOT be counted.");
Scanner stringUser = new Scanner(System.in);
String input = stringUser.nextLine();
input = input.replaceAll("\\s+", "");
input = input.toLowerCase();
// counting occurrence of character with loop
int i;
int charCountA = 0;
int charCountB = 0;
int charCountC = 0;
int charCountD = 0;
int charCountE = 0;
int charCountF = 0;
int charCountG = 0;
int charCountH = 0;
int charCountI = 0;
int charCountJ = 0;
int charCountK = 0;
int charCountL = 0;
int charCountM = 0;
int charCountN = 0;
int charCountO = 0;
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'a') {
charCountA++;
getOccurence(charCountA, "A");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'b') {
charCountB++;
getOccurence(charCountB, "B");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'c') {
charCountC++;
getOccurence(charCountC, "C");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'm') {
charCountM++;
getOccurence(charCountM, "M");
}
}
}
// method for the occurrence
public static void getOccurence(int number, String letter) {
double occ = number / input * 10; //
System.out.println();
System.out.println("Number of " + letter + "'s - " + number);
System.out.println("Occurence of " + letter + " - " + occ + "%");
}
}
I know that I only have ABC and M in at the moment but was gonna work those in later.
This is the first time i've posted on here and i'm still newish to Java so any help whatsoever is greatly appreciated!
I ran it and it says line 67. here is the total:
public static void getOccurence(int number,String letter){
double occ = number / input *10; //
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
To fix:
double occ = (number > 0) ? number/input * 10 : 0;
This sets occ to 0 in case of number being set to 0. Good luck.
Hope this helps.
The line of code causing the error is in your method:
public static void getOccurence(int number,String letter){
double occ = number / input *10; // <------ERROR FROM HERE (input is always 0)
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
The input variable is declared in your class here:
Line 6: public static int input;
Since you didn't initialize it nor does the value is being changed in your codes, the value of input remains as 0 through out the entire program. (Default value for an uninitialized int variable is 0)
Since it is always 0, you are always dividing a number with 0.
double occ = number / 0*10;

Counting the '1's in a binary number string - Java

This is part of my code, I was instructed to write a program that accepts a binary number as a string, and that will only show "Accepted" if the total number of 1's is 2. There is more to it, but getting to the point where it is counting the 1's is my problem at the moment. If anyone could point me in the direction of my error, it would be most appreciated.
import java.util.Scanner;
public class BinaryNumber
{
public static void main( String [] args )
{
Scanner scan = new Scanner(System.in);
String input;
int count = 0;
System.out.print( "Enter a binary number > ");
input = scan.nextLine( );
for ( int i = 0; i <= input.length()-1; i++)
{
char c = input.charAt(i);
if ((c == '1') && (c == '0'))
if (c == '1')
{count++;}
if (count == 2)
{System.out.println( "Accepted" );
}
if (count != 2)
{System.out.println( "Rejected" );
System.out.print( "Enter a binary number > ");
input = scan.nextLine( );
}
The problem is that if ((c == '1') && (c == '0')) will never be true.
You need to check if the character is 1 OR 0 and then check if it's a '1' to increment your counter.
int count;
Scanner scan = new Scanner(System.in);
String input;
boolean notValid = false; //to say if the number is valid
do {
count = 0;
System.out.print("Enter a binary number > ");
input = scan.nextLine();
for (int i = 0; i <= input.length()-1; i++){
char c = input.charAt(i);
if(c == '0' || c == '1'){
if (c == '1'){
count++;
if(count > 2){
notValid = true;
break; //<-- break the for loop, because the condition for the number of '1' is not satisfied
}
}
}
else {
notValid = true; // <-- the character is not 0 or 1 so it's not a binary number
break;
}
}
}while(notValid); //<-- while the condition is not reached, re-ask for user input
System.out.println("Done : " + input);

Categories

Resources