Java True If Last Numbers Are 0 - java

I am trying to make a java program that will allow the user to enter any amount of numbers. If they enter a 0, the program will say the tree is false. I got that to work but I want it so if the last two numbers entered have are 0 the program will print true. The 0 represents null
For example if they enter 5 numbers:
2 4 5 0 0 = true
2 0 5 0 0 = false
2 4 5 6 7 = true
All that other stuff was confusing so I simplified it
System.out.println("Enter a number or enter 0 to represent null: ");
for(int i=0;i<num;i++)
{
arr[i] = input.nextInt();
if(arr[i] == 0)
{
isTree = false;
}
}
System.out.println("Is this a tree: " + isTree);

You can use regex "[1-9]+0{2}" => one or more number between 1 to 9 and finish with 2 zero.
Example with your code :
System.out.println("Enter a number or enter 0 to represent null: ");
java.util.regex.Pattern pattern = Pattern.compile("[1-9]+0{2}");
java.util.regex.Matcher matcher = pattern.matcher("20500");
boolean isTree = false;
while(matcher.find()) {
isTree = true;
}
System.out.println("Is this a tree: " + isTree);
You can try this tool for test your regex : https://www.debuggex.com/

Do what you are doing, but also check for two zeros at the end:
System.out.println("Enter a number or enter 0 to represent null: ");
for(int i=0;i<num;i++)
{
arr[i] = input.nextInt();
if(arr[i] == 0 && i < arr.length-2) //ignore if last two nodes
{
isTree = false;
}
}
boolean isTree2 = (arr[arr.length-1] == 0 && arr[arr.length-2] == 0)
|| (arr[arr.length-1] != 0 && arr[arr.length-2] != 0);
System.out.println("Is this a tree: " + (isTree && isTree2));

I think you want that if last two digits are zero then your program will say its true.
int length = arr.length;
boolean isTree = false;
if(length >= 2) {
if(arr[length-1] == 0 && arr[length-2] == 0) {
isTree = true;
}
}
System.out.println(isTrue);

System.out.println("Enter a number or enter 0 to represent null: ");
boolean cond = false;
for(int i=0;i<num;i++){
arr[i] = input.nextInt();
if(arr[i] == 0){
cond = true;
}
if(arr[i] !=0 && cond){
isTree = true;
break;
}
}
System.out.println("Is this a tree: " + isTree);

I wouldn't bother checking as you're entering input, but check after all inputs have been made. I would concatenate all your inputs into a string and then evaluate the string to determine if it satisfies your tree condition.
public static void main(String[] args) throws Exception {
int num = 5;
int[] arr = new int[num];
System.out.println("Enter a number or enter 0 to represent null: ");
for (int count = 0; count < 5; count++) {
for (int i = 0; i < num; i++) {
arr[i] = input.nextInt();
}
// Arrays.toString(arr) results in [2, 4, 5, 0, 0]
// Remove all brackets, commas, and spaces
String inputs = Arrays.toString(arr).replaceAll("\\[", "").replaceAll("\\]", "").replaceAll(", ", "");
boolean isTree = true;
// Only have to check for ending 00 if you know a 0 is in your inputs
if (inputs.contains("0")) {
isTree = inputs.endsWith("00") && !inputs.substring(0, inputs.length() - 2).contains("0");
}
System.out.println("Is this a tree: " + isTree);
System.out.println("");
}
}
Results:

Related

How to make while loop check if there are 16 digits in a string

How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!
import java.util.Scanner;
public class LuhnAlgorithm {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine();
int i = 0;
char chk = nums.charAt(15);
while(!nums .equals("") ) {
if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
}
int sum = 0;
for( i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if ( i % 2 == 0 ) {
num = num * 2;
if ( num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if ( sum2 == chk2) {
System.out.println("Number is valid.");
}
else {
System.out.println("Number is not valid. ");
}
System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
nums = input.nextLine();
}
System.out.println("Goodbye!");
input.close();
}
}
You can include your code that you only want done if the length ==16 in an if statement.
Meaning, instead of:
if (nums.length != 16) {
//code if there is an error
}
//code if there is no error
you can do:
if (nums.length == 16) {
//code if there is no error
} else {
//code if there is an error
}
(I also want to point out that you set chk = nums.charAt(15) before your while loop, but you don't reset it in the while loop for the next time the user inputs a new credit card number.)
You can bring the prompts and all your initialization except the scanner itself into the while loop. Then if they say "", break to exit the loop. If they say a number that is too short or too long, say continue to go back to the prompting.
Thus:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine().trim();
if (nums.length() == 0) {
break; //exits while loop
}
if (nums.length() != 16) { //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
continue; //goes back to the beginning right away
}
//still here, process the number
char chk = nums.charAt(15);
int sum = 0;
for (int i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if (i % 2 == 0) {
num = num * 2;
if (num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if (sum2 == chk2) {
System.out.println("Number is valid.");
} else {
System.out.println("Number is not valid. ");
}
}
System.out.println("Goodbye!");
input.close();
}
}

Java ISBN checksum generator -- infinite loop?

I need to build this ISBN checksum generator (for both ISBN-10 and ISBN-13) for my CS class using strings, chars, and a bunch of nested loops and conditional statements. Somewhere in this mess, I think something is triggering an infinite loop because when I am prompted for an input, I give the input and press enter and it just goes to a new line and expects me to enter a bunch more data I guess when instead it should be prompting me again to enter another one after each successful entry and otherwise tell me it's incorrect and then still again ask for another input. And when I type in quit it doesn't end the program and display the checksum results like it's supposed to, instead it exhibits the same behavior as other inputs do. If I type in quit the first time without giving the program any numbers it does end the program properly but of course, the values of the output variables are null.
My code thus far:
/******************************************************************************
* Program Name: Lab05A - ISBN
* Program Description: Calculate ISBN-10 AND ISBN-13
* Program Author: xxxxxxxxx
* Date Created: 10/10/2018
* Change# Change Date Programmer Name Description
* ------- ------------ ------------------- ---------------------
******************************************************************************/
package lab05a;
import java.util.Scanner;
public class Lab05A {
public static void main(String[] args) {
// Input for s
Scanner input = new Scanner(System.in); // Create new scanner
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: "); // our ever-lasting prompt
String s = input.next(); // declare string variable "s" and set it equal to next input from user.
String output10 = null; // Declaring string output10
String output13 = null; // Declaring string output13
// main while loop
while (!"QUIT".equals(s)) { //this will run as long as the program does not receive an input of "QUIT", not case sensitive.
char checkDigit;
char checkSum = '0';
if (s.length() == 9) { //if the length of the inputted string is 9 characters...
int sum = 0; // initialize sum variable
for (int i=0; i <= s.length();) {
sum = sum + ((s.charAt(i) - '0') * (i + 1));
}
if (sum % 11 == 10) {
checkDigit = 'X';
}
else {
checkDigit = (char) ('0' + (sum % 11));
}
output10 = output10 + "\n" + s + checkDigit;
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
else if (s.length() == 12) {
int sum = 0;
for (int i=0; i <= s.length();) {
if (i % 2 == 0) {
sum = sum + (s.charAt(i) - '0');
}
else {
sum = sum + (s.charAt(i) - '0') * 3;
}
checkSum = (char) (10 - sum % 10);
if (checkSum == 10) {
checkSum = 0;
}
output13 = "\n" + output13 + checkSum;
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
}
else if (!s.toUpperCase().equals("QUIT")) {
System.out.println(s + " is invalid input.");
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
}
System.out.println("The 10 digit ISBNs are \n" + output10);
System.out.println("The 13 digit ISBNs are \n" + output13);
}
}
Instructions
Flowchart as a separate image since it's kinda small in the instructions doc
Thanks for your help.
Yes, you are missing the incrementor in this for loop
for (int i=0; i <= s.length();) {
change to
for (int i=0; i <= s.length(); i++) {
I am sure that you do not want <=, maybe just <
so
for (int i=0; i < s.length(); i++) {
BTW this is easy to solve if you debug your code - an essential skill --
edit
If you have the below code (and s.length == 12)
for (int i=0; i < s.length(); i++) {
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
Then it will execute 12 times. Fix your loop
UPDATED CODE since I implemented some of the suggestions here:
package lab05a;
import java.util.Scanner;
public class Lab05A {
public static void main(String[] args) {
// Input for s
Scanner input = new Scanner(System.in); // Create new scanner
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: "); // our ever-lasting prompt
String s = input.next(); // declare string variable "s" and set it equal to next input from user.
String output10 = ""; // Declaring string output10
String output13 = ""; // Declaring string output13
// main while loop
while (!"QUIT".equalsIgnoreCase(s)) { //this will run as long as the program does not receive an input of "QUIT", not case sensitive.
char checkDigit;
char checkSum = '0';
if (s.length() == 9) { //if the length of the inputted string is 9 characters...
int sum = 0; // initialize sum variable
for (int i=0; i < s.length(); i++) {
sum = sum + ((s.charAt(i) - '0') * (i + 1));
}
if (sum % 11 == 10) {
checkDigit = 'X';
}
else {
checkDigit = (char) ('0' + (sum % 11));
}
output10 = output10 + "\n" + s + checkDigit;
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
else if (s.length() == 12) {
int sum = 0;
for (int i=0; i < s.length(); i++) {
if (i % 2 == 0) {
sum = sum + (s.charAt(i) - '0');
}
else {
sum = sum + (s.charAt(i) - '0') * 3;
}
checkSum = (char) (10 - sum % 10);
if (checkSum == 10) {
checkSum = 0;
}
output13 = "\n" + output13 + s + checkSum;
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
}
else if (!"QUIT".equalsIgnoreCase(s)) {
System.out.println(s + " is invalid input.");
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
}
System.out.println("The 10 digit ISBNs are \n" + output10);
System.out.println("The 13 digit ISBNs are \n" + output13);
}
}

check isbn 10 number java

I should make a programm to control the number of an isbn 10 number. Therefore I'm not allowed to use arrays andd the input of the number has to be a char. The In method is similar to java scanner.
public class ISBN {
public static void main(String[] args) {
System.out.println("ISBN - Pruefung");
System.out.println("=================");
System.out.print("ISBN-Nummer: ");
char isbn = In.read();
int check = 0;
int d=0;
for (d=0; d<10; d++) {
if ('0' <= isbn && isbn <= '9' ) {
check = (int) ((isbn-48)*d)+check;
if(d ==9) {
int lastDigit = check%11;
if(lastDigit ==10) {
System.out.println("x");
}else {
System.out.println(lastDigit);
}
}else {
System.out.print(isbn);
}
}else {
System.out.println(isbn + "Falsche Eingabe");
System.exit(0);
}
isbn = In.read();
}
if (d == 10 && check%11 ==0) {
System.out.println("wahr");
}else {
System.out.println("falsch");
}
}
}
I googled some isbn 10 numbers but my programs says they are wrong (example 2123456802). Now my question where is my mistake and/or understood I the function of the last number wrong?
the sum of all the ten digits, each multiplied by its (integer) weight, descending from 10 to 1, is a multiple of 11.
So you just need to sum that digit value time the weight :
int check = 0;
for(int weight = 10; weight > 0; weigth--){
char c = In.read(); //get the next character
int i;
if( c == 'x' || c == 'X' ){
i = 10;
} else {
if(! Character.isDigit(c)) //Because, just in case...
throw new IllegalArgumentException("Not a numeric value");
i = Character.getNumericValue( c );
}
check += i * weight;
}
Just need to check if it is a multiple of 11
if ( check % 11 == 0 )
System.out.println( "VALID" );
else
System.out.println( "INVALID" );

Entering an if statement

In this segment of code, from everything I'm seeing, it should be entering the for loop and then the if statement as long as you enter 1's and 0's, which is what I'm doing. It's not entering it, as I've seen from my print statements.
I don't see a reason why.
If it did enter the if statement, I also am unsure what to do because my suspicion is that it will only set true if the last bit is not a 1 or 0: my intention being for zeroesAndOnes to be false if anything except 1's and 0's are entered. However, as it stands, it's false all the time.
System.out.println("Please enter a 32 bit number consisting of "
+ "1's and 0's.");
String number = kb.nextLine();
int count = 0;
boolean zeroesAndOnes = false;
for(int i = 0; i < number.length(); i++){
if(number.charAt(i) == '0' || number.charAt(i) == '1'){
zeroesAndOnes = true;
System.out.println("If boolean " + zeroesAndOnes);
}
else{
zeroesAndOnes = false;
count++;
}
}
System.out.println("If boolean end " + zeroesAndOnes);
if(number.length() == 32 && count > 1){
if(number.charAt(0) + number.charAt(1) % 2 == 1){
symmDiff = 1;
}
else{
symmDiff = 0;
}
for(int i = 2; i < number.length(); i++){
if((symmDiff + number.charAt(i)) % 2 == 1){
symmDiff = 1;
}
else{
symmDiff = 0;
}
}
System.out.println("The parity bit for this number is " + symmDiff);
}
else{
System.out.println("These numbers do not match the specification.");
}
When checking for char equality, be sure the comparison is what you need. For instance
if(number.charAt(i) == 0)
checks for decimal value equality. To check for an actual '0' char, compare the char value
if ( number.charAt(i) == '0' )
for comparing a char you should use
if(number.chartAt(i) == '0')
another issue is number.charAt(0) will give you char not int. so when you are doing
number.charAt(0)+number.charAt(1) //you are concatenating character at index 0 and index 1
// do this
int first = Integer.parseInt(number.substring(0,1));
int second = Integer.parseInt(number.substring(1,2));
if( (first+second)%2 == 1){
// your statement
}

How to check if every odd index in a string has the same letter?

I'm working on this program where I need to verify if every odd index in a String has the letter "X". For example if my String is: AXFXTX then I should get a message: "GOOD", if not I should get a message: "BAD". Can anyone tell me what I'm missing please. Thank you in advanced.
Here's my code
import java.util.Random;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int min = 1;
int max = 10;
int randomNum = rand.nextInt((max - min) + 1) + min;
System.out.println("Random number = " + randomNum);
System.out.print("Enter a word of " + randomNum + " characters:");
String myString = scan.nextLine();
while(myString.length() != randomNum){
System.out.print("Enter a word of " + randomNum + " characters:");
myString = scan.nextLine();
}
char[] c = myString.toCharArray();
for(int i = 0 ; i < c.length ; i++){
if(c[i] == 'X'){
System.out.println("GOOD!");
}
else{
System.out.println("BAD");
}
}
}
}
If I understand your question, then it's important to note that the first odd index is 1. So you can start at 3 and check if that, and every subsequent odd number (index += 2), is the same as the first. Something like,
boolean sameLetter = true;
for (int index = 3; index < c.length && sameLetter; index += 2) {
sameLetter = (c[1] == c[index]);
}
System.out.println(sameLetter ? "GOOD!" : "BAD");
Simply evaluate odd indices only:
char[] c = myString.toCharArray();
boolean good = true;
for(int i = 3 ; i < c.length ; i+=2){
if(c[i] != c[i-2]){
good = false;
break;
}
}
if(good) System.out.println("GOOD");
else System.out.println("BAD");
I would simply use a regular expression here
str.matches(".(\\w)(.\\1)+") //true is GOOD
Try
booelan allGood = true;
for(int i = 2 ; i < c.length ; i = i + 2){
if(c[i] != c[0]){
allGood = false;
break;
}
}
To start with, you need a boolean variable here to track if it's consistent across all characters. Second, you need to improve your loop
boolean testSucceed = true;
for(int i = 1 ; i < c.length ; i += 2){
if (c[i] != 'X') testSucceed = false;
break;
}
if(testSucceed){
System.out.println("GOOD!");
} else{
System.out.println("BAD");
}
Change the for loop to :
for(int i = 0 ; i < c.length ; i+=2)
so that it goes over alternate characters.
//If NOT divisible by 2- Check only ODD number
Edited: You are suppossed to use modulus % and not division %. My bad
for(int i = 0 ; i < c.length ; i++){
if(c[i]%2 != 0){
if(c[i] == 'X'){
System.out.println("GOOD!");
}
else{
System.out.println("BAD");
}
}
}

Categories