Scanner Object Never Waits For User To Input Anything

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


ADVERTISEMENT

Polynomials Into Array Using User Input With Scanner

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

Reading Input With Scanner And Checking If User Entered Empty String?

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

Create New Scanner With The Specified String Object

Jul 4, 2014

//Scanner Test
String stream2 = "ab34ef
56";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(stream1);
// find a string "World"

[Code] ....

Matched expression found by findInLine: 34

ef56

is new line? right?

The java.util.Scanner.nextLine() method advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end.

then 56 is in new line and it must return ef.What is the problem?

View Replies View Related

Create Account Object And Allow User To Input Account ID

Nov 10, 2014

How to write a driver program, this my code I have :

import java.util.Date;
public class myAccount {
public static void main(String[] args) {
//create an instance object of class Stock
Account myAccount = new Account(012233445566, 20000.00, 0.045);

[Code] ......

View Replies View Related

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 View Related

Console Input Of Strings Using Scanner

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

Parsing Input From A File Using Scanner

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

Use Scanner To Get Input And Distinguish Between Int And Text?

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

Checking To See If Input From Scanner Is Integer

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

Creating A Scanner And Putting Input Into Arrays

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

Failing To Read Input With Scanner NextLine

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

Scanner That Scans Console For Input To Fetch String Word

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

Get Object Strings To Print In List So That User Can Select That Object To Manipulate Its Attributes

Oct 7, 2014

I am new to Java and have read books, the Java docs, and searched the Internet for my problem to no avail. I have an Array of objects that contains strings. How can I get the object's strings to print in a list so that the user can select that object to manipulate its attributes? For example, the user can select "Guitar 1" from a list and manipulate its attributes like tuning it, playing it, etc. I have a class called Instruments and created 10 guitar objects.Here is the code:

Instrument [] guitar = new Instrument[10];
for (int i = 0; i < 10; i++) {
guitar[0] = new Instrument("Guitar 1");
guitar[1] = new Instrument("Guitar 2");
guitar[2] = new Instrument("Guitar 3");
guitar[3] = new Instrument("Guitar 4");
guitar[4] = new Instrument("Guitar 5");
guitar[5] = new Instrument("Guitar 6");

[code]...

View Replies View Related

Java Program That Will Ask A User To Input Grades Until User Inputs Sentinel Value

Apr 9, 2014

Write a java program that will ask a user to input grades until the user inputs the sentinel value -1. The program should test each input to determine whether 0<=grade<=100. If the grade entered is within this range, the program should print "Grade accepted;" if not, the program should print "Invalid input".

View Replies View Related

Program That Takes User Odd Number And Print Prime Numbers Lower Than User Input

Nov 4, 2014

I have been struggling with this program for weeks. This program is supposed to take a user's inputted odd number and then print out all prime numbers lower than that number.

public class PrimeNumber
{
Scanner scan = new Scanner(System.in);
int userNum;
String neg;

public void getUserNum()

[code]...

View Replies View Related

Code Not Running Scanner NextLine After Using Scanner NextInt?

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

Where To Input Segment To Get User Input Dialog

Apr 9, 2015

Where do I input this segment?

Scanner user_input = new Scanner( System.in );// This line goes at the top with the other global variables

public void getUserInput(){
System.out.print("Enter litres: ");
litres = user_input.nextDouble( );
System.out.print("Enter mileage: ");
mileage = user_input.nextDouble( );
System.out.print("Enter speed: ");
speed = user_input.nextDouble( );

[Code] ....

This is my client file.

class Client{
public static void main(String []args){
Bike R1=new Bike(5.0, 60.0,30.0);//create bike object with params
Bike R2=new Bike();//without params
System.out.println(R1.increaseSpeed());//calling methods
System.out.println(R1.maxDistance());
System.out.println(R2.increaseSpeed());
System.out.println(R2.maxDistance());
}
}

View Replies View Related

How To Get User Input

Nov 13, 2014

I have been coding in my class at school (Grade 11 Computer science) and i just downloaded the program on my computer at home, unfortunately i cannot access my computer notes at home and i also dont remember certian specifics of coding, so my question is how would i get user input to create a program. The comments are the parts i dont remember. (I am trying to slowly build my memory with this stuff)

Here is my code so far:

import java.util;
[highlight=java]
public class hello_world {
public static void main(String[] args) {
string name;
//WHAT DO I PUT HERE????

[code]....

View Replies View Related

Asking User For Input Twice?

Apr 19, 2014

I'm working on creating a dice game and getting the users input is giving me a really hard time. I have the main game working but this part I'm stuck on. The problem is that it's not giving me the chance to enter the second input when I ask for the game.

//Create Scanner object
Scanner keys = new Scanner(System.in);
//Get chips

[Code]....

*****This is what I get when I run it

run:

How much money would you like to change? 50

You now have $50 in chips.

What game do you want to play? You did not pick dice.

View Replies View Related

User Event - Global Object Declaration

Mar 10, 2015

I have an application that uses an object that is declared globally for the class. Within a method that is triggered by a user event, it creates a new object and assigns it to this global object declaration. My question is, when the object is overwritten multiple times by the user selecting the button that calls this method, will the older instances be garbage collected or is there still a reference to them? Is there any downfall to this logic and if so what would be a solution.

View Replies View Related

Can Control User Input

Oct 11, 2014

Is there a way you can control user input?

For example, is it possible to only allow the user to enter digits?

View Replies View Related

Formatting User Input

Feb 4, 2014

I have been given a piece of work to do for College that requires me to format user input. For example: This is an example of text that will have straight left and right margins after formatting

will transform into:

This..is..an.example
of..text..that..will
have..straight..left
and...right..margins
after.....formatting

The user inputs the width, in the case above being 20. Each line has to therefore be 20 characters long. All spaces are to be replaced with full stops.

This.is.an.example.o
f.text.that.will.hav
e.straight.left.and.
right.margins.after.
formatting..........
public class Main {
public static void main ( String args[])

[code]....

View Replies View Related

ArrayList - Get User Input And Sum Together

Jul 2, 2014

Goal is to get user input and sum together. I've tried it different ways. This is the one with the least amount of problems.

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.lang.Integer.parseInt

ArrayList<Integer> leftCU = new ArrayList<>(); {
System.out.println
("Please enter one at a time the number of CU's for each class that is left to complete. Enter Q when done.");
leftCU.add(in.nextInt());

[Code] .....

View Replies View Related

Get User Input For A Char Value?

Jan 9, 2015

I am trying to get user input for a char value and am having some difficulty getting input for a char value.

Java Code:

//imports packages
import java.io.*;
import java.text.DecimalFormat;
class ModuleCulminatingTask {
public static void main (String args []) {
//declares variables
float var3, var4;
long var5 = (int)(Math.random()*10);

[code]....

View Replies View Related

Simple Input Value From User

Apr 10, 2014

I'm not sure what is wrong with my code:

import java.util.Scanner;
public class Main {
int age = 0;
System.out.println("Enter your age: ");
// Read in values
age = in.nextInt();
}

The in is underlined, telling me "cannot find symbol"

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved