Search Results

Search found 50 results on 2 pages for 'userinput'.

Page 1/2 | 1 2  | Next Page >

  • how to userinput without typing to a batch file

    - by Blood hound
    I am trying to run a batch file which requires user input "y/n" to do further action , I want to call this batch file for automation , as during automation argument yes or no need to be passed without user intervention , any idea how to achieve it ? cmd /c setup.bat now if setup.bat is run " yes or no " need to be selected to get the desired result as now this setup.bat is called during automation, is there is anyway to pass "yes" parameter as an input to setup.bat

    Read the article

  • Call methods in main method

    - by Niloo
    this is my main method that gets 3 integers from command line and I parse then in my validating method. However I have one operation method that calls 3 other methods, but i don't know what type of data and howmany I have to put in my operatinMethod() " cuase switch only gets one); AND also in my mainMethod() for calling the operationMehod(); itself? please let me know if i'm not clear? Thanx! main method: public class test { // Global Constants final static int MIN_NUMBER = 1; final static int MAX_PRIME = 10000; final static int MAX_FACTORIAL = 12; final static int MAX_LEAPYEAR = 4000; //Global Variables static int a,b,c; public static void main (String[] args) { for(int i =0; i< args.length; i++){} if(validateInput(args[0],args[1],args[2])){ performOperations(); } } //Validate User Input public static boolean validateInput(String num1,String num2,String num3){ boolean isValid = false; try{ try{ try{ a = Integer.parseInt(num1); if(!withinRange(a,MIN_NUMBER, MAX_PRIME)) { System.out.println("The entered value " + num1 +" is out of range [1 TO 10000]."); } isValid = true; } catch(Exception ex) { System.out.println("The entered value " + num1 + " is not a valid integer. Please try again."); } b = Integer.parseInt(num2); if(!withinRange(b,MIN_NUMBER, MAX_FACTORIAL)) { System.out.println("The entered value " + num2 +" is out of range [1 TO 12]."); } isValid = true; } catch(Exception ex) { System.out.println("The entered value " + num2 + " is not a valid integer. Please try again."); } c = Integer.parseInt(num3); if(!withinRange(c,MIN_NUMBER, MAX_LEAPYEAR)) { System.out.println("The entered value " + num3 +" is out of range [1 TO 4000]."); } isValid = true; } catch(Exception ex) { System.out.println("The entered value " + num3 + " is not a valid integer. Please try again."); } return isValid; } //Check the value within the specified range private static boolean withinRange(int userInput ,int min, int max){ boolean isInRange = true; if(userInput < min || userInput > max){ isInRange = false; } return isInRange; } //Perform operations private static void performOperations(int userInput) { switch(userInput) { case 1: // count Prime numbers countPrimes(a); break; case 2: // Calculate factorial getFactorial(b); break; case 3: // find Leap year isLeapYear(c); break; } } // Verify Prime Number private static boolean isPrime(int prime) { for(int i = 2; i <= Math.sqrt(prime) ; i++) { if ((prime % i) == 0) { return false; } } return true; } // Calculate Prime private static int countPrimes(int userInput){ int count =0; for(int i=userInput; i<=MAX_PRIME; i++) { if(isPrime(i)){ count++; } } System.out.println("Exactly "+ count + " prime numbers exist between "+ a + " and 10,000."); return count; } // Calculate the factorial value private static int getFactorial(int userInput){ int ans = userInput; if(userInput >1 ){ ans*= (getFactorial(userInput-1)); //System.out.println("The value of "+ b +"! is "+ getFactorial(userInput)); } return ans; } // Determine whether the integer represents a leap year private static boolean isLeapYear(int userInput){ if (userInput % 4 == 0 && userInput % 400 == 0 && userInput % 100 ==0){ System.out.println("The year "+ c +" is a leap year"); } else { System.out.println("The year "+ c +" is a not leap year"); } return false; } }

    Read the article

  • Java Scanner class reading strings

    - by Max
    I've created a scanner class to read through the text file and get the value what I'm after. Let's assume that I have a text file contains 1 : Fnjiei : ID 7868860 : Age 18 2 : Oipuiieerb : ID 334134 : Age 39 3 : Enekaree : ID 6106274 : Age 31 I'm trying to get a name and id number and age, but everytime I try to run my code it gives me an exception. Here's my code. Any suggestion from java gurus?:) public void readFile(String fileName)throws IOException{ Scanner input = null; input = new Scanner(new BufferedReader(new FileReader(fileName))); try { while (input.hasNextLine()){ int howMany = 3; System.out.println(howMany); String userInput = input.nextLine(); String name = ""; String idS = ""; String ageS = ""; int id; int age; int count=0; for (int j = 0; j <= howMany; j++){ for (int i=0; i < userInput.length(); i++){ if(count < 2){ // for name if(Character.isLetter(userInput.charAt(i))){ name+=userInput.charAt(i); // store the name }else if(userInput.charAt(i)==':'){ count++; i++; } }else if(count == 2){ // for id if(Character.isDigit(userInput.charAt(i))){ idS+=userInput.charAt(i); // store the id } else if(userInput.charAt(i)==':'){ count++; i++; } }else if(count == 3){ // for age if(Character.isDigit(userInput.charAt(i))){ ageS+=userInput.charAt(i); // store the age } } id = Integer.parseInt(idS); // convert id to integer age = Integer.parseInt(ageS); // convert age to integer Fighters newFighters = new Fighters(id, name, age); fighterList.add(newFighters); } userInput = input.nextLine(); } } }finally{ if (input != null){ input.close(); } } } My appology if my mere code begs to be changed.

    Read the article

  • User input... How to check for ENTER key

    - by user69514
    I have a section of code where the user enters input from the keyboard. I want to do something when ENTER is pressed. I am checking for '\n' but it's not working. How do you check if the user pressed the ENTER key? if( shuffle == false ){ int i=0; string line; while( i<20){ cout << "Playing: "; songs[i]->printSong(); cout << "Press ENTER to stop or play next song: "; getline(cin, line); if( line.compare("\n") == 0 ){ i++; } } }

    Read the article

  • C# dealing with invalid user input

    - by Zka
    Have a simple console app where user is asked for several values to input. Input is read via console.readline(). Ex Name: Fred //string Lastname: Ashcloud //string Age: 28 //int I would like to make sure that int and double types are entered and if the user enters garbage, lets him repeat the procedure. Example, if the user enters "28 years old" where age expects int the app will crash. What is the best way to check for these inputs? Right now I can only think of: while (!Int32.TryParse(text, out number)) { Console.WriteLine("Error write only numbers"); text = Console.ReadLine(); } Is there any other way to do this? try catch statements if one wants to give a more detailed feedback to the user? How in that case?

    Read the article

  • C++ Detecting ENTER key pressed by user

    - by user69514
    I have a loop where I ask the user to enter a name. I need to stop when the user presses the ENTER key..... or when 20 names have been entered. However my method doesn't stop when the user presses the ENTER key //loop until ENTER key is entered or 20 elements have been added bool stop = false; int ind = 0; while( !stop || ind >= 20 ){ cout << "Enter name #" << (ind+1) << ":"; string temp; getline(cin, temp); int enterKey = atoi(temp.c_str()); if(enterKey == '\n'){ stop = true; } else{ names[ind] = temp; } ind++; }

    Read the article

  • Qt C++ signals and slots did not fire

    - by Xegara
    I have programmed Qt a couple of times already and I really like the signals and slots feature. But now, I guess I'm having a problem when a signal is emitted from one thread, the corresponding slot from another thread is not fired. The connection was made in the main program. This is also my first time to use Qt for ROS which uses CMake. The signal fired by the QThread triggered their corresponding slots but the emitted signal of my class UserInput did not trigger the slot in tflistener where it supposed to. I have tried everything I can. Any help? The code is provided below. Main.cpp #include <QCoreApplication> #include <QThread> #include "userinput.h" #include "tfcompleter.h" int main(int argc, char** argv) { QCoreApplication app(argc, argv); QThread *thread1 = new QThread(); QThread *thread2 = new QThread(); UserInput *input1 = new UserInput(); TfCompleter *completer = new TfCompleter(); QObject::connect(input1, SIGNAL(togglePause2()), completer, SLOT(toggle())); QObject::connect(thread1, SIGNAL(started()), completer, SLOT(startCounting())); QObject::connect(thread2, SIGNAL(started()), input1, SLOT(start())); completer->moveToThread(thread1); input1->moveToThread(thread2); thread1->start(); thread2->start(); app.exec(); return 0; } What I want to do is.. There are two seperate threads. One thread is for the user input. When the user enters [space], the thread emits a signal to toggle the boolean member field of the other thread. The other thread 's task is to just continue its process if the user wants it to run, otherwise, the user does not want it to run. I wanted to grant the user to toggle the processing anytime that he wants, that's why I decided to bring them into seperate threads. The following codes are the tflistener and userinput. tfcompleter.h #ifndef TFCOMPLETER_H #define TFCOMPLETER_H #include <QObject> #include <QtCore> class TfCompleter : public QObject { Q_OBJECT private: bool isCount; public Q_SLOTS: void toggle(); void startCounting(); }; #endif tflistener.cpp #include "tfcompleter.h" #include <iostream> void TfCompleter::startCounting() { static uint i = 0; while(true) { if(isCount) std::cout << i++ << std::endl; } } void TfCompleter::toggle() { // isCount = ~isCount; std::cout << "isCount " << std::endl; } UserInput.h #ifndef USERINPUT_H #define USERINPUT_H #include <QObject> #include <QtCore> class UserInput : public QObject { Q_OBJECT public Q_SLOTS: void start(); // Waits for the keypress from the user and emits the corresponding signal. public: Q_SIGNALS: void togglePause2(); }; #endif UserInput.cpp #include "userinput.h" #include <iostream> #include <cstdio> // Implementation of getch #include <termios.h> #include <unistd.h> /* reads from keypress, doesn't echo */ int getch(void) { struct termios oldattr, newattr; int ch; tcgetattr( STDIN_FILENO, &oldattr ); newattr = oldattr; newattr.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newattr ); ch = getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldattr ); return ch; } void UserInput::start() { char c = 0; while (true) { c = getch(); if (c == ' ') { Q_EMIT togglePause2(); std::cout << "SPACE" << std::endl; } c = 0; } } Here is the CMakeLists.txt. I just placed it here also since I don't know maybe the CMake has also a factor here. CMakeLists.txt ############################################################################## # CMake ############################################################################## cmake_minimum_required(VERSION 2.4.6) ############################################################################## # Ros Initialisation ############################################################################## include($ENV{ROS_ROOT}/core/rosbuild/rosbuild.cmake) rosbuild_init() set(CMAKE_AUTOMOC ON) #set the default path for built executables to the "bin" directory set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin) #set the default path for built libraries to the "lib" directory set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib) # Set the build type. Options are: # Coverage : w/ debug symbols, w/o optimization, w/ code-coverage # Debug : w/ debug symbols, w/o optimization # Release : w/o debug symbols, w/ optimization # RelWithDebInfo : w/ debug symbols, w/ optimization # MinSizeRel : w/o debug symbols, w/ optimization, stripped binaries #set(ROS_BUILD_TYPE Debug) ############################################################################## # Qt Environment ############################################################################## # Could use this, but qt-ros would need an updated deb, instead we'll move to catkin # rosbuild_include(qt_build qt-ros) rosbuild_find_ros_package(qt_build) include(${qt_build_PACKAGE_PATH}/qt-ros.cmake) rosbuild_prepare_qt4(QtCore) # Add the appropriate components to the component list here ADD_DEFINITIONS(-DQT_NO_KEYWORDS) ############################################################################## # Sections ############################################################################## #file(GLOB QT_FORMS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ui/*.ui) #file(GLOB QT_RESOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} resources/*.qrc) file(GLOB_RECURSE QT_MOC RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} FOLLOW_SYMLINKS include/rgbdslam_client/*.hpp) #QT4_ADD_RESOURCES(QT_RESOURCES_CPP ${QT_RESOURCES}) #QT4_WRAP_UI(QT_FORMS_HPP ${QT_FORMS}) QT4_WRAP_CPP(QT_MOC_HPP ${QT_MOC}) ############################################################################## # Sources ############################################################################## file(GLOB_RECURSE QT_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} FOLLOW_SYMLINKS src/*.cpp) ############################################################################## # Binaries ############################################################################## rosbuild_add_executable(rgbdslam_client ${QT_SOURCES} ${QT_MOC_HPP}) #rosbuild_add_executable(rgbdslam_client ${QT_SOURCES} ${QT_RESOURCES_CPP} ${QT_FORMS_HPP} ${QT_MOC_HPP}) target_link_libraries(rgbdslam_client ${QT_LIBRARIES})

    Read the article

  • "input cannot be resolved" when added a try..catch

    - by Mark
    I originally tried to get my throw statement to work without a try catch and the userInput = input.nextInt(); line worked fine. But when I tried adding the try..catch it didn't like my input saying it cannot be resolved. I don't think my try..catch is correct yet but I am planning on tackling that after I can get this input to be recognized but I would appreciate any feedback on things you see with that as well. Thanks import java.util.Scanner; public class Program6 { public static void main(String[] args) { final int NUMBER_HIGH_LIMIT = 100; final int NUMBER_LOW_LIMIT = 10; int userInput; try { System.out.print("Enter a number between 10 and 100: "); userInput = input.nextInt();//Says input cannot be resolved Verify v = new Verify(NUMBER_HIGH_LIMIT, NUMBER_LOW_LIMIT); } catch(NumberHighException exception) { userInput = 0; } catch(NumberLowException exception) { userInput = 0; } } }

    Read the article

  • powershell: use variable with wildcard with get-aduser

    - by user179037
    powershell newbie here. I am building a simple bit of code to help me find user's by entering letters of user names. How do I get a wildcard to work w/ a variable? this works: $name=read-host -prompt "enter user's first or last initial" $userInput=get-aduser -f {givenname -like 'A*' } cmd /c echo "output: $userInput" this does not: $name=read-host -prompt "enter user's first or last initial" $userInput=get-aduser -f {givenname -like '$name*' } cmd /c echo "output: $userInput" The first bit of code delivers a list of users with "A" in their name. Any suggestions woudl be appreciated. thanks

    Read the article

  • StringIndexOutOfBoundsException: String index out of range 0

    - by Evan F
    I'm trying to write a program to take the first letter of the user input to generate a username. I'm trying to write it so that if the user leaves the input blank, then the letter that would otherwise be taken to generate the username defaults to the letter 'z'. Here is my full code: import java.util.Scanner; /** UsernameGenerator.java Generates a username based on the users inputs. @author: Evan Fravert */ public class UsernameGenerator { /** * Generates a username based on the users inputs. *@param args command line argument */ public static void main(String[] args) { // abcde String first; String middle; String last; String password1; String password2; int randomNum; randomNum = (int) (Math.random() * 1000) + 100; Scanner userInput = new Scanner(System.in); System.out.println("Please enter your first name:"); first = userInput.nextLine(); String firstLower = first.toLowerCase(); System.out.println("Please enter your middle name:"); middle = userInput.nextLine(); String middleLower = middle.toLowerCase(); System.out.println("Please enter your last name:"); last = userInput.nextLine(); int lastEnd = last.length()-1; String lastLower = last.toLowerCase(); System.out.println("Please enter your password:"); password1 = userInput.nextLine(); System.out.println("Please enter your password again:"); password2 = userInput.nextLine(); char firstLetter = firstLower.charAt(0); char middleLetter = middleLower.charAt(0); char lastLetter = lastLower.charAt(0); char lastLast = lastLower.charAt(lastEnd); if first.length() == 0) { firstLetter = 'z'; } else { firstLetter = firstLower.charAt(0); } System.out.println("Your username is " + firstLetter + "" + middleLetter + "" + lastLetter + "" + "" + lastLast + "" + randomNum); System.out.println("Your password is " + password1); System.out.println("Welcome " + first + " " + middle + " " + last + "!"); } }

    Read the article

  • Error when passing quotes to webservice by AJAX

    - by Radu
    I'm passing data using .ajax and here are my data and contentType attributes: data: '{ "UserInput" : "' + $('#txtInput').val() + '","Options" : { "Foo1":' + bar1 + ', "Foo2":' + Bar2 + ', "Flags":"' + flags + '", "Immunity":' + immunity + '}}', contentType: 'application/json; charset=utf-8', Server side my code looks like this: <WebMethod()> _ Public Shared Function ParseData(ByVal UserInput As String, ByVal Options As Options) As String The userinput is obvious but the Options structure is like the following: Public Structure Options Dim Foo1 As Boolean Dim Foo2 As Boolean Dim Flags As String Dim Immunity As Integer End Structure Everything works fine when $('#txtInput') contains no double-quotes but if they are present I get an error (for an input of asd"): {"Message":"Invalid object passed in, \u0027:\u0027 or \u0027}\u0027 expected. (22): { \"UserInput\" : \"asd\"\",\"Options\" : { \"Foo1\":false, \"Foo2\":false, \"Flags\":\"\", \"Immunity\":0}}","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"} Any idea how I can avoid this error? Also, when I pass the same input with quotes directly it works fine.

    Read the article

  • What's wrong in this simple android Program, I get 'Force Close'.

    - by andyfan
    What is wrong in this program, My eclipse IDE doesn't show any errors....when I execute this simple program the emulator shows force close....Anybody please clarify import android.app.Activity; import android.view.View.OnClickListener; import android.view.View; import android.os.Bundle; import android.widget.*; public class HelloWorld extends Activity implements OnClickListener { /** Called when the activity is first created. */ View Et1,Bt1,TxtDisp; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.name_getter); Bt1=(Button)findViewById(R.id.Btn1); Et1=(EditText)findViewById(R.id.UserInput); TxtDisp=(TextView)findViewById(R.id.TextDisp); Bt1.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub String userInput=((EditText) Et1).getText().toString(); ((TextView)TxtDisp).setText(userInput); } }

    Read the article

  • [java] How to get ALL the information from a socket

    - by raven
    Hello, I'll begin this question with the claim that I have read the java networking guide before asking you. I do not understand how to READ the socket and get all the info summed up into a string. the socket might contains more than 1 line [trying to make a chat]. Please do no refer me to any other site unless it clearly states "this exact line does this.." because I failed to understand what this code part does BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } Please, I just want to make a loop that will receive information from a socket, get all the content together into one string [I also want it to know where to add another line]. Thanks allot for anyone who helps, I have been trying to get an answer from tuts for hours and just failed to understand!

    Read the article

  • Having trouble returning a value from a method call when sending an array and the program is error out when run in reference to the sort

    - by programmerNOOB
    I am getting the following output when this program is run: Please enter the Social Security Number for taxpayer 0: 111111111 Please enter the gross income for taxpayer 0: 20000 Please enter the Social Security Number for taxpayer 1: 555555555 Please enter the gross income for taxpayer 1: 50000 Please enter the Social Security Number for taxpayer 2: 333333333 Please enter the gross income for taxpayer 2: 5464166 Please enter the Social Security Number for taxpayer 3: 222222222 Please enter the gross income for taxpayer 3: 645641 Please enter the Social Security Number for taxpayer 4: 444444444 Please enter the gross income for taxpayer 4: 29000 Taxpayer # 1 SSN: 111111111, Income is $20,000.00, Tax is $0.00 Taxpayer # 2 SSN: 555555555, Income is $50,000.00, Tax is $0.00 Taxpayer # 3 SSN: 333333333, Income is $5,464,166.00, Tax is $0.00 Taxpayer # 4 SSN: 222222222, Income is $645,641.00, Tax is $0.00 Taxpayer # 5 SSN: 444444444, Income is $29,000.00, Tax is $0.00 Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --- System.ArgumentException: At least one object must implement IComparable. at System.Collections.Comparer.Compare(Object a, Object b) at System.Collections.Generic.ObjectComparer`1.Compare(T x, T y) at System.Collections.Generic.ArraySortHelper`1.SwapIfGreaterWithItems(T[] keys, IComparer`1 comparer, Int32 a, Int32 b) at System.Collections.Generic.ArraySortHelper`1.QuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer) at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) --- End of inner exception stack trace --- at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer) at System.Array.Sort[T](T[] array) at Assignment5.Taxpayer.Main(String[] args) in Program.cs:line 150 Notice the 0s at the end of the line that should be the tax amount??? Here is the code: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace taxes { class Rates { // Create a class named rates that has the following data members: private int incLimit; private double lowTaxRate; private double highTaxRate; // use read-only accessor public int IncomeLimit { get { return incLimit; } } public double LowTaxRate { get { return lowTaxRate; } } public double HighTaxRate { get { return highTaxRate; } } //A class constructor that assigns default values public Rates() { int limit = 30000; double lowRate = .15; double highRate = .28; incLimit = limit; lowTaxRate = lowRate; highTaxRate = highRate; } //A class constructor that takes three parameters to assign input values for limit, low rate and high rate. public Rates(int limit, double lowRate, double highRate) { } // A CalculateTax method that takes an income parameter and computes the tax as follows: public int CalculateTax(int income) { int limit = 0; double lowRate = 0; double highRate = 0; int taxOwed = 0; // If income is less than the limit then return the tax as income times low rate. if (income < limit) taxOwed = Convert.ToInt32(income * lowRate); // If income is greater than or equal to the limit then return the tax as income times high rate. if (income >= limit) taxOwed = Convert.ToInt32(income * highRate); return taxOwed; } } //end class Rates // Create a class named Taxpayer that has the following data members: public class Taxpayer { //Use get and set accessors. string SSN { get; set; } int grossIncome { get; set; } // Use read-only accessor. public int taxOwed { get { return taxOwed; } } // The Taxpayer class should be set up so that its objects are comparable to each other based on tax owed. class taxpayer : IComparable { public int taxOwed { get; set; } public int income { get; set; } int IComparable.CompareTo(Object o) { int returnVal; taxpayer temp = (taxpayer)o; if (this.taxOwed > temp.taxOwed) returnVal = 1; else if (this.taxOwed < temp.taxOwed) returnVal = -1; else returnVal = 0; return returnVal; } // End IComparable.CompareTo } //end taxpayer IComparable class // **The tax should be calculated whenever the income is set. // The Taxpayer class should have a getRates class method that has the following. public static void GetRates() { // Local method data members for income limit, low rate and high rate. int incLimit = 0; double lowRate; double highRate; string userInput; // Prompt the user to enter a selection for either default settings or user input of settings. Console.Write("Would you like the default values (D) or would you like to enter the values (E)?: "); /* If the user selects default the default values you will instantiate a rates object using the default constructor * and set the Taxpayer class data member for tax equal to the value returned from calling the rates object CalculateTax method.*/ userInput = Convert.ToString(Console.ReadLine()); if (userInput == "D" || userInput == "d") { Rates rates = new Rates(); rates.CalculateTax(incLimit); } // end if /* If the user selects to enter the rates data then prompt the user to enter values for income limit, low rate and high rate, * instantiate a rates object using the three-argument constructor passing those three entries as the constructor arguments and * set the Taxpayer class data member for tax equal to the valuereturned from calling the rates object CalculateTax method. */ if (userInput == "E" || userInput == "e") { Console.Write("Please enter the income limit: "); incLimit = Convert.ToInt32(Console.ReadLine()); Console.Write("Please enter the low rate: "); lowRate = Convert.ToDouble(Console.ReadLine()); Console.Write("Please enter the high rate: "); highRate = Convert.ToDouble(Console.ReadLine()); Rates rates = new Rates(incLimit, lowRate, highRate); rates.CalculateTax(incLimit); } } static void Main(string[] args) { Taxpayer[] taxArray = new Taxpayer[5]; Rates taxRates = new Rates(); // Implement a for-loop that will prompt the user to enter the Social Security Number and gross income. for (int x = 0; x < taxArray.Length; ++x) { taxArray[x] = new Taxpayer(); Console.Write("Please enter the Social Security Number for taxpayer {0}: ", x + 1); taxArray[x].SSN = Console.ReadLine(); Console.Write("Please enter the gross income for taxpayer {0}: ", x + 1); taxArray[x].grossIncome = Convert.ToInt32(Console.ReadLine()); } Taxpayer.GetRates(); // Implement a for-loop that will display each object as formatted taxpayer SSN, income and calculated tax. for (int i = 0; i < taxArray.Length; ++i) { Console.WriteLine("Taxpayer # {0} SSN: {1}, Income is {2:c}, Tax is {3:c}", i + 1, taxArray[i].SSN, taxArray[i].grossIncome, taxRates.CalculateTax(taxArray[i].grossIncome)); } // end for // Implement a for-loop that will sort the five objects in order by the amount of tax owed Array.Sort(taxArray); Console.WriteLine("Sorted by tax owed"); for (int i = 0; i < taxArray.Length; ++i) { Console.WriteLine("Taxpayer # {0} SSN: {1}, Income is {2:c}, Tax is {3:c}", i + 1, taxArray[i].SSN, taxArray[i].grossIncome, taxRates.CalculateTax(taxArray[i].grossIncome)); } } //end main } // end Taxpayer class } //end Any clues as to why the dollar amount is coming up as 0 and why the sort is not working?

    Read the article

  • Batch File input validation - Make sure user entered an integer

    - by B2Ben
    I'm experimenting with a DOS batch file to perform a simple operation which requires the user to enter a non-negative integer. I'm using simple batch-file techniques to get user input: @ECHO OFF SET /P UserInput=Please Enter a Number: The user can enter any text they want here, so I would like to add some routine to make sure what the user entered was a valid number. That is... they entered at least one character, and every character is a number from 0 to 9. I'd like something I can feed the UserInput into. At the end of the routine would be like an if/then that would run different statements based on whether or not it was actually a valid number. I've experimented with loops and substrings and such, but my knowledge and understanding is still slim... so any help would be appreciated. I could build an executable, and I know there are nicer ways to do things than batch files, but at least for this task I'm trying to keep it simple by using a batch file.

    Read the article

  • Why can't my main class see the array in my calender class

    - by Rocky Celltick Eadie
    This is a homework problem. I'm already 5 days late and can't figure out what I'm doing wrong.. this is my 1st semester in Java and my first post on this site Here is the assignment.. Create a class called Calendar. The class should contain a variable called events that is a String array. The array should be created to hold 5 elements. Use a constant value to specify the array size. Do not hard code the array size. Initialize the array in the class constructor so that each element contains the string “ – No event planned – “. The class should contain a method called CreateEvent. This method should accept a String argument that contains a one-word user event and an integer argument that represents the day of the week. Monday should be represented by the number 1 and Friday should be represented by the number 5. Populate the events array with the event info passed into the method. Although the user will input one-word events, each event string should prepend the following string to each event: event_dayAppoinment: (where event_day is the day of the week) For example, if the user enters 1 and “doctor” , the first array element should read: Monday Appointment: doctor If the user enters 2 and “PTA” , the second array element should read: Tuesday Appointment: PTA Write a driver program (in a separate class) that creates and calls your Calendar class. Then use a loop to gather user input. Ask for the day (as an integer) and then ask for the event (as a one word string). Pass the integer and string to the Calendar object’s CreateEvent method. The user should be able enter 0 – 5 events. If the user enters -1, the loop should exit and your application should print out all the events in a tabular format. Your program should not allow the user to enter invalid values for the day of the week. Any input other than 1 – 5 or -1 for the day of the week would be considered invalid. Notes: When obtaining an integer from the user, you will need to use the nextInt() method on your Scanner object. When obtaining a string from a user, you will need to use the next() method on your Scanner object. Here is my code so far.. //DRIVER CLASS /** * * @author Rocky */ //imports scanner import java.util.Scanner; //begin class driver public class driver { /** * @paramargs the command line arguments */ //begin main method public static void main(String[] args) { //initiates scanner Scanner userInput = new Scanner (System.in); //declare variables int dayOfWeek; String userEvent; //creates object for calender class calendercalenderObject = new calender(); //user prompt System.out.println("Enter day of week for your event in the following format:"); System.out.println("Enter 1 for Monday"); System.out.println("Enter 2 for Tuesday"); System.out.println("Enter 3 for Wednsday"); System.out.println("Enter 4 for Thursday"); System.out.println("Enter 5 for Friday"); System.out.println("Enter -1 to quit"); //collect user input dayOfWeek = userInput.nextInt(); //user prompt System.out.println("Please type in the name of your event"); //collect user input userEvent = userInput.next(); //begin while loop while (dayOfWeek != -1) { //test for valid day of week if ((dayOfWeek>=1) && (dayOfWeek<=5)){ //calls createEvent method in calender class and passes 2 variables calenderObject.createEvent(userEvent,dayOfWeek); } else { //error message System.out.println("You have entered an invalid number"); //user prompts System.out.println("Press -1 to quit or enter another day"); System.out.println("Enter 1 for Monday"); System.out.println("Enter 2 for Tuesday"); System.out.println("Enter 3 for Wednsday"); System.out.println("Enter 4 for Thursday"); System.out.println("Enter 5 for Friday"); System.out.println("Enter -1 to quit"); //collect user input dayOfWeek = userInput.nextInt(); //end data validity test } //end while loop } //prints array to screen int i=0; for (i=0;i<events.length;i++){ System.out.println(events[i]); } //end main method } } /** * * @author Rocky */ //imports scanner import java.util.Scanner; //begin calender class public class calender { //creates events array String[] events = new String[5]; //begin calender class constructor public calender() { //Initializes array String[] events = {"-No event planned-","-No event planned-","-No event planned-","-No event planned-","-No event planned-"}; //end calender class constructor } //begin createEvent method public String[] createEvent (String userEvent, int dayOfWeek){ //Start switch test switch (dayOfWeek){ case 1: events[0] = ("Monday Appoinment:") + userEvent; break; case 2: events[1] = ("Tuesday Appoinment:") + userEvent; break; case 3: events[2] = ("WednsdayAppoinment:") + userEvent; break; case 4: events[3] = ("Thursday Appoinment:") + userEvent; break; case 5: events[4] = ("Friday Appoinment:") + userEvent; break; default: break; //End switch test } //returns events array return events; //end create event method } //end calender class }

    Read the article

  • DateTime.Parse with the "+" symbol

    - by Blah_Blah
    So I have a piece of code which parses and validates user input: DateTime myDateTime = DateTime.Parse(userInput,currentCulture); Current culture is being set (to en-ca or en-fr) and the user Input is always in ISO 8601 format "yyyy-MM-dd". If the user enters 1900-01-01 the date is created as expected. If the input is "1900-01+01" the date time created is 1899-12-31 6:00:00 PM No exception is thrown, the DateTime.Parse happily converts this to the wrong date. To make this work I am using DateTime.ParseExact(userInput,"yyyy-MM-dd",currentCulture). So my question is: whats up with the +01 or any + value? Am I missing something in ISO standard?

    Read the article

  • while loop / string input not working java

    - by Mikeecb
    I have looked online and all of the tutorials / questions have pointed me to this. I can't see why this isn't working. Any help would be much appreciated. Thanks import java.util.*; public class test { static Scanner userInput = new Scanner(System.in); public static void main(String[] args) { String textEntered = userInput.next(); if (textEntered == "hello") { System.out.println("Hello to you too!"); } } } I enter "hello" but nothing is printed. Also I have tried next() and nextLine();

    Read the article

  • Retrieve a static variable using its name dynamically using reflection

    - by user2538438
    How to retrieve a static variable using its name dynamically using Java reflection? If I have class containing some variables: public class myClass { string [][] cfg1= {{"01"},{"02"},{"81"},{"82"}}; string [][]cfg2= {{"c01"},{"c02"},{"c81"},{"c82"}}; string [][] cfg3= {{"d01"},{"d02"},{"d81"}{"d82"}}; int cfg11 = 5; int cfg22 = 10; int cfg33 = 15; } And in another class I want variable name is input from user: class test { Scanner in = new Scanner(System.in); String userInput = in.nextLine(); // get variable from class myClass that has the same name as userInput System.out.println("variable name " + // correct variable from class) } Using reflection. Any help please?

    Read the article

  • How can I modify my Shunting-Yard Algorithm so it accepts unary operators?

    - by KingNestor
    I've been working on implementing the Shunting-Yard Algorithm in JavaScript for class. Here is my work so far: var userInput = prompt("Enter in a mathematical expression:"); var postFix = InfixToPostfix(userInput); var result = EvaluateExpression(postFix); document.write("Infix: " + userInput + "<br/>"); document.write("Postfix (RPN): " + postFix + "<br/>"); document.write("Result: " + result + "<br/>"); function EvaluateExpression(expression) { var tokens = expression.split(/([0-9]+|[*+-\/()])/); var evalStack = []; while (tokens.length != 0) { var currentToken = tokens.shift(); if (isNumber(currentToken)) { evalStack.push(currentToken); } else if (isOperator(currentToken)) { var operand1 = evalStack.pop(); var operand2 = evalStack.pop(); var result = PerformOperation(parseInt(operand1), parseInt(operand2), currentToken); evalStack.push(result); } } return evalStack.pop(); } function PerformOperation(operand1, operand2, operator) { switch(operator) { case '+': return operand1 + operand2; case '-': return operand1 - operand2; case '*': return operand1 * operand2; case '/': return operand1 / operand2; default: return; } } function InfixToPostfix(expression) { var tokens = expression.split(/([0-9]+|[*+-\/()])/); var outputQueue = []; var operatorStack = []; while (tokens.length != 0) { var currentToken = tokens.shift(); if (isNumber(currentToken)) { outputQueue.push(currentToken); } else if (isOperator(currentToken)) { while ((getAssociativity(currentToken) == 'left' && getPrecedence(currentToken) <= getPrecedence(operatorStack[operatorStack.length-1])) || (getAssociativity(currentToken) == 'right' && getPrecedence(currentToken) < getPrecedence(operatorStack[operatorStack.length-1]))) { outputQueue.push(operatorStack.pop()) } operatorStack.push(currentToken); } else if (currentToken == '(') { operatorStack.push(currentToken); } else if (currentToken == ')') { while (operatorStack[operatorStack.length-1] != '(') { if (operatorStack.length == 0) throw("Parenthesis balancing error! Shame on you!"); outputQueue.push(operatorStack.pop()); } operatorStack.pop(); } } while (operatorStack.length != 0) { if (!operatorStack[operatorStack.length-1].match(/([()])/)) outputQueue.push(operatorStack.pop()); else throw("Parenthesis balancing error! Shame on you!"); } return outputQueue.join(" "); } function isOperator(token) { if (!token.match(/([*+-\/])/)) return false; else return true; } function isNumber(token) { if (!token.match(/([0-9]+)/)) return false; else return true; } function getPrecedence(token) { switch (token) { case '^': return 9; case '*': case '/': case '%': return 8; case '+': case '-': return 6; default: return -1; } } function getAssociativity(token) { switch(token) { case '+': case '-': case '*': case '/': return 'left'; case '^': return 'right'; } } It works fine so far. If I give it: ((5+3) * 8) It will output: Infix: ((5+3) * 8) Postfix (RPN): 5 3 + 8 * Result: 64 However, I'm struggling with implementing the unary operators so I could do something like: ((-5+3) * 8) What would be the best way to implement unary operators (negation, etc)? Also, does anyone have any suggestions for handling floating point numbers as well? One last thing, if anyone sees me doing anything weird in JavaScript let me know. This is my first JavaScript program and I'm not used to it yet.

    Read the article

  • Java: How to check the random letters from a-z, out of 10 letters minimum 2 letter should be a vowel

    - by kalandar
    I am writing a program to validate the following scenarios: Scenario 1: I am using the Random class from java.util. The random class will generate 10 letters from a-z and within 10 letter, minimum 2 letters must be a vowels. Scenario 2: When the player 1 and player 2 form a word from A-Z, he will score some points. There will be a score for each letter. I have already assigned the values for A-Z. At the end of the game, the system should display a scores for player 1 and player 2. How do i do it? Please help. I will post my code here. Thanks a lot. =========================================== import java.util.Random; import java.util.Scanner; public class FindYourWords { public static void main(String[] args) { Random rand = new Random(); Scanner userInput = new Scanner(System.in); //==================Player object=============================================== Player playerOne = new Player(); playerOne.wordScore = 0; playerOne.choice = "blah"; playerOne.turn = true; Player playerTwo = new Player(); playerTwo.wordScore = 0; playerTwo.choice = "blah"; playerTwo.turn = false; //================== Alphabet ================================================== String[] newChars = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; //values of the 26 alphabets to be used int [] letterScore = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10}; // to assign score to the player1 and player 2 String[] vowel = { "a", "e", "i", "o", "u" }; // values for vowels int vow=0; System.out.println("FINDYOURWORDS\n"); int[] arrayRandom = new int[10]; //int array for word limiter String[] randomLetter = new String[10]; //storing the letters in newChars into this array //=============================================================================== boolean cont = true; while (cont) { if (playerOne.turn) { System.out.print("Letters of Player 1: "); } else if (!playerOne.turn) { System.out.print("Letters of Player 2: "); } for (int i = 0; i < arrayRandom.length; i++) { //running through the array limiter int r = rand.nextInt(newChars.length); //assigning random nums to the array of letters randomLetter[i] = newChars[r]; System.out.print(randomLetter[i]+ " "); } //input section for player System.out.println(""); System.out.println("Enter your word (or '@' to pass or '!' to quit): "); if (playerOne.turn) { playerOne.choice = userInput.next(); System.out.println(playerOne.turn); playerOne.turn = false; } else if (!playerOne.turn){ playerTwo.choice = userInput.next(); System.out.println(playerOne.turn); playerOne.turn = true; } //System.out.println(choice); String[] wordList = FileUtil.readDictFromFile("words.txt"); //Still dunno what this is for if (playerOne.choice.equals("@")) { playerOne.turn = false; } else if (playerTwo.choice.equals("@")) { playerOne.turn = true; } else if (playerOne.choice.equals("!")) { cont = false; } for (int i = 0; i < wordList.length; i++) { //System.out.println(wordList[i]); if (playerOne.choice.equalsIgnoreCase(wordList[i]) || playerTwo.choice.equalsIgnoreCase(wordList[i])){ } } } }}

    Read the article

  • Am I going the right way to make login system secure with this simple password salting?

    - by LoVeSmItH
    I have two fields in login table password salt And I have this little function to generate salt function random_salt($h_algo="sha512"){ $salt1=uniqid(rand(),TRUE); $salt2=date("YmdHis").microtime(true); if(function_exists('dechex')){ $salt2=dechex($salt2); } $salt3=$_SERVER['REMOTE_ADDR']; $salt=$salt1.$salt2.$salt3; if(function_exists('hash')){ $hash=(in_array($h_algo,hash_algos()))?$h_algo:"sha512"; $randomsalt=hash($hash,md5($salt)); //returns 128 character long hash if sha512 algorithm is used. }else{ $randomsalt=sha1(md5($salt)); //returns 40 characters long hash } return $randomsalt; } Now to create user password I have following $userinput=$_POST["password"] //don't bother about escaping, i have done it in my real project. $static_salt="THIS-3434-95456-IS-RANDOM-27883478274-SALT"; //some static hard to predict secret salt. $salt=random_salt(); //generates 128 character long hash. $password =sha1($salt.$userinput.$static_salt); $salt is saved in salt field of database and $password is saved in password field. My problem, In function random_salt(), I m having this FEELING that I'm just making things complicated while this may not generate secure salt as it should. Can someone throw me a light whether I m going in a right direction? P.S. I do have an idea about crypt functions and like such. Just want to know is my code okay? Thanks.

    Read the article

  • UISwitch within UIScrollview nearly impossible to use....

    - by samsam
    Hi there. I'm using a UISwitch-Component at the bottom of a view that sits within a UIScrollView. Now the problem that appeared, is that the switch is nearly impossible to swipe because the UIScrollView seems to dominate the userinput. Switching works very well by tapping the switch, but from my point of view, most users "switch" the UISwitch instead of tapping. Did anyone of you face the same / or similar problems and managed to come up with a solution? thx in advance sam

    Read the article

  • Display both forms together

    - by Ani
    I have 2 forms Form1 and Form2, when program executes I want both forms to display but Form2 with ShowDialog(); i.e user has to respond to Form2 before using Form1. How can I achieve this? Form2 will take userinput and will display on Form1, so do I have to hide Form2 after user responds to Form2 or just kill it.

    Read the article

  • Possible loss of precision; extracting char from string

    - by Troy
    I am getting a string from the user and then doing some checking to make sure it is valid, here is the code I have been using; char digit= userInput.charAt(0) - '0'; This had been working fine until I did some work on another method, I went to compile and have been receiving a 'possible loss of precision' error since then. What am I doing wrong?

    Read the article

1 2  | Next Page >