Scanner Taking Input Twice
Oct 29, 2014
I have a small bug in my program. The user is asked what person(s) information they want to access but lets say they want captain they must enter "captain" twice. I think it will make more sense to you with the code. I have searched all over to see what is causing the bug but still have found no resolution. I even tried making two different scanners but that didn't work either.
I know the while loop (line 16) I am using is causing the bug because it works fine without that but then I cannot validate the input.
package myproject;
import java.util.Scanner;
public class Enterprise {
public static void main (String[]args){
String userInput;
[Code]......
View Replies
ADVERTISEMENT
Feb 1, 2015
There is a problem that I am facing while using the Scanner class for taking inputs from the user. Suppose if I need to take an integer and a String input from the user, and I take the integer input first then the place where the user has to input the String skips and the variable shows a "" nothing on printing it. Suppose in this code snippet
import java.util.Scanner;
public class Test
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
System.out.println("Enter a word");
String str = sc.nextLine();
System.out.println("Enter integer is " + n);
System.out.println("Entered statement is " + str);
}
}
The output is
Enter a number
13
Enter a word
Enter integer is 13
Entered statement is
I need to know why this happens and how should I avoid it. I've seen that taking the String input first solves the issue but while taking the input in a loop to populate a database the program only lets the user enter the first statement and the following statements are skipped.
View Replies
View Related
Oct 25, 2014
What I have so far are two classes, Movie class and MovieTestDrive class. I've to get the title, genre and ratings for movies and then put them into an array and call the playIt() method.
I would like to create a for loop to iterate three times for three instances of the Movie class but I don't know how to do it.
When I try to run the code, it won't work and I don't know if this is because I have Scanner running incorrectly whilst encapsulating my data. What I have so far:
class Movie {
// Create instance variables for the Movie class.
private String title;
private String genre;
private int rating;
// Use getters and setters to set and display the variables.
[Code] .....
View Replies
View Related
Feb 3, 2014
I am stumped on a coding project I am working on. I am making an inventory program with predefined values for the items. I am not sure how to iterate through my arrayList, and allow the user to input the "number sold."
I have made an arrayList and populated it using the add(), but I am not sure if it is working correctly. This is my inventoryItem class :
package inventory;
import java.text.DecimalFormat;
public class inventoryItm {
String itemName;
double unitPrice;
int numberSold;
[Code] .....
View Replies
View Related
Feb 7, 2014
I am trying to test the instanceof keyword. To do this, I've made a method with a simple logical test like so:
Java Code:
Vehicle vehicle1 = new Vehicle();
public void Type(){
if (vehicle1 instanceof Vehicle) {
System.out.println("Type = Vehicle");
}
else if (vehicle1 instanceof Car) {
System.out.println("Type = Car");
}
else if (vehicle1 instanceof Truck) {
System.out.println("Type = Truck");
}
}
} mh_sh_highlight_all('java');
I wanted to try implementing it into the class definitions for Vehicle, then extend that to Car and Truck, but I'm not sure how to use this test in a general case.
The only way this method works is if I set the test to specifically accept a specific object as a parameter.
I want to test multiple objects, but I'm not really sure how else to do this without simply copy-pasting the logical test multiple times and changing the respective objects that are used as parameters.
View Replies
View Related
Jun 7, 2014
I'm developing a Swing application for the first time. To test my application, I have currently hardcoded some text labels and fields in a JPanel, so that a user can enter input details for a maximum of 3 segments. But this limits the maximum number of segments to 3. However, the requirement is that when the user enters the number of segments (could be greater than 3 as well), corresponding number of input sets need to be taken.
Screenshot attached, with values entered.
Basically I want to know how I should go about taking the inputs from the user.
View Replies
View Related
Jun 6, 2014
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input == "next") {
System.out.print("good Job!");
}
else {
System.out.println("Why ?");
}
//If I type in next it prints out "Why ?" instead of "Good Job!" - Why though ?
View Replies
View Related
May 9, 2015
I am having a great deal of frustration trying to use the scanner to get user input from the eclipse console. Here is what I am trying to do.
Print a menu for the user with options, take that (1) char input and run it into a switch statement for processing. I have that done and it is working fine.
If the user chooses to enter strings for storage, They are instructed to enter their string and press enter to complete that string entry. Then enter the next string and press enter, etc.
So I have a While loop for this. Get the scanner input, store it in the LinkedList, get the next scanner input, etc. I get the scanner string and store it in a Linked list. That works fine. The user is instructed to simply enter a blank string to end the entry procedure, like just press Enter on the new line without typing a new string.
The problem is the scanner doesn't seem to return anything for me to Test to close this procedure. How do I TRAP the fact that the user just pressed enter so I can end my procedure? I have tried next() and nextLine() and reset(), etc. And I am getting knowhere.
View Replies
View Related
Mar 26, 2014
I'm having some kind of weird problem reading input from a file. It says that my scanner object I'm using to hold an item of information isn't initialized, when I do try to initialize it, it says error variable already initialized. I'm using the scanner to read input from a file whose contents are this
10
150.4
88.4
-3.14
499.4
799.4
1299.8
0
1900.2
901.7
4444.4
This is my program
import java.util.*;
import java.io.*;
public class QudratullahMommandi_3_07 {
Toolkit_General toolKit = new Toolkit_General();
public static void main (String[]args)throws IOException
[Code] .....
This is the error message
QudratullahMommandi_3_07.java:34: error: variable holder2 might not have been initialized
String holder2 = holder2.trim();
^
1 error
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
View Replies
View Related
Sep 13, 2014
Is there any way to use scanner to get input and distinguish between int and text? I'm trying to make a scanner method I can call whenever I need user input no matter if I need int or text. Using two methods (one for int, other for text) at the moment.
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Person person1 = new Person();
System.out.println("What is your name?");
[Code] .....
View Replies
View Related
Jun 12, 2014
So I clipped this out of my Jeopardy game code and made it into its own project for testing. using this code I want to check to see if the input for wage is an integer?
import java.util.Scanner;
public class test {
/**
* @param args
*/
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
Obviously right now if you enter "aflwkj" or some such for the wager, the program terminates. How to make a loop that will keep asking the user for a value for wage until the input is an integer?
View Replies
View Related
Apr 15, 2014
I'm trying to read user input from the terminal and separate the input into separate arrays depending on if the user input is an integer, scanner, or a string. The terminal should keep asking the user for input until the user types "quit".
import java.util.*;
public class arrayScanner {
public static void main(String[] args) {
ArrayList<Integer> intList = new ArrayList<Integer>();
ArrayList<Double> doubleList = new ArrayList<Double>();
ArrayList<String> otherList = new ArrayList<String>();
[code].....
View Replies
View Related
Feb 19, 2014
Assignment: Your task is to implement a similar scheme to store polynomials of any number of terms, such that the number of terms and the components (coefficient, variable and exponent) of every term are entered from the keyboard. To implement the interactive input we will using the Java class Scanner, defined in the java.utils standard package. The Scanner class can be used in Java to read data types from a file.
Since the input console (keyboard) is treated as the file called System.in, we can create a Scanner for that input stream as new Scanner (System.in), as shown below. Once you define a Scanner object, using its method next() you can read Strings from the file/keyboard. The incomplete program below is your assignment. You are supposed to complete without changing the existing code. Your output should be the terms of the polynomial entered by the user, separated by + signs. Additional instructions in the code below, that you will change to achieve the requested functionality.
import java.util.Scanner;
public class Polynomials {
public static void storeTerm (int coeff, String var, int exp, String poly[][], int
where){
//ENTER THE COEFFICIENT, VARIABLE AND EXPONENT INTO THE
//ARRAY POLY THAT REPRESENTS THE POLYNOMIAL, AT POSITION "where"
//THAT RANGES BETWEEN INDEX 0 AND POLY.LENGTH-1
[Code] ....
Anyways, I'm not looking for straight answers. I just want to know which section I should start on first because I was advised to tackle programs one problem at a time.
View Replies
View Related
Jan 29, 2014
I Just made a simple code, but in any case it's not taking the input I'm trying to enter for the city.
View Replies
View Related
Jun 13, 2014
The method below is called within a large loop in another method. The code has been boiled down to easily show the problem I'm having. I found that the method worked fine (prompts user for input, gets input, returns input) until I added a statement at the end of the method that closes the Scanner object. When the kb.close() statement is present, the method works the first time through, but subsequent calls to this method only display the prompt and the Scanner object never waits for the user to input anything thereafter.
public int scanIt()
{
int i;
Scanner kb = new Scanner(System.out);
System.out.print("==> "); // prompt for input
if(kb.hasNextInt())
{
i = kb.nextInt();
System.out.println("User entered " + i);
}
kb.close();
}
View Replies
View Related
Jul 28, 2014
I'm having an issue, I have a scanner (Scan.nextLine();) that scans the console for input to fetch the string "word". Then I want to fetch a character using Scan.findInLine(word).charAt(number);. The problem is that the console requires me to write 2 lines in order for the program to move on. I only want the program to scan for a word, and then move on with what it has instead of requiring 2 inputs.
View Replies
View Related
Apr 7, 2015
The project is a program that allows the user to enter students and enter grades for each student. One of the requirements is that if there is already a grade stored for the student that it will display the previous grade. IF the user then enters a new grade the new grade will be stored. IF the user simply presses enter (enters an empty string) nothing is done. I have everything working except for the requirement of doing nothing if the user enters an empty string. If I just press enter at this point I get a NumberFormatException.
The below code is a method "setTestGrades" from the student class. This method iterates through each student object stored in an array list and then checks if there is a previous grade (Requirement# unset grades have to default to -1) before allowing the user to set a new grade.
public void setTestGrades(int testNumber) { //Sets the grade for the specified test number for each student in the arraylist.
testNumber -= 1;
Scanner input = new Scanner(System.in);
for (int i = 0; i < studentList.size(); i++) {
System.out.println("Please enter the grade for Test #" + (testNumber + 1) + " For Student " + studentList.get(i).getStudentName());
[code]....
View Replies
View Related
Feb 14, 2015
package jdbc;
import java.sql.*;
import javax.sql.*;
import java.util.*;
public class Jdbc {
public static void main(String[] args) {
[code]....
View Replies
View Related
Apr 11, 2014
This piece of code is giving me the most trouble as I cannot convert the self defined class (Fraction) into int in order to store the elements in the variable (max). What is the best way to go about grabbing the next element and storing it in max and compare it to the previous to get the highest and lowest value?
System.out.println("Enter numerator / denominator");
frak[0] = new Fraction(keyb.nextInt(), keyb.nextInt());
frak[0] = max;
for (int i = 1; i < frak.length; i++){ // starting from array element 1
System.out.println("Enter numerator / denominator");
frak[i] = new Fraction(keyb.nextInt(), keyb.nextInt());
if (max > frak[i]){
}
View Replies
View Related
Jul 9, 2014
I have written a java app that's been working for a few years now and the client is very satisfied. However, a certain user has been experiencing a problem where the app runs fine BUT whenever it interacts with the OS (Win7 in this case), it takes ~10 mins to respond. Actions include, for example, exporting the currently displayed JTable to a CSV file or making an OS call to open up MS Word, etc.
I copied the users version of the app onto my platform (win 8.1) and tested it on winXP too with no problems which points towards an issue on the users particular PC. Furthermore, it used to run on the users PC fine until something (??) happened.
I've tried the following so far:-
1. looked at System restore to check anything new installed - nothing obvious
2. disabling anti virus - problem still occurs
3. monitoring JVM process time using Task Manager - little CPU time seems to be utilised (=> no loop etc)
I'll try :-
1. using JvisualVM - although I don't think this will show me what's going on with the OS
2. excluding the JVM and the app from all anti malware
Any app or something that shows interaction with the OS so I can trace what might be intercepting the call from my app to the OS?
View Replies
View Related
Oct 29, 2014
I am working on a web-application where i have a functionality which generates reports based on the data from DB. for small amount of data its working nice if the data is huge its taking more time. to avoid this problem i developed a standalone batch where i generated the jar file for the sources in web-application and made a call to the appropriate methods.
But my problem is if web-application takes 10 secs to generate the report but in the case of standalone its taking nearly 3-5 mins to generate the same report. i didn't do much of the changes in code just using the same code as web-application
I am using tomcat 6 application server to run the web-application for standalone using batch commands.....
View Replies
View Related
Apr 26, 2015
This is the code that I have so far, It will only print out the digit if it is entered first..How to I get it to print out all digits? and I am getting an error that the c is not initialized
import java.util.*;
//Write a program that prompts the user for some text. Output only the digits in that text. Hint: Use a loop and the Character.isDigit method.
public class Q1
{
[Code].....
View Replies
View Related
Jan 20, 2015
I've looking for information on taking a range of data from a google sheet such as the one below.
JavaGroupCat.png
The function that i'm trying to accomplish is allowing a user to run the program and input their 5-digit Unique - ID. After inputting their 5-Digit ID the program will take that input, and check whether or not that ID is present on the spreadsheet.
Ex: (Using the numbers from above) I type in : "89504" then (I would want the program to spit out if the ID is on the sheet).
(89504 appears on the sheet) So i would want it to print out something like "ID is found on list "Cat".
Associated named include: "Phil Roberts".
I tried, with my limited knowledge, to create what I have described above.
import java.io.*;
import java.util.*;
public class SwitchesTwo
{
public static void main(String args[]) {
System.out.println("Welcome to the ID # Checker");
System.out.println("Enter the ID of the person you are trying to verify");
[Code].....
The issue I have with the mock-up above is the fact that I have to manually add in every individual name and ID. I would much rather write code that would allow it to update as I update the spreadsheet. Therefore, no need for 800+ cases. (theres around 800 ID numbers for this project)
In a perfect world, the code would be something like "Take info from cells C5 - C2000 and store as string array" (I think array would work.) while also doing the same with B5 - B2000.
View Replies
View Related
Sep 5, 2014
I am not very comfortable with Strings in Java. The problem I am facing is, taking a string that contains a sentence and reversing the words. Example would be, "Hi I am Bob" and changing it to "Bob am I Hi". Then returning the String.
My initial thoughts were to change the string into a character array and then manually doing the work with loops and tedious comparison statements. I quickly realized that there must be a better way but I am not very familiar with strings in Java to know what a more sufficient way would be.
View Replies
View Related
Apr 27, 2014
I've built up an unreasonably large and unreasonably complicated JPanel. Unfortunately, when I use setViewportView to add it to a JScrollPane, a get an extended UI freeze—that operation takes several seconds. I'm trying to figure out what's taking so long. I've tried some fairly extreme things, like overriding the paintComponent, PaintComponents, paintChildren, paint, repaint, validate, revalidate, and validateTree methods in the panel with no-ops to try to figure out what's taking so long, but to no avail. I've tried validating the JPanel before adding it, but that has no effect. If I override the addImpl method of the scroll pane, that makes things quick, but it doesn't really narrow things down much.
View Replies
View Related
Apr 24, 2014
At the moment I am studying it and the problem is Taking a range of names in an array and outputting them alphabetically, But for some reason I get an outOfBoundsException. And its starting to get to me. How to put the code in
import java.util.Scanner;
import java.util.Arrays;
public class lab241 {
public static void main(String[] args) {
Scanner kb= new Scanner(System.in);
String[ ] names = new String[4];
names[0]= ("Horatio");
names[1]= ("Anatoly");
names[3]= ("Evelyn");
names[4]= ("Anna");
Arrays.sort(names);
for(String N: names){
System.out.println(N);
View Replies
View Related