Looking for a simple way for scanner to detect an empty entry ie. just an enter key - java.util.scanner

I am learning Java and using the scanner to detect and use int values. Everything works fine except that when I press enter without typing in any value I want the app to tell me that it is an invalid entry. Any help greatly appreciated.
My code is below.
int days = 0; // variable to store number of days
boolean isValidDay = false; // detects if the input is a valid number
// create a new scanner
// with the value from the console
Scanner input = new Scanner(System.in);
do
{
try
{
// Print question
System.out.print("Enter the number of days to record rainfall: ");
days = input.nextInt(); // Is it a valid Integer?
if (days <= 0)
{
System.out.println("The input is invalid. Please enter again!");
}
else
{
isValidDay = true;
}
}
catch (InputMismatchException e) // invalid Integer
{
System.out.println("The input is invalid. Please enter again!");
input.nextLine();
}
} while (!isValidDay); // keep repeating till we get a valid number for a day

Related

Need help understand how Strings work in my method

I am trying to understand how this convertingStringToInt method works. I am reading a file, storing the values in an array and am to pass those values to the method to be converted. In the parameters of convertingStringToInt, I have (String number) I don't get where the String "number" is getting its values. So I am passing in a string called numbers, but how is that newly created String associated with any of the values in my file...?!?
I am trying to understand the cause all the return numbers are the error code -460 except the last digit in the file. So the String numbers is associated with the file somehow I just don't get how...
public static void read_file()
{
try {
File file = new File("randomNumbers.txt");
Scanner scan = new Scanner(file);
int amountOfNumbersInFile = convertingStringToInt(scan.nextLine()); // read the first line which is 100 to set array size
global_numbers = new int[amountOfNumbersInFile]; // set the array size equal to the first line read which is 100
for (int index = 0; index < amountOfNumbersInFile; index++)
{
String line = scan.nextLine();
global_numbers [index] = convertingStringToInt(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static int convertingStringToInt(String numbers) //what does string "number" equal? why/where is it declared?
{
String numbers = scan.nextInt();
try {
return Integer.parseInt(numbers);
} catch (NumberFormatException n) {
return -460;
}
}
I have global_numbers declared as a global variable.
so the first thing u need understand is what u have in your txt file
if in this file you have only number is ok use stringToInt
but if you have words this never work properly

Logical error with the statement 'sc.nextLine();'

When I run this part of my program, it fails to recognize the two input statements using 'sc.nextLine();', but it accepts an entry for 'sc.next();'. Does anyone have any suggestions?
String information()
{
int l;char at;String nam,id,number;long contact;
System.out.println("\nPlease enter your name");
nam=sc.nextLine();
do
{
System.out.println("\nPlease enter your contact number");
contact=sc.nextLong();
number=Long.toString(contact);
l=number.length();
if(l<5||l>8&&l!=10)
error();
}
while(l<5||l>8&&l!=10);
System.out.println("\nPlease enter your e-mail id");
id=sc.nextLine();
int len=id.length();
for(int k=0;k<len;k++)
{
at=id.charAt(k);
if(Character.isWhitespace(at))
{
error();
break;
}
}
return nam;
}
Try sc.nextLine above the
nam = sc.nextLine();
It takes nextLine into an empty line so you need to clear the buffer first.

ObservableList producing errors

I made this program that produces 6 random numbers between 1 and 41. In the UI i have 6 textfields and a button. If i press the button the 6 numbers are being displayed in the textfields. I have 1 function(theNumbers()) fired when the button is pressed, the first function makes an ObservableList with the numbers 1-41 and the second function picks 6 numbers randomly.
The problem that happens is that after pressing the button a few times there is an ArrayIndexOutofBound Exception: -1 thrown, usually after (or a few times after) the number 0 is produced (which isnt even in the list) also sometimes a IndexOutOfBoundsException: Index: 4, Size: 4 exception is thrown(the number is random btw). Also it seems to be able to produce the same number twice or numbers bigger then 41.(seen 151)
This is my code:
First function:
ObservableList<Integer> list1 = FXCollections.observableArrayList();
private void createList(ObservableList<Integer> list1) {
this.list1 = list1;
int numbers = 41;
for (int i = 1; i <= numbers; i++) {
list1.add(i);
}
}
Second function:
private void theNumbers() {
createList(list1);
ObservableList<Integer> finalNums = FXCollections.observableArrayList();
try {
for (int i = 0; i < 6; i++) {
FXCollections.shuffle(list1);
int lucky = new Random().nextInt(list1.size());
finalNums.add(lucky);
list1.remove(list1.indexOf(lucky));
}
} catch (Exception ex) {
throw ex;
}
FXCollections.sort(finalNums);
textField1.setText(finalNums.get(0).toString());
textField2.setText(finalNums.get(1).toString());
textField3.setText(finalNums.get(2).toString());
textField4.setText(finalNums.get(3).toString());
textField5.setText(finalNums.get(4).toString());
textField6.setText(finalNums.get(5).toString());
list1.clear();
finalNums.clear();
}
Any clues to why it does this? Could it be my Acer Aspire One Netbook messing up? To my knowledge these errors shouldn't be happening.
Your code tries to remove the exact same number twice ore more in one pass of the for construct. For example you cannot remove the number "2" more than once from the list. The indexOf(2) method will return with -1 because it cannot find the value 2 in the list anymore.
So you might check if a number still exists in list1 before you try to remove from there.
private void theNumbers() {
createList(list1);
ObservableList<Integer> finalNums = FXCollections.observableArrayList();
try {
for (int i = 0; i < 6; i++) {
FXCollections.shuffle(list1);
int lucky;
do
{
lucky= new Random().nextInt(list1.size());
}while(list1.indexOf(lucky) == -1);
finalNums.add(lucky);
list1.remove(list1.indexOf(lucky));
}
} catch (Exception ex) {
throw ex;
}
That should solve your problem.
try using
int lucky = new Random().nextInt(list1.size()-1);

Cast from int to String on android

I'm developing an app where I need to send the values of 3 seekbars via bluetooth. All the bluetooth method I've developed is based on the bluetoothChat example. The app communicates well sending characters, but as i said, i need to send the value of 3 seekbars.
So, I'm creating a sending function to send these 3 values in one string, but i think that i'm doing wrong the cast because i'm getting an error and the logcat refers my to this point.
This is the code, need to mention that the "savedProgressX" values are int type and have the current value of the seekbar, and the "sendX" values are textview type that I've created only to save these values:
public void sendValues() {
send1 = Integer.toString(savedProgress1);
send2 = Integer.toString(savedProgress2);
send3 = Integer.toString(savedProgress3);
/**Set the seekbars values into a string*/
String message = send1+":"+send2+":"+send3+"\n";
//String[] values = message.split(":");
//for (String value : values) {
//int number = Integer.valueOf(value);
//}
/**Check that we're actually connected before trying anything*/
if (GlobalVar.mTransmission.getState() != GlobalVar.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
/**Get the message bytes and tell the Transmission to write*/
byte[] send = message.getBytes();
GlobalVar.mTransmission.write(send);
/**Reset out string buffer to zero*/
GlobalVar.mOutStringBuffer.setLength(0);
}

Menu driven palindrome tester getting stack Overflow error

I'm doing this for a class, and I'm really not terribly awesome at this as I'm over a decade out of practice. I'm trying to write a program that displays a menu so the user can choose between methods of determining if it's a palindrome.
It then needs to redisplay the menu once it has completed the test. I'm getting a stack overflow error in the isPalindrome method since I combined the 2 classes into one class, which I thought would fix another problem I was having with the output! Any thoughts or directions I can take?
import java.util.Scanner;
public class PalHelper
{
public String pal;
public void MenuList()
{
System.out.println("How would you like to check your phrase?");
System.out.println("1. Check the first letter like it's the last letter - Leave no phrase unturned!");
System.out.println("2. I Prefer my Palindromes have the gentle treatment");
System.out.println("3. We're done here");
System.out.print("Selection: ");
}
public PalHelper()
{
Scanner decision = new Scanner(System.in);
MenuList();
switch (decision.nextInt())
{
//to access the character by character method of determination
case 1:
System.out.print("Enter Phrase to Test, the Hard Way:");
Scanner keyboard1 = new Scanner(System.in); //declares scanner variable for user entry
String UserInput1 = keyboard1.next();//Phrase variable
Boolean test1 = isPalindrome(UserInput1);
if (test1 == true){
System.out.println(UserInput1+" is a palindrome. That doesn't make you smart.");
}
else {
System.out.println(UserInput1+" is a not palindrome. Why don't you think a little harder and try again.");
}
System.out.println("..\n..\n..\n");
keyboard1.close();
new MenuList();
break;
//to access the string buffer method of determination
case 2:
System.out.print("Thank you for choosing the gentle way, please enter your phrase:");
Scanner keyboard2 = new Scanner(System.in); //declares scanner variable for user entry
String UserInput2 = keyboard2.next();
Boolean test2 = isPalindrome2(UserInput2);
if (test2 == true){
System.out.println(UserInput2+" is a palindrome. Congratulations! You are so wonderful!");
}
else {
System.out.println(UserInput2+" is a not palindrome. It's ok, I'm sure you'll get it next time.");
}
System.out.println("..\n..\n..\n");
keyboard2.close();
new MenuList();
break;
//exit menu
case 3:
System.out.println ( "Too bad – I hid a boot!" );
break;
//response to input other than 1,2,3
default:
System.out.println ( "No sir! Away! A papaya war is on." );
System.out.println("..\n..\n..\n");
new MenuList();
break;
}// close switch
}//close pal helper
public void Palindrome(String UserInput) {
}
public boolean isPalindrome(String UserInput) {
pal = UserInput.toUpperCase();
if (pal.length() <= 1) {//one character, automatically a palindrome
return true;
}
char start = pal.charAt(0);
char end = pal.charAt(pal.length()-1);
if (Character.isLetter(start) &&
Character.isLetter(end)) {//check if first and last characters match
if (start != end) {
return false; //if the beginning & ending characters are not the same it's not a palindrome
}
else {
Palindrome subpal = new Palindrome(pal.substring(1,pal.length()-1));
return subpal.isPalindrome(); //check middle dropping start and end letters
}
}
else if (!Character.isLetter(start)) {
Palindrome subpal = new Palindrome(pal.substring(1));
return subpal.isPalindrome(pal); //check if first letter is a letter, drop if not
}
else {
Palindrome subpal = new Palindrome(pal.substring(0,pal.length()-1));
return subpal.isPalindrome(pal); //check if first letter is a letter, drop if not
}
}//close isPalindrome
public boolean isPalindrome2(String UserInput){
pal = UserInput.toUpperCase();
pal = pal.replaceAll("\\W", "");//gets rid of space and punctuation
StringBuffer check = new StringBuffer(pal);//reverses pal string and creates new stringbuffer for check
check.reverse();
if (check.toString().equals(pal)){//checks for equality between pal and it's reverse
return true;
}
else {
return false;
}
}//close isPalindrome2
public static void main (String[]args)
{
new PalHelper();
}//close main
}//close class
Aside from my comment above, there is a problem that I noticed: in some cases, you construct a new Palindrome instance with the substring, but pass the full string while recursing to the isPalindrome() method. This causes the recursion to never terminate (which also makes your code hard to follow).
Your example is missing something, the following line has missing closing brackets:
Palindrome subpal = new Palindrome(pal.substring(1,pal.length()-1);
Your comments dont seem to match the code:
return subpal.isPalindrome(pal); //check if first letter is a letter, drop if not
Try adding Output to the Method isPalindrome() or debug it. You are probably not calling it with the right Strings and end up looping over the same Strings over and over.
public boolean isPalindrome(String UserInput) {
System.out.println(UserInput);
...
Edit: If your code really is exaclty like you posted then vhallac is right, you call isPalindrome() with the full String.

Resources