Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Trying to check command line for bad input with while loop so if wrong it will reprompt questions

Posted on 2004-09-08
3
233 Views
Last Modified: 2012-06-27
Hello, i hope this is an easy fix here is my problem..........

I'm trying to use the commandline to prompt the user for two things the degree of polynomial and its coefficients as follows but if it makes any error i want to reprompt the questions untill they answer correctly.I'll do this with a while true loop and 2 if statements if the two statements not entered flag will be false exit while loop continue calculation

enter degree:
enter coeff with spaces betwwen each ex 1 2 3:

then i'll use string tokenizer to get each coeeficient and place into an array. My problem is io need to make sure when they enter a degree these two cases are followed countTokens is number of coeff

1) if (degree < countTokens() ) thedn reprompt questions because degree was smallerthan the amount of coeff

2) if(degree +2 <=  countTokens() this would mean the array[degree+1] would give out of boundry exception because more coefficients than array allots

does this logic make sense?  so example input output

enter degree:3
coeff :1 2
so this would re ask question

enter degree:3
coeff: 1 2 3 4 5
reask question

enter deg:3
coef 1 2 3 4
ok ! this will break the loop.


so here is my code please any help will be greatly appreciated i can't get it to only respond when appriate datra is answered to stop array exceptions.

==============code=======================

boolean poly_flag=true;

                    while(poly_flag)
                    {


                        System.out.println("Enter in degree of polynomial : ");
                        main.setDegree( Integer.parseInt(buffer.readLine()) );             //grab degree from user input


                      System.out.println("Enter in non negative coefficients n for example 1 2 3 will be 1x^2 + 2x + 3");
                    coef_input = buffer.readLine();                            //grab coefficients from user input

                      coef = new int[main.getDegree() +1];    // allocate array size of degree plus one

                       token = new StringTokenizer(coef_input); //Use stringtokenizer to truncate coefficients


               int deg = main.getDegree();
                // check to make sure coefficients do not exceed array or are smallr than degree
                if( deg >=  token.countTokens() )
                {
                              
                    System.out.println("Your degree is bigger than the amount of coefficients please try again");
                    poly_flag=true
               }
                else
       poly_flag=false;


                  }//end while loop
0
Comment
Question by:tyweed420
3 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 12011705
>>because more coefficients than array allots

Any particular reason why you should limit this?
0
 

Author Comment

by:tyweed420
ID: 12012901
because i use degree +1 to allocate the array., so if thery enter more coef than array allows its wrong for the polynomial and it creates out of bounds exceptionm

is this not correct thinking
0
 
LVL 1

Accepted Solution

by:
jLasitha earned 50 total points
ID: 12012961
This may be the code that you want...

import java.io.*;
import java.util.*;

public class Polynomial {
   
   
    private static String read()throws Exception{
       
        BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
        return br.readLine();
    }

    public static void main(String[] args) {
       
        int[] aCoeff;
        do{
           
            try{
                System.out.print("Enter degree :");
                int degree = Integer.parseInt( read() );
                System.out.print("Enter coeff:");
                String coeff =   read();
               
                StringTokenizer st = new StringTokenizer( coeff );
               
                int noOfCoeff = st.countTokens();
               
                if( ( degree + 1 ) ==  noOfCoeff ){
                   
                    System.out.println("Ok! Break loop");
                    aCoeff = new int[ noOfCoeff ];
                    //Copy elements to the array
                    break;
                }
                else{
                   
                     System.out.println("Reasking...");
                }
            }catch( Exception e ){
               
                System.out.print( e.getMessage() );
            }
           
        }while(true);
    }
   
}
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
web services creation SOAP vs REST 5 57
hibernate insert example 13 34
Java string replace 11 54
ejb example issues 3 26
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question