Scanner Array Initializing

Oct 12, 2014

Scanner sc = new Scanner(System.in);
Question question = new Question();
Quiz quiz = new Quiz();
System.out.print("Enter the prompt: ");
question.prompt = sc.nextLine();

[Code] .....

Here is the example run that I am trying to achieve:

* 1. Enter the prompt: What is the capital of the USA?
* 2. Enter a possible answer: New York City, NY
* 2. Is New York City, NY the correct answer (y/n)? n
* 3. Enter a possible answer: Pittsburgh, PA
* 3. Is Pittsburgh, PA the correct answer (y/n)? n
* 4. Enter a possible answer: Washington, DC
* 4. Is Washington, DC the correct answer (y/n)? y
* 5. Enter a possible answer: Chicago, IL
* 5. Is Chicago, IL the correct answer (y/n)? n

The problem is that my for loop runs through correctly the first time, but doesn't seem to react to me initializing my choices array after that. It ends up looking like this:

Enter the prompt: What is the capitol of the USA?
Enter a possible answer: New York City, NY
Is New York City, NY the correct answer (y/n)?n
Enter a possible answer: Is the correct answer (y/n)?

But I cannot understand why it's doing that.

View Replies


ADVERTISEMENT

C Struct - Initializing 3D Array?

Oct 23, 2014

I have a C struct as follows:

struct myHAI
{
int id;
char celcius[5];
char fahrenheit[5];
 
[Code] .....

I think the Java code is just a little to kludgey. I have to add 256 records to the 3D array which means I have to call the method 256 times. I'd really like to initialize the class all at once similar to the C struct. But I don't know if that is possible. Thus, any less kludgey way of initializing a 3D array?

View Replies View Related

Initializing Array - Equal Sign?

Nov 15, 2014

i know that int [][] x = new int[2][2] will generate a 2x2 array but I'm looking at a certification mock question and I see double [][] da = new double [3][]. What is the empty [] on the right hand side of the equal sign trying to tell me? Is there some default value?

View Replies View Related

Pass User Input - Initializing Array In Method

Feb 7, 2015

I need to pass user input from the main method, which is then validated using another method that is returned as a valid score, and then I pass the valid input to another method that stores the data in an array. The array is initialized within the method. I tried to use an if-else statement to initialize the array, because I originally did this at the beginning of the method. I soon learned that I was creating a new array everything I accessed the method. Needless to say, this isn't working either.

public static void main(String[] args) {
int judges = 7;
float[] validScores = new float[judges];
for (int i = 0; i < judges; i++) {
float score = -1;

[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

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

Populate Array From Text File Or Scanner

May 26, 2014

I have a simple txt file, each line simply containing 1 word.I would like each work to represent an index of the array..im having some difficulty populating an array from either a txt file or a scanner.i seem to be able to fill the scanner so to speak with the contents of the text file but not the array. I don't know how to syntax it

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Arrays;
public class ReadFile
public static void main(String[] args) {

[code]....

View Replies View Related

JSP :: Initializing Captcha From Session

Feb 26, 2015

I am new to JSP and I'm having a problem with captcha containing a value in the field when toggling from the first page to another and clicking submit on the second page before entering data to validate the fields and the code just falls through and returns the error "Please enter the correct code". The values returned are (captcha)96043 (code)null, captcha is not null because it is retrieved from session which is the last value captured from the page I'm assuming.

I've used request.getSession().removeAttribute( "captcha" ); before building the page to clear out the values, resetting captcha to null etc.; nothing is working.

Here's the code:

boolean isPostBack =false;
String captcha = (String) session.getAttribute("captcha");
String code = (String) request.getParameter("j_captcha_response");

[code]....

View Replies View Related

Initializing Variable Within Program

Mar 3, 2014

My objective is to write a program that calculates the bodyfat of people. The difficult thing is, that the calculations are different for males and females, so I tried to prompt the user to state whether they are male or female, then use and "if" statement to tether their response to the corresponding calculations.

Here's my algorithm:

Here's what I have:

package bodyweight;
import java.util.Scanner;
public class Weightcalc {
static Scanner console = new Scanner(System.in);
public static void main(String[] args){

[Code] ....

It keeps telling me that bodyweight is not initialized, but when I do, I get a hell of a lot more bugs on everything telling me they aren't initialized. I just want the program to transfer the user to select inputs, based on whether they are male or female.

View Replies View Related

Initializing Arrays Of Various Types

Sep 18, 2014

For basic arrays, we can directly combine declaration and initialization as E.g: int[] num= new int[2]

But can we do this do for forming class object arrays? like

class stu
{
.....
}
stu[] s=new stu[2]
????

View Replies View Related

Initializing Variables In Two Connected Classes

Nov 3, 2014

I am writing a program with different screens. At first you have to log in to access the program. So I have a problem with the variables username and password. I can't seem to get theme from the DbConnection class. I suppose it is a basic problem?

In the DbConnection class i have a problem with the returns.

In the Login class i have a problem with the connection.getUsername(); and connection.getPassword();

Here is some code:

class DbConnection
package kim.contracts.database;
import java.sql.*;
public class DbConnection {
private Connection conn;
private Statement st;
private ResultSet rs;

[Code] .....

View Replies View Related

Initializing Constructor As Parameter For A Method?

Jan 2, 2014

So, I am learning Swing, and Swing Layouts. I just came across a really confusing (for me) line of code.

Java Code:

setLayout(new BorderLayout()); mh_sh_highlight_all('java');

So, this is weird for me because I don't really understand why the BorderLayout class constructor is being initialized as a parameter for the setLayout..

View Replies View Related

Error Occurs Unless Initializing Variable?

Oct 12, 2014

I don't understand that the error occurs when I don't initialize the variable myPoint. Whereas, I initialize the variable myPoint after variable declaration and before place of error.
 
package enumeration;
import java.util.Random; 
public class Craps {

[Code]....

When I initialize the variable myPoint to zero in its decleration, the error disappear. But why? I have already initialized the variable myPoint in default case before the line of error occured..

View Replies View Related

Initializing Object Outputs Zeroes Instead Of Values Given To It

Oct 30, 2014

public class Check2
{
private int red;
private int green;
private int blue;

public Check2(){
red = 0;
green = 0;
blue = 0;

[Code] .....

And when i uses it in another class named "Check" it returns zeroes :

public class Check
{
public static void main(String[] args) {
Check2 obj = new Check2(125,254,12); // the toString method should return the values i gave it here . but it shows me zeroes instead.
System.out.println("the colors are " + obj.toString());
}
}

Output : the colors are (0,0,0)

View Replies View Related

Scanner Is Not Working

Apr 24, 2014

I wrote a piece of code:

for(int i = 0; i < x; i++){
System.out.println("Enter students full name:");
sName[i] = result.fullName(sc.nextLine());
sExam[i] = result.examName("VB");
System.out.println("Enter students exam score:");
int scor = sc.nextInt();
sScore[i] = result.examScore(scor);
sGrade[i] = result.examGrade(scor);
}

When i run it i get:

Enter number of students:
1
Enter students full name:
Enter students exam score:

The problem is, i cant enter "full name", program is just jumping to the next step "exam score".

View Replies View Related

Scanner Ignores Last Int

Feb 9, 2015

why does sevenPointsOrLess only work if I declare it as a String and use next() instead of nextInt()? Also why does it take part of the next line with it?

Here is the text I am trying to scan:

England,3,0,1,2,0
Samoa,1,0,3,0,1

Code:

lineScanner.useDelimiter(",");
country = lineScanner.next();
Won = lineScanner.nextInt();
Drawn = lineScanner.nextInt();
Lost = lineScanner.nextInt();
fourOrMoreTries = lineScanner.nextInt();
sevenPointsOrLess = lineScanner.next();

Results:

country = "England"
Won = "3"
Drawn = "0"
Lost = "2"
fourOrMoreTries = "2"
sevenPointsOrLess = "0 Samoa"

View Replies View Related

Scanner In Java

Jan 3, 2015

I'm trying to write a basic java program so that when I run it, I can store the names and codes of some of my school textbooks...I try the scanner statement to input the name of the book but an exception is thrown when I type the name of the book..I have attached the code for my program.

import java.util.Scanner;
public class Books{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.print("Enter amount of products : ");
int products= s.nextInt();
long [] code= new long[products];
String[] names = new String[products];
for (int x=1;x<(products+1);x++){
System.out.println("Enter IMEI number "+x);
code[x] = s.nextLong();
System.out.println("Enter name "+x);

[code]....

View Replies View Related

Scanner Isn't Accepting Doubles

Jan 25, 2014

I had to use scanner to receive input from the user for a formula and everything compiled and worked correctly except when I entered a double into the Scanner, it only accepts ints and gives me this error every time I enter a double:

java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at TestA1Q2.main(TestA1Q2.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

I know that you usually get that error when the Scanner expects something else that is different from what you type and I have looked over my code time and time again and cannot find anything. I created a test program to see if it was just that problem and not something else in the code and I still got the same error but when I tried compiling and running it here browxy.com everything worked and I got the right answer for the formula. Here's the test I used:

import java.util.Scanner;
public class TestA1Q2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a double");
double velocity = keyboard.nextDouble();
}
}

At this point I'm thinking it might be a problem with my install of DrJava and I've tried re-installing but nothing changed.

View Replies View Related

Scanner Cannot Be Used As Variable In If Statements?

May 18, 2014

I created a variable for the scanner called serena. Serena variable is equal to what the user inputs. My if statement says that if the answer the user enters is not equal to the actual answer then it is to display "wrong". It is a basic math game I am working on. NetBeans is telling me that I cannot use the scanner in an if statement?

package pkgnew;
import java.util.Scanner;
public class New{
public static void main(String args[]){
Scanner serena = new Scanner(System.in);
double fnum, snum, answer;

[Code] ....

Do I have to define Serena as whatever number the user inputs? If so, how?

View Replies View Related

Can Use Java Scanner With String?

Jan 18, 2010

I couldn't get this code working:

import java.util.*;
public class scan {
public static void main (String args[]) {
String testi;
Scanner scan = new Scanner(System.in);

[Code] .....

Did i write something wrong or can't Scanner be used with String?

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

Scanner NextLine Won't Enter Anything

Jan 26, 2014

My program is supposed to let me enter the following info for 3 employees: name, number of hours worked this week, and hourly pay rate. It lets me enter the name for the first employee, but for the second and third, it skips over the name and forces me to enter the number of hours worked and pay rate without a name. I have the code and the output posted below. First the program code:

Java Code:

import java.util.Scanner;
public class SalaryCalc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name;
double hours;
double rate;
double grossPay = 0;
double overtime;

[code]...

Enter hours worked this week: mh_sh_highlight_all('java'); Notice I can only enter the name for the first employee (Bigfoot). If I wanted to enter "Nessie" for my second employee's name, it skips over the name prompt and prompts me for the hours worked instead.

View Replies View Related

True And False / Scanner

Jul 7, 2014

My goal is to ask them for their name and if they got it right then it says yes while if they wrote it wrong, it would say no.

Java Code: public static void main(String[] args) {
Scanner name = new Scanner(System.in);
System.out.println("What is your name?");
String sname = name.nextLine();
name.close();
System.out.println("Are you sure it's " + sname + "?");
Scanner tfname = new Scanner(System.in);
String stfname = tfname.next();

[code]....

View Replies View Related

While Loop In Combination With A Scanner

May 17, 2014

I have the following task given to me (to be solved in NetBeans) :

View the contents of the file tuinman.txt: each line has a (real) number, followed by a line text.

Write the readGardener () method that reads the file completely. Only if the number is negative, write the rest of the line. (For each input line, a new line output.)

Extra: Adjust your method so you get the text after each negative number, written "word by word", among themselves. A word can contain characters that are not "letters" are (,,. '") - ,this you may ignore.

"tuinman.txt" is dutch for "gardener.txt". This txt file is located in the same map where build,nbproject,src, etc... are located. I couldn't solve this task so i looked at the solution. It didn't work... So i tried the solution of the extra bit:

package labo.pkg2;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Methods {
public void readGardener() throws FileNotFoundException {

[Code] ....

The txt file is added as an attachment to this post.

The weird thing is, the first thing the program prints is "Van" "morgen" "ijlt",... wich are words from line 19 in the txt file. All the ones before line 19 the program won't print, even if the number is negative. Even weirder, the next thing that is printed after line 19 is the NUMBER from line 20, nowhere in this code do i tell the program to print a number, and yet it does... But that's not all! From line 19 on, he just prints every single thing in the document except for the negative number, if your mind didn't explode already, it sure did now!

So in short: I need some code that prints all the lines from the txt files that start with a negative number. Only the text may be printed though, there may be no numbers in the output!

The txt file, i couldn't add it as a attachment

123
-456,12 De tuinman en de dood
184,67 was hij, Kees, de enige die het zag, want niemand lette d'r op...
-845,14
-8,12452 Een Perzisch Edelman:
157,24 Dus daar gaan we dan.

[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

Manipulating Strings In A File Scanner

Feb 25, 2014

I was given a text file that has list of names phone numbers, calls in and out etc... Like this

Adams#Marilyn#8233331109#0#0#01012014#C
Anderson#John#5025559980#20#15#12152013#M
Baker-Brown#Angelica#9021329944#0#3#02112014#C

The # are delimiters between data items and each line has the call status as the last item. I need to know how I can display each persons information on the screen in a format such as:

Name Phone Calls Out Calls In Last Call

Marilyn Adams (823) 333-1109 0 0 01-01-2104
John Anderson (502) 555-9980 20 15 12-15-2013
Angelica Baker-Brown (859) 254-1109 11 5 02-11-2014

I have to use substring method to extract the phone number and add parentheses/dashes ect I also must have a while statement and a delimiter...

So Far my code looks like this Also I am in a beginners Java coding class....

import java.util.Scanner;
import java.io.*;
 public class phonedata2_1 {
public static void main (String[] args) throws IOException {
  String Phonefile, FirstName, LastName;
Scanner PhoneScan, fileScan;
 
[Code] ....

View Replies View Related







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