Using Substring Methods To Format Numbers Between 1,000 And 999,999
Mar 20, 2015
Write a program that reads number between 1,000 and 999,999 from the user and prints it without a comma separating the thousands. Read the input as string. Find the length of the string and use the substring to break it into two pieces. Do not include the comma. You can then concatenate using the + symbol to reassemble without the comma. For example if the number is 123,456. First would equal 123 and second would equal 456. noCommaNumber - 123456.
I do not think it is required to only allow numbers in that range in the code. My question is how to get the first half of the number before the comma in a string to make the last line work. What I think is not doing what I need is the line String first = numberIn.substring(numberIn.indexOf(",", 0)); This is just the last thing I tried.Getting the second half is done using IndexLastOf method in the substring class javaforumquest.jpg
View Replies
ADVERTISEMENT
May 8, 2014
I am working with a program I wrote for class. I got it to compile and do what I want, But I was wondering how I can format my methods to to display a decimal with 1-2 decimal places. Would I create a method in my NumberAnalysis class to do it for me? Or would I declare an instance of the DecimalFormat class in my main method?
import java.util.Scanner; //Needed for Scanner Class
import java.io.*; //Need for File and IOException
import java.text.DecimalFormat;
public class Ex8_11 {
public static void main(String[] args) throws IOException{
{
DecimalFormat decformatter = new DecimalFormat("#0.00");
[Code] .....
This is my output:
Lowest Number: 1.09
Highest Number: 82.76
Total Number: 367.89000000000004
Total Average Number: 30.657500000000002
Think I just solved the answer to my own question, I did it by declaring double variables in my main method and called the methods and instantiated the variables into the methods... Is there a better way to do this?
package lesson4.skowronek;
import java.util.Scanner; //Needed for Scanner Class
import java.io.*; //Need for File and IOException
import java.text.DecimalFormat;
public class Ex8_11 {
public static void main(String[] args) throws IOException{
[Code] ....
View Replies
View Related
Aug 7, 2014
I am trying to do is extract numbers that are in word format in a long String, i.e. a song, and return each of their numerical values, in order to add them all up. So I'd like to calculate the sum of all of the numbers in the text. This has to work for any piece of text and for all numbers up to a trillion.
So I broke the string down into tokens and stored them in a String []. And I divided up the possible numbers in word format into:
LARGEST: thousand, million, billion, trillion
HUNDRED: hundred
TENS: twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety
UNITS: one, two, three, four, five, six, seven, eight, nine
SPECIALS: ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen
I believe that these are the only words that it will need to recognize. I began reading the tokenized string from right to left and then when I came across a unit, special or tens as the first number I hit, I would then set it's numerical value and check if the word before was also a number and whether to add or multiply etc. i.e. First number hit is a two, if the number before is sixty, then I would just add it to sixty and check the word before that and so on.
However, when implementing it, it seems like an extremely long way around it. How I could implement this in a swifter manner? An example of it working would be:
"Nine Million rockets turned Three times and met Twenty Two Aliens", it would extract, Twenty Two as 2, then 20 = 22, then extract Three as 3, and then Nine Million as 1,000,000 x 9 = 9,000,000
9,000,000 + 22 + 3 = 9,000,025
View Replies
View Related
Jan 25, 2015
I'm trying to put together a method that formats telelphone numbers, but there's a part of my code that not working. If I enter (305)912-5458 into the variable phoneNumb I get an index is out of range error. I added a lot of system out messages so that I can try to get an idea of why the code was crashing.
public static void main(String[] args) {
int intBegin = 0;
int intEnd = 1;
int length;
String charact;
StringBuilder numbuilder = new StringBuilder();
[Code] .....
The error message I'm getting is:
run:
The length is 13
intBegin is at 0
intEnd is at 1
index is at 0
Charcter ( was not inserted
[Code] ....
View Replies
View Related
Feb 28, 2015
I have to write a program that displays the first 100 pentagonal numbers using different methods. This is what I have so far:
Java Code:
public class FivePointOne{
public static void main(String[]args){
System.out.println("The the pentagonal numbers are: ");
}
//this method will find the penagonal numbers
public static int getPentagonalNumber(int n){
[Code] ....
But when I compile it to test it out I receive the error message "Illegal start of expression," ';' expected, and "reach end of file while parsing".
View Replies
View Related
Apr 12, 2015
I got this code with mode methods. The results is not exactly what I want.
Code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.*;
public class ProcessMarks {
private static final int NMARKS = 125;
[Code] ...
Result (it's repeat number):
*Mode is = 53
*Mode is = 53
*Mode is = 53
*Mode is = 53
*Mode is = 53
*Mode is = 62
*Mode is = 62
*Mode is = 62
*Mode is = 62
*Mode is = 62
*Mode is = 67
*Mode is = 67
*Mode is = 67
*Mode is = 67
*Mode is = 67
*Mode is = 77
*Mode is = 77
*Mode is = 77
*Mode is = 77
*Mode is = 77
*Mode is = 78
*Mode is = 78
*Mode is = 78
*Mode is = 78
*Mode is = 78
*Mode is = 85
*Mode is = 85
*Mode is = 85
*Mode is = 85
*Mode is = 85
Result that i want it to be (number appear only once):
*Mode = 53, 62, 67, 77, 78, 85
or
*Mode is = 53
*Mode is = 62
*Mode is = 67
*Mode is = 77
*Mode is = 78
*Mode is = 85
View Replies
View Related
Apr 23, 2014
I'm trying to use regex to find a word containing the substring "cat." I'm not sure why this isn't working?
String match = "^ cat$";
View Replies
View Related
Jun 13, 2014
I have one column "category" which contain data like
`"Failed extract of third-party root list from auto update cab at: [URL] with error: The data is invalid."`
I need to select url part in between `" < > "` sign of category column.
how to do this usign regex?
View Replies
View Related
Mar 22, 2014
(Check substrings) You can check whether a string is a substring of another string by using the indexOf method in the String class. Write your own method for this function. Write a program that prompts the user to enter two strings, and checks whether the first string is a substring of the second.
What the function should return
public class Ex2 {
public static void main(String[] args) {
System.out.println("Input the first string:");
Scanner input = new Scanner(System.in);
String firstString = input.nextLine();
System.out.println("Input the second string:");
String secondString = input.nextLine();
check(firstString,secondString);
[Code] ....
View Replies
View Related
Apr 22, 2014
Why isn't it working?
Java Code:
if ((line.substring(i,i+2)) == "go")
break; mh_sh_highlight_all('java');
I printed this to check if substring works fine, used this:
Java Code: System.out.println(line.substring(i,i+2) + " : "+ length); mh_sh_highlight_all('java');
So, output:
Er : 1
ra : 2
ag : 3
go : 4
on : 5
n' : 6
'> : 7
Line:
String line = "Eragon'>";
Shouldn't it break loop after printing "go : 4"?
line.substring(i,i+2) prints go here. But if doesn't work.
View Replies
View Related
Sep 10, 2014
Why does the substring method subtract an extra 1?
For example:
myString = "Programming and Problem Solving";
myString.substring(0, 7) would be "Program" instead of "Program".
It's not explained in the book I'm reading and didn't see it online.
View Replies
View Related
Sep 4, 2012
I have to alter my Sentence class to find the index of the substring "sip" in Mississippi but I'm really not sure where to begin. This is what I have...
Sentence.java
public class Sentence {
private boolean outcome;
private String sentence;
public Sentence(String aSentence) {
sentence = aSentence;
[Code] ....
I know that I need to change public boolean find(String t) to public int indexOf(String t) but I'm not sure what to start doing to get the index of "sip".
View Replies
View Related
Dec 29, 2014
I am trying for a logic that i have some emp ids as a string seperated by commas and i need the substring of emp ids as below. splitting the string as below.
public static void main(String args[]) {
String empId = "1,2,3,4,5,6,7,8,9,10";
int i;
int count = 9;
for (i = 0; i <= count; i = i + 3) {
System.out.println("Emp IDs are : " +empId);
}}
Result is:
Emp IDs are : 1,2,3,4,5,6,7,8,9,10
Emp IDs are : 1,2,3,4,5,6,7,8,9,10
Emp IDs are : 1,2,3,4,5,6,7,8,9,10
Emp IDs are : 1,2,3,4,5,6,7,8,9,10
But I want the result like:
Emp IDs are : 1,2,3
Emp IDs are : 4,5,6
Emp IDs are : 7,8,9
Emp IDs are : 10
View Replies
View Related
Jul 16, 2014
I'm still working with the singlylinkedlist data structure and trying to return a string of individual characters stored in each node. ( head--('J')---('A')---('V')---('A')---tail ) Hopefully this beautifully executed depiction to the left will clarify.
This is what I came up with after designing the algorithm w/ pen and paper. I know that I'm not accounting for the OutOfBound errors, an empty list, or an index < 0.... I will get to that.
Right now, I'm not sure why my assignment to the character array, ' chars[i] = cursor.getLink(getElement()); ' , is not working. The two methods getLink and getElement, type Node and T, respectively, exist in my Node class which is a private nested class in MySLList. Why would I be getting the following error: "The method getElement() is undefined for the type StringX" ? Is this a good design and implementation of the substring method?
public String substring(int index) {
char[] chars = new char[(getSize() - index)]; //getSize() defines the size of list in MySLList
Node cursor = null;
//Set the cursor to the node = index
if(cursor == head) {
[Code] ....
View Replies
View Related
Jun 18, 2014
Need code logic or regex to get substring between two different delimiters and then parse it into Integer array.
My Input String is : Transmitter#MSE14_REC_FTP40 #138^TPPurgeUility_test #103^YUG_Trans #57^
Output (ie. substring between "#" and "^")
138
103
57
View Replies
View Related
Aug 22, 2014
I tried to create file and write the output of my program in it in java when i use WriteLong then the file does not contain long value, how I create this file my program is to print prime numbers between 500000 to 10000000
public class primenumber {
public static void main(String[] args) {
long start = 5000000;
long end = 10000000;
System.out.println("List of prime numbers between " + start + " and " + end);
for (long i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.println(i);
[Code] ....
View Replies
View Related
Apr 24, 2014
I've just written a program that generates 100 numbers that range from 0 ~ 25 using arrays, the program calls another method that sorts the even numbers into a separate array and returns the array. I need it to display both arrays, however, when I run my program, the numbers of both arrays are mixed together, and I'm not sure how to separate them.
[ public class Array1
{
public static void main(String[] args)
{
int array [ ] = new int[100];
for (int i = 0; i < array.length; i++)
{
array[i] = (int) (Math.random() * 26);
[Code] .....
View Replies
View Related
Feb 1, 2015
I'm trying to make a program that generates 20 random integers between 1 and 20 and then prints the list of random numbers to the screen. After that, I want to print a different list to screen with the same numbers from the first list only skipping any number that has been already printed to the screen. So two lists are printed to the screen. The first one has 20 random numbers. The second one has those same 20 numbers but only prints the numbers in the first list that aren't duplicated. So if m
y list of 20 random integers contains three 2s and two 14s, only one 14 and one 2 is printed to the second list. Currently, my code generates 20 numbers from 1 to 20 and stores those numbers in an array but I don't know how to print solve the second part of my problem. I don't know how to print the s different list only without duplicate numbers. As a result, my output is nothing because it doesn't print any number from the first list as oppose to skipping only duplicate one.
public void randomNum(){
System.out.println("Twenty random integers: ");
int max = 20; // max value for range
int min = 1; // min value for range
Random rand = new Random();
int[] all = new int[20];
[Code] ....
View Replies
View Related
Nov 23, 2014
I have to make a program that prompts the user to enter 10 numbers and at the end it prints out the distinct numbers and then the other numbers that weren't repeated...
I have the part where it prints out the distinct numbers but I stuck on how to make it print out the other numbers that didn't repeat...
import javax.swing.JOptionPane;
public class DistinctNumbers {
public static void main(String[] args) {
String getInput;
int input;
int[] numbers = new int[10];
[Code] ....
View Replies
View Related
Mar 10, 2015
Create an integer array with 10 numbers, initialize the array to make sure there are both positive and negative integers. Write a program to generate two arrays out of the original array, one array with all positive numbers and another one with all negative numbers. Print out the number of elements and the detailed elements in each array.
public class problem3 {
public static void main(String[]args){
int[] numbers = {1, 2, 3, 4, 5, -1, -2, -3, -4, -5};
for (int i = 0; i<numbers.length;){
if(i>0){
System.out.println(numbers);
}
else
System.out.println(numbers);
}
}
}
View Replies
View Related
Jul 31, 2014
I tried out doing number (generated randomly) != (another number) but that does not work. If I for example want a number between 1 and 10, but I do not want the number 5, what can I do in order to make this happen?
View Replies
View Related
Oct 17, 2014
Program is to list all prime numbers between two entered numbers.
import java.util.Scanner;
public class question6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter lower int:");
int x = input.nextInt();
[Code] .....
View Replies
View Related
Jun 9, 2014
<script type="text/javascript">
function CompareDates(id)
{
var monName = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec");
var d = new Date(id);
var curr_date = d.getDate();
[code]....
why the default date format that the textbox accepts is in 'mm/dd/yyyy'.For example if i entered "13-05-2014" then it would return an error stating date is invalid.If i entered "12-05-2014" then it would return "5 Dec, 2014".I did not declare any dateformat anywhere except for the datepickers which as shown above, is 'd MMM, yyyy'.Before this happened i trialed and error many different kind of codes to try to validate the date however it all didnt work and so i reverted it all back to the original codes.Last time the dateformat that the textbox accepted was 'dd/mm/yyyy' and it worked fine with my javascript function except the validation part.
Now it still works except that the dateformat changed to 'mm/dd/yyyy'.I did try to use console.log to find out what's wrong but there were no error messages.Why has the dateformat changed by itself?
View Replies
View Related
May 24, 2006
I'm doing a project in JSP and Oracle..Here in my project there are two types of department.. Accounts and Sales.. Accounts department is able to download some pages to Excel format and it is working properly.. now in the sales they have to download in pdf format.. then only it is possible to send to the HO..now what they are doing is downloading the JSP page in excel format and converting to pdf manually using the Acrobat Printer.. is that possible to change to pdf format.. for converting to excel format.. i'm just using 2 linesand it is here
<%@ page language="java" session="true" import="java.sql.*" import="java.lang.*" contentType="application/vnd.ms-excel" %><%response.setHeader("Content Disposition","attachment; filename=test.xls");%>
in the filename side i chaged to test.pdf.. and in the contentType i changed to Acrobat readerand it is downloading but cannot view the content
View Replies
View Related
Dec 12, 2014
I am getting the following error:
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '.2f'
The line it is referring to is:
System.out.println("
Toppings: ");
for (int i = 0; i < toppings.size(); i++) {
System.out.format("%-15s£%.2f
",BBQSpecial.getToppings().get(i)
.name(), BBQSpecial.getToppings().get(i).getCost());
View Replies
View Related
Jun 4, 2014
When trying to convert the time zone of a date I encountered the log below. java.lang.IllegalArgumentException: Cannot format given Object as a Date..Here is what my code looks like:
1. First I will get the date from the email header by the following code.
String messageDate = (String) mail.headers["Date"];
Output: Wed, 4 Jun 2014 18:30:05 +0800
2. Next I will convert the timezone to EST.
SimpleDateFormat timeZoneConvert = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
timeZoneConvert.setTimeZone(TimeZone.getTimeZone(" EST"));
String l_MailDateEST = timeZoneConvert.format(messageDate.trim());
Once the code run I encounter the said error.
View Replies
View Related