Input From Different Classes - Cannot Cast Int To String

Oct 18, 2014

I am working on a program where I want the user to input multiple classes.

One int, and one String.

Can this be done? if so, how?

I have a tried to get input from both, like in the code below:

Java Code:

import java.util.Scanner;
public class ForumFlowchart {
public static void main(String[]args){
//Creating scanner.
Scanner input = new Scanner(System.in);
//Get information about job
System.out.println("Type in Int");
int i1 = input.nextInt();

[Code] ....

If I keep my input in the same class, I get the error "Can not cast int to string". My question is, it is possible to get an input from both an Int and a String in the same program?

View Replies


ADVERTISEMENT

Getting Class Cast Exception While Using Object Input Stream

Jun 5, 2014

I'm developing an application to track the status of a production flow-line and have hit a bit of a snag. When attempting to read saved data I run into this:

Exception in thread "main" java.lang.ClassCastException: flowline.End_Of_File cannot be cast to flowline.Operation
at flowline.Station.checkLoadPreviousStationStatus(Station.java:91)
at flowline.Station.main(Station.java:212)
Java Result: 1

I've been reading up on different methods to saving and retrieving data and have decided ObjectInputStream would be the best option.

The save method works fine, I opted to use a EndOfFile class to determine when I've reached the end of the input stream. The problem is, when my loop encounters this object, it doesn't terminate the loop.

public void checkLoadPreviousStationStatus() throws FileNotFoundException, IOException,
ClassNotFoundException, EOFException, TempArrayOutOfBoundsException{
Object loadOpn = null;
End_Of_File eof = new End_Of_File();
File f = new File(fileName);

[Code] .....

The Operation cast is a cast to the objects my LinkedList contains. The highlighted line is where the exception occurs.

View Replies View Related

JSP :: Cannot Cast From String To ArrayList

Apr 30, 2012

I'm actually trying to complete the excersise of the Servlets and JSP book in page 303 but I'm getting the following error in Eclipse Cannot cast from String to ArrayList(JSP).Here is the code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.util.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hobbies Sharing</title>
</head>

[code]...

The error as it appears in line <% ArrayList al = (ArrayList)request.getParameter("Names"); %>

View Replies View Related

Cannot Cast From File To String

Jan 24, 2014

I have Java code that iterates through files in a directory like this:

for (File child : dir.listFiles()) {
}

Inside that for loop I want to put the filename into a HashMap like this: autocompleteMap.put((String)child,itemList);

The java compiler doesn't like my cast attempt: "Cannot cast from File to String".How do I convert the filename into a String to put into my hash?

View Replies View Related

String Cannot Be Cast To Boolean

Apr 6, 2014

JAVA CODE:

package gui.dialog;

import cli.data001;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Vector;

[Code] ....

OUTPUT:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
at javax.swing.plaf.synth.SynthTableUI$SynthBooleanTa bleCellRenderer.getTableCellRendererComponent(Synt hTableUI.java:731)
at javax.swing.JTable.prepareRenderer(JTable.java:573 1)
at javax.swing.plaf.synth.SynthTableUI.paintCell(Synt hTableUI.java:684)

[Code] ....

View Replies View Related

JSP :: JSTL And EL - Long Value Cast To String

Mar 27, 2015

I'm trying to write a condition to jstl if tag,

<c:forEach var="ledg" items="user_ledgers">
<c:if test="${ledg.transactionID == param['trns']}">
<c:out value="${ledg.name}"/>
</c:if>
</c:forEach>

Ledg is an object of ledger class and transactionID is a field of type long.

I found this error while runtime.

javax.el.PropertyNotFoundException: Property 'transactionID' not found on type java.lang.String

I tried to convert transactioID value to String by several ways. But not working.

String concatenation
<c:if test="${(ledg.transactionID+’’) == param['trns']}">
Using custom tag
<c:set var="equals" scope="page">
<z:doTheyEquals v1="${ledg.transactionID}" v2="${param['trns']}"/>
</c:set>

It also expects String type.

View Replies View Related

Trying To Cast One Object As Another

Oct 13, 2014

Im trying to loop through a hashmap of objects. They are defined as People objects. People has two subclasses , Instructor and Student. As I am looping through the map of People, I am searching for class Instructor. If I find it, I want to access its method getDepartment in a println by casting to Instructor. When I do I get a runtime error:

Exception in thread "main" java.lang.ClassCastException: java.util.HashMap$Node cannot be cast to uStaff.Instructor
at uStaff.PersonApp.menu(PersonApp.java:108)
at uStaff.PersonApp.main(PersonApp.java:21)

//Instantiate the different Person, student and instructor objects
Person thisPerson = new Person(01,fName,mName,lName,email,ssn,age);
Student thisStudent = new Student(02,"Stacey","Marie","Morgan","smorgan@gmail.com","213-45-6789",20);
thisStudent.setMajor("music");
Instructor thisInstructor = new Instructor(03,"Joe","Douglass","Wells","joe@drumhaven.com","555-98-3029",46);
thisInstructor.setDepartment("Computer Science");

[code]....

View Replies View Related

Cannot Cast From Object To Double

Nov 9, 2014

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("js");
String expres = calc.getText().toString();
calc.setText(expres);
try {
calc.setText(((double)engine.eval(expres)) + "");
} catch (Exception e) {
}

This line: calc.setText(((double)engine.eval(expres)) + "");

*The error message for this line: Cannot cast from object to Double

View Replies View Related

Cast 2D Array To ArrayList

Jan 23, 2014

I ve got a 2d array and I want to cast it in an 2d arraylist. I ve create a function that cast an array to arraylist. My problem arises, when I tried to parse the whole 2d matrix to the arraylist. I use the following code:

Java Code: double sums[][] = computeSums(lab, projections);
ArrayList<ArrayList<Double>> lists = new ArrayList<ArrayList<Double>>();
ArrayList<Double> nu = new ArrayList<Double>();
System.out.println(sums[0].length);
for (int i = 0; i < sums.length; i++) {

ArrayList<Double> tt = toList(sums[i], nu);
lists.add(tt);
} mh_sh_highlight_all('java');

The problem is that only the first matrix sums[0] is copied to the 2d arraylist sums.length times. How is is possible to store all the different sums matrices to the arraylist??

View Replies View Related

When Does Internal Cast Actually Happen

Nov 3, 2014

When does an internal cast actually happen? I am aware that compound assignment operator do an internal cast. Does it happen in Assignment 1?Assignment 2?Assignment 3?Assignment 4?

Java Code:

public class Parser{
public static void main( String[] args){
byte b=1;
short s=1;
int i=1;
s=b;//Assignment 1
s<<=b;//Assignment 2
b<<=s;//Assignment 3
s +=i;//Assignment 4
}
} mh_sh_highlight_all('java');

View Replies View Related

Need Cast For Covariant Method

May 21, 2014

import java.util.ArrayList;
 public class Demo {
        class Expr {}
        abstract class Factory <T extends Expr> {
                abstract T generate();

[Code] ....

Doesn't Factory2 produce Statements?

View Replies View Related

How To Cast Floating Point Number To Int

Jan 7, 2015

the output of this:

int x = (int) 24.6;

View Replies View Related

How To Cast PrintStream Object In ObjectOutPutStream

Jul 10, 2014

I want to write formatted output on a notepad file using ObjectOutputStream but I am not getting it in human readable formatted form

Here is my person class

public class Person implements Serializable {
private String firstName;
private String lastName;
private int age;
public String getFirstName() {
return firstName;

[code]....

I want to know how to use printStream.print() like method to write formatted output.

View Replies View Related

How Is Class Cast In Method Parameter

Jan 15, 2014

how is cast a class at a methods parameters? i have a problems in a methods paramter. i draw red line my exception and mymethods is orage color ....

Caffe drink = new Caffe();
CoffeCup cup = new CoffeCup();
cup.setTempeture(100);
drink.drinkcaffe((CaffeCup)(cup.getTempeture()));

[code]....

View Replies View Related

Compile Error - Cannot Cast From Integer To Byte

May 29, 2014

I have a msg object that contains an ArrayList<Integer> collection. However, in order to send the elements in the array over the udp socket, it needs to be sent as a byte[] array. So why am I using ArrayList<Integer> over byte array in first place? Well when I receive data from socket from embedded c program, I need to get an unsigned representation of the data, and thus I need to store it in integers, since bytes in Java are unsigned and unsigned chars in c that are greater than 127 will yield incorrect values in java. But when I send an ack back over the socket, I need to send the data back as bytes. So I convert the ArrayList<Integer> to a byte array:

Java Code: byte[] data = msg.toByteArray();
DatagramPacket response = new DatagramPacket(data, data.length,
packet.getAddress(), packet.getPort());
public class Gprs {
...
public byte[] toByteArray(){

[Code] ....

The problem is I get an "Cannot cast from Integer to byte" when trying to cast the integer to byte: data[i] = (byte)m_data.get(i);

How can I resolve this?

View Replies View Related

Get A String From User Input?

Apr 13, 2014

I trying to get this code to get user input instead of reading from a hardcoded array. I'm getting compile errors while trying to get user input. Here's some of the code:

Java Code: // BubbleSort Java
// compile with: javac BubbleSort.java
// run with: java BubbleSort

[Code]....

View Replies View Related

Evaluating User Input For String Or Int

Jan 14, 2015

I have to take a users input. The general gist of the problem is I want to convert a decimal number entered by the user inputs into it's binary equivalent....the conversion part I know how to do.

I'm stuck at the user input phase. If the user inputs a decimal number within the correct range (lets say between 0-5000 for this example) the conversion goes ahead as planned and the program outputs on the screen the binary equivalent.

If on the other hand the user inputs a number outside of this range ... OR a String OR and empty space, an error message is given and the user is asked to try again. I don't know how to handle it if the user enters the different types...int or String.

View Replies View Related

String Input / Output And Casting

Oct 2, 2014

I have to create a program that uses the Scanner in String input and Output that will enable the user to convert

double -> int
int -> byte
int -> short
int -> hex-string

The output should look something like this:

Syntax: convert <value> <type>
convert 15.5 int~> 16
convert 128 byte~> -128
<type>: int, byte, short, hex, decimal
Syntax: max <type>
max byte~> 127
<type>: int, byte, short

[Code] ....

View Replies View Related

Program Will Only Accept Input From 1 String?

Jan 14, 2015

I am trying to create a fortune teller and everything is running fine except the program does not prompt you to answer the questions

Do you like donuts?
and
What did you have for breakfast?

Here is the code this is in Bluej :

import java.util.Scanner;
public class FortuneTeller {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to Fortune Teller");

[Code] .....

View Replies View Related

Limit On String Input From Console

Mar 2, 2015

I am trying to make a program in which first I am entering number of charachters and then in nextline their is exactly that number of characters should be enter after than program should stop taking input from console..this is I have try so far

private static ArrayList<String> chars;
static String inputdata;
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
chars=new ArrayList<String>();

[code]....

View Replies View Related

Converting String Input To Double

May 2, 2014

I am supposed to write a program on PuTTY using UNIX (I have Windows 8), but I am not comfortable with it yet, so I am using Java through NetBeans (IDE 7.4).

The program has to follow these instructions (ignore the Linux part of the instructions, the rest is in bold):

Write a program on the Linux system using the putty utility. The program should get strings of data from the command line (that is, look for the data in the "args" array of strings). Use a loop to convert each of the strings in the array into a double and add the number to a total. Print the total after all of the strings have been processed.

The program will use try-catch to catch any error that occurs. If an error occurs, the program will print a message saying that the error occurred. The program can end at that point.

You should create the Java program using the nano editor. The input data should be a list of numbers on the line that runs the program.

The problem so far is that I keep getting an error when converting a String value into a new double value. I have yet to code the try-catch method in my program

Java Code:

import java.util.*;
public class Program13Strings {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("How many lines of data do you wish to enter?");
int size = scan.nextInt();

[Code] ....

*NOTE: right where my code says double newDouble = Double.valueOf(newResponse); is where the error is occurring.

*ERROR: Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"

at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1241)
at java.lang.Double.valueOf(Double.java:504)
at program13strings.Program13Strings.main(Program13St rings.java:21)

Java Result: 1

How can this be fixed so I don't get this error?

View Replies View Related

Input String And Test Whether Or Not It Is Palindrome

Feb 6, 2015

I have to write a program that inputs a string and tests whether or not it is a palindrome. This worked fine, and now I want to make it so I continually enter strings until I tell the program to stop.

The code below compiles just fine, but it doesn't do what I want. Why it doesn't work how I think it should work? (Typing in STOP does not make the program stop.)

Here is the code

import javax.swing.JOptionPane;
public class PalTest {
public static void main(String[] args){
String S="pony";
while(S!="STOP"){
S=JOptionPane.showInputDialog("Enter a string (STOP to terminate):");

[Code] ....

View Replies View Related

Type Safety - Unchecked Cast From Object To LinkedList (EventData)

Feb 28, 2014

I am getting "Type safety: Unchecked cast from Object to LinkedList<EventData>" in eclipse for a piece of code stated below

public LinkedList<EventData> loadFromFile(File file) {
queue=new LinkedList<EventData>();
//Some piece of code
return (LinkedList<EventData>)queue.clone(); //--->getting warning here
}

I know that because clone() method is returning Object, hence compiler doesn't have type information that's why showing warning. I don't want to suppress this warning instead i want to fix it.

View Replies View Related

Scanning Known String And Not Input Typed By User?

Jul 29, 2014

I'm having an issue with my program that needs 2 lines of input when I only want one. First I call Scan.nextLine(); to fetch a word. Then I want Scan.findInLine(word).charAt(number); to scan the string word for a letter instead of having to put another line in the console. How do I make Scan.findInLine(word).charAt(number); scan a single String instead of scanning input typed by the user?

View Replies View Related

Getting User Input From TextArea And Storing It As String Value

Jan 20, 2015

I am having trouble with getting a user input once they enter it in to a JTextArea and then storing it in to a string value. See, I wanted the user to enter an answer in to the JTextArea, and then once I store it in to a string value, I would be able to use it later. I wanted to after storing the variable to print it on to a JLabel, but nothing is showing up... Heres my code.

static String usera[]= new String [10];
for (int i=0; i< usera.length; i++) {
//These are the JTextArea names
usera[0]= Question1.getText();
usera[1]= Question2.getText();

[Code].....

I already initialized the JLabels earlier in my code, and I did not feel the need to post all my code here. This is where I am trying to get the string variable and then printing it out.

View Replies View Related

How To Compare Int To Empty String To Input Error

Apr 16, 2015

I am having issues with the program below everything works but I can't figure out a way to add code that if a user just hits enter without inputting anything it says "entering in nothing is not a valid choice" I am stuck on how to compare a int to a string ...

//import statements
import java.util.*; //for scanner class
// class beginning
public class Guess {
public static void main(String[] args ) {
//Declare variables area

[Code] ....

View Replies View Related







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