Some trouble in loop - java

Hi there,
I'm a newbie in java and I have a problem with this code. I'm thinking if it is a problem in loop or something..
public static void main(String[] args) {
try {
Scanner scn = new Scanner(System.in);
int z = 0;
String input;
int[] ABArray = new int[2];
while (z == 0) {
System.out.println("Input X to terminate.");
System.out.print("Input: ");
input = scn.nextLine().toLowerCase();
for (int i = 0; i < input.length(); i++) {
char AB = input.charAt(i);
ABArray[AB - 'a']++;
}
if (ABArray[0] == 0 || ABArray[1] == 0) {
System.out.println("Not Equal");
System.out.println("");
} else if (ABArray[0] == ABArray[1]) {
System.out.println("Equal");
System.out.println("");
} else if (ABArray[0] != ABArray[1]) {
System.out.println("Not Equal");
if (ABArray[0] > ABArray[1]) {
System.out.println("The number of A is greater than B.");
} else if (ABArray[0] < ABArray[1]) {
System.out.println("The number of B is greater than A.");
}
System.out.println("");
}
}
} catch (ArrayIndexOutOfBoundsException X) { } //Terminates the program
}
The problem is this
I/O
Input:
ABABAB
Output:
Equal
Input:
AABBB
Output:
Not Equal
The number of B is greater than A.
Input:
AABB //It is equal.
Output:
Not Equal //It says not.
The number of B is greater than A.
As you see, the problem is when I input equal A and B at the first, it says equal, when I input not equal A and B but at the third when I input equal A and B it says not equal.
Problem solved.
Thanks for the help.

You have to set all the values in ABArray to zero every time you start to work inside the while loop. Right now on the third time you start the while loop (with AABB input) you still keep the values which were left from the previous run of the loop - 5 in the 0-indexed element of an array and 6 in the 1-indexed element of an array, thus the program gives you the wrong output.

How about you simply read in the input into a string, then loop through it, counting the number of occurrences of each character you are interested in (here 'a' and 'b'), checking whether their counts are equal? So this works for example:
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
String input;
while (true) {
System.out.println("Input X to terminate.");
System.out.print("Input: ");
input = scanner.nextLine().toLowerCase();
if (input.equals("X")) {
break;
} else {
int countA = 0;
int countB = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'a') {
countA++;
} else if (input.charAt(i) == 'b') {
countB++;
}
}
if (countA == countB) {
System.out.println("Equal!");
} else {
System.out.println("Not equal!");
}
}
}
} catch (ArrayIndexOutOfBoundsException e) // Terminates the program
{
}
}

You can use this code:
public static void main( String[] args )
{
try
{
Scanner scn = new Scanner(System.in);
int z=0;
String input;
int[] ABArray = null;
while(z==0)
{
ABArray = new int[2];
System.out.println("Input X to terminate.");
System.out.print("Input: ");
input=scn.nextLine().toLowerCase();
for ( int i = 0; i < input.length(); i++ )
{
char AB=input.charAt(i);
ABArray[AB-'a']++;
}
if(ABArray[0]==0||ABArray[1]==0)
{
System.out.println("Not Equal");
System.out.println("");
}
else if(ABArray[0]==ABArray[1])
{
System.out.println("Equal");
System.out.println("");
}
else if(ABArray[0]!=ABArray[1])
{
System.out.println("Not Equal");
if(ABArray[0]>ABArray[1])
{
System.out.println("The number of A is greater than B.");
}
else if(ABArray[0]<ABArray[1])
{
System.out.println("The number of B is greater than A.");
}
System.out.println("");
}
}
}
catch(ArrayIndexOutOfBoundsException X) //Terminates the program
{
X.printStackTrace();
}
}

Related

Stuck with detecting next line from console

I am banging my head to the wall but just can't figure out what is going wrong. Simple program but not working. I need to get 3 inputs(integers) from user. End the program on either array full or when user presses enter. Here is what i am trying without any luck. It works fine all the situtations EXCEPT it cant detect nextline.
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
if (sc.next().isEmpty() || sc.next().equals("\n")){
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
Please help me . Why is it not detecting next line. I have googled already and tried lot of solutions provided but none worked for me. Any HELP!!!
Thanks
Edited code :
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
String next = sc.next();
if (next.isEmpty() || next.equals("\n"))
{
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
}
int[] intArray = new int[3];
int counter = 0;
boolean enterPressed = false; // added boolean to test if they entered a blank line
try (
Scanner sc = new Scanner(System.in); // declaring in a try-with-resources, so it automatically closes.
) {
System.out.println("Start!!");
System.out.println("Enter int"); // Have to print this the first time
while (counter < 3 && !enterPressed) {
if (counter > 0) { System.out.println("Enter int"); }
String next = sc.nextLine(); // just grab a line (the user pressed enter)
if (next.isEmpty()) {
enterPressed = true;
} else {
try {
intArray[counter] = Integer.parseInt(next);
counter++;
} catch (NumberFormatException ex) {
System.out.println("wrong input.");
}
}
}
}
Your code is sticking because it's waiting on the conditional check for sc.hasNextInt(). The solution I propose below, manually parses the user-input string to see if it's an int, rather than using the Scanner's functionality to check if it's an int or not.
I left some comments in the code to hopefully add clarity. Let me know if anything doesn't make sense, and I'm happy to elaborate!
import java.util.Arrays;
import java.util.Scanner;
public class ScannerTestNew {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
// Variable used to hold the user's input via the Scanner.
String userInput = null;
while (true) {
System.out.print("Enter an integer: ");
userInput = sc.nextLine();
// Check to see if an empty string/enter/return has been input:
if (userInput.length() == 0) {
System.out.println("Input is empty!");
break;
}
// Checking to see if the input can be parsed into an int. If it can't, retry.
int intInput = 0;
try {
intInput = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
System.out.println("Invalid input for type Integer. Please try again.");
continue;
}
// We know we have an int at this point. Checking that the array isn't already
// filled.
if (counter <= 2) {
intArray[counter] = intInput;
counter++;
// The array is filled, act accordingly.
} else if (counter > 2) {
System.out.println("Array is full.");
System.out.printf("Array Elements: %s", Arrays.toString(intArray));
break;
}
sc.close();
}
}
}

Why is my code not incrementing?

So my professor had us do an assignment that asks the user for 5 numbers that are valid (51-99) and unique (non-repeating). I just can't figure out why my nested for loop inside the while loop is not incrementing the i, I suspect it is the break; but without that the for loop keeps looping. Any help would be awesome. Thank you.
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
for (int i =0; i < userArray.length; i++) {
userArray[i] = count;
real++;
break;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int a) {
if (a > 50 && a < 100) {
return true;
} else {
return false;
}
}
I got it guys! I just had to remove the for loop and put this in:
userArray[i] = count;
i++;
real++;
Thank you schmidt73 and everyone that helped!
int i=0;
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
userArray[i++] = count;
real++;
} else {
System.out.println("That is not a valid number.");
}
}
I guess this is what you are trying to do.
First, you also need to test if the array contains the value you are trying to add (in validate). You could do something like
public static boolean isValid(int[] arr, int real, int a) {
if (a > 50 && a < 100) {
for (int i = 0; i < real; i++) {
if (arr[i] == a) {
return false;
}
}
return true;
}
return false;
}
Then your main method might be written like
int[] userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
if (isValid(userArray, real, count)) {
userArray[real++] = count;
} else {
System.out.println("That is not a valid number.");
}
}
System.out.println("The array contains: " + Arrays.toString(userArray));

Multiple of an Integer inside range

I am doing a school project and I kinda got blocked.
I am looking forward building a javascript that asks the user of a number between 1 and 20 and then finds and lists all the multiples of that number inside range 0 and 100.
Here is what it looks like at the moment:
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%100) == 0) {
System.out.println(n1);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
I am obviously bad at math cause I can't get the formula to work.
Thank you in advance!
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%i) == 0) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
All multiples that fall between 0 and 100? That's the kind of thing for-loops are made for. After performing your IO and reading the number n1, change that while loop to the following.
for (int i = n1; i >= 0 && i <= 100; i = i + n1) {
System.out.println(i);
}
In case you aren't familiar with for loops, this basically says, set i to the value of n1, and keep adding n1 to it, printing each value as you go. When it leaves the range of 0..100, it terminates. So for instance, if 8 is entered it goes 8, 16, 24, 32, ..., 80, 88, 96.
If you really want to use a while loop, then try:
int i = n1;
while(i >= 0 && i <= 100) {
System.out.println(i);
i = i + n1;
}
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1*i) <= 100) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
This should work. You were just finding if the number n1 was divisible by 100.

why the code does not respond and keep runing?

I am writing a program that translates from Roman numerals to decimal numbers.
For some reason it does not return the value when it checks the user's input. However it already fixed,
what I'm facing right now is: The code does not respond me the number (it's keep show a blank screen after the input).
How can I fix this? Is there an issue in my code? I am just a starter so what I have learned is just basic stuff.
public static void main(String[] args) {
// Fill in the body
Scanner in= new Scanner(System.in);
String user = promptUserForNumeral(in);
while (user.length()!=0) {
int numb= convertNumeralToNumber(user);
System.out.println("The numeral "+user+ " is the decimal number "+numb);
user = promptUserForNumeral(in);
}
}
private static String promptUserForNumeral(Scanner inScanner) {
// Fill in the body
System.out.println("Enter a roman numeral (Q to quit): ");
String i = inScanner.nextLine();
while (i.length()<=0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
return i;
}
private static int convertNumeralToNumber(String numeral) {
// Fill in the body
int numb = 0;
int n=0;
int ch=0;
while (n<numeral.length()) {
char l= numeral.charAt(n);
numb=convertCharacterToNumber(l);
if (numb<0) {
System.out.println("Cannot be define");
n++;
}
else if (n==numeral.length()) {
ch+=numb;
}
else {
int nnumb=convertCharacterToNumber(numeral.charAt(n));
if (nnumb>numb) {
ch+=nnumb-numb;
n++;
}
else {
ch+=numb;
}
}
}
if (ch>3999) {
System.out.println("Input number must be less than 3999");
numb=ch;
}
return numb;
}
private static int convertCharacterToNumber(char numeral) {
// Fill in the body
int n=0;
if (numeral=='m' || numeral =='M') {
return 1000;
}
else if (numeral=='d' || numeral=='D') {
return 500;
}
else if (numeral=='c' || numeral=='C') {
return 100;
}
else if (numeral=='l' || numeral=='L') {
return 50;
}
else if (numeral=='x' || numeral=='X') {
return 10;
}
else if (numeral=='v' || numeral=='V') {
return 5;
}
else if (numeral=='i' || numeral=='I') {
return 1;
}
else {
return -1;
}
}
}
public class stringTest {
public static void main(String[] args) {
// Fill in the body
Scanner in= new Scanner(System.in);
String user = promptUserForNumeral(in);
while (user.length()!=0) {
int numb= convertNumeralToNumber(user);
System.out.println("The numeral "+user+ " is the decimal number "+numb);
user = promptUserForNumeral(in);
}
}
private static String promptUserForNumeral(Scanner inScanner) {
// Fill in the body
System.out.println("Enter a roman numeral (Q to quit): ");
String i = inScanner.nextLine();
while (i.length()>=0) {
if (i.length()==0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
else if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
else return i; // in your program the while is never ending, so it does not return any value.
}
return "";
}
private static int convertNumeralToNumber(String numeral) {
// Fill in the body
int preNumber = 0;
int curNumber = 0;
int n=0;
int ch=0;
while (n<numeral.length()) {
char l= numeral.charAt(n);
curNumber=convertCharacterToNumber(l);
if (curNumber<0) {
System.out.println("Cannot be define");
System.exit(0);
}
else {
// I have changed the logic to evaluated decimal Number equivalent to Roman Literal
if(preNumber < curNumber && n != 0) ch = curNumber - ch;
else ch += curNumber;
preNumber = curNumber;
}
n++;
}
return ch;
}
private static int convertCharacterToNumber(char numeral) {
// Fill in the body
if (numeral=='m' || numeral =='M') {
return 1000;
}
else if (numeral=='d' || numeral=='D') {
return 500;
}
else if (numeral=='c' || numeral=='C') {
return 100;
}
else if (numeral=='l' || numeral=='L') {
return 50;
}
else if (numeral=='x' || numeral=='X') {
return 10;
}
else if (numeral=='v' || numeral=='V') {
return 5;
}
else if (numeral=='i' || numeral=='I') {
return 1;
}
else {
return -1;
}
}
}
You can probably look into promptUserForNumeral method, I think it is not necessary. You can include that in the main while loop to look for user errors.
Check this
while (i.length()>=0) {
if (i.length()==0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
else if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
}
return i;
This won't quit or return anything while i.length() > 0. That return is dead code if user didn't enterq.
Solution: Specify a else with break; then it will work.
else
break;
I would rewrite your while loop :
while (i.length()<=0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
return i;
You have lots of redundant conditions. The problem lies within this loop:
while (i.length() >= 0) {
if (i.length() == 0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
} else if (i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
}
Take any value for i like "V".
It's length is greater than zero, hence it enters the loop.
It's length is again not zero in the first if condition, hence it proceeds to the elseIf
Since the value isn't a "q", the else part doesn't execute either.
So it goes back to the loop's start & again checks the condition if length is greater than zero.
So, you have an infinite loop. Work through your logic again & remove any unnecessary conditions. You can also use the break; statement to terminate the loop.

Preventing input errors

I made this java code to input a number:
public static void main(String[] args)
{
int temp;
do{
Scanner scan = new Scanner(in);
out.print("enter number ");
temp = scan.nextInt();
if(temp >= 5 && temp <= 40){
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("|");
}
out.println();
y--;
z+=2;
}
for(int c = 0; c < 1 + temp/10; c++) {
for (int i = 0; i <= x / 2; i++)
{
System.out.print(" ");
}
System.out.println("|");
}
}else{
out.print("enter a number between 5 and 40");
}
}while(temp != 0);
}
}
However, this will return an error if I enter for example a letter or an invalid character. I would like to know how to, instead of making the program crash, make it display an error message and then asking again the question until the entry is correct?
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int temp=0;
boolean error=false;
do{
error=false;
try
{
Scanner scan = new Scanner(System.in);
System.out.print("enter number ");
temp = scan.nextInt();
if(temp==0)
break;
if(temp >= 5 && temp <= 40)
{
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
System.out.print(" ");
}
for(int k = 0; k<z; k++)
{
System.out.print("|");
}
System.out.println();
y--;
z+=2;
}
for(int c = 0; c < 1 + temp/10; c++)
{
for (int i = 0; i <= x / 2; i++)
{
System.out.print(" ");
}
System.out.println("|");
}
}
else
{
System.out.println("enter a number between 5 and 40");
}
}catch(Exception e)
{
System.out.println("Enter a valid number..try again");
error=true;
}
}while(temp != 0 || error);
}
}
When the error or exception occurs i.e. in scan.nextInt() an Exception is thrown and as you have not caught the exception the JVM stops executing the program.
So always write statements which can throw Exceptions within a try{ } block and immediately follow it with a catch(Exception e) {} block to catch the exception. If no exception occurs then catch block will not execute. If any error occurs inside try{} block : control jumps to catch block and it is executed and all other statements in try{} (after the erroneous line) are ignored.
try
{
..
error
.. // skipped
..
}
catch(Exception e)
{
...
...// handle exception
}
// control comes here after executing catch block
Read in the value from the user as a string and then try to parse it to a number in a try {} catch{} block, if an exception is thrown parsing it, tell the user only numbers are acceptable. if not continue processing with the number they gave you.
The Scanner has a method to check if the next token is an integer: hasNextInt.
You could do this:
package com.sandbox;
import java.util.Scanner;
public class Sandbox {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer:");
while (!scanner.hasNextInt()) {
System.err.println("Wrong! Enter an integer");
scanner.next();
}
System.out.println("Your integer was: " + scanner.nextInt());
}
}
This worked as you'd want on a windows console. I'm a little concerned it'll work incorrectly on Linux/Mac. Anyone mind testing it out for me? If this works, I like it best because there's no try/catch.
Extending from #Shouvik Roy's answer..
import java.util.Scanner;
public class Bingo {
public static void main(String[] args){
boolean isInt = false;
int temp;
System.out.print("enter a number ");
do{
Scanner scan = new Scanner(System.in);
try
{
temp = scan.nextInt();
isInt = true;
}
catch(Exception e)
{
System.out.println("Couldn't read number. Reason - "+e.getMessage());
System.out.println("Enter a valid number ");
}
}while(!isInt);
}
}
------------------Edit-------------------
boolean isInt = false;
System.out.print("enter a number ");
do{
try
{
Scanner scan = new Scanner(in);
temp = scan.nextInt();
isInt = true;
}
catch(Exception e)
{
System.out.println("Couldn't read number. Reason - "+e.getMessage());
System.out.println("Enter a valid number ");
}
}while(!isInt)

Categories