Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let's assume a text file is a Math text book. How should I code to find out the largest number in that file? I'm aware of using StringTokens, parseLong, split, etc. But I can't figure out a proper way to combine them.
To be precise, let's say that text has something like:
Chapter 3.5
Million has 6 zeros. Ex. 6,000,000
Billion has 9 zeros. Ex. 9,000,000,000
Trillion has 12 zeros. Ex. 8,000,000,000,000
The largest number is 8000000000000. How do I extract that?
Thanks in advance.
Use the Scanner interface. This code assumes you pass in the file path as the first argument. The Scanner interface handles commas in numbers. I use BigInteger to handle any size number.
public static void main (String[] args) throws java.lang.Exception
{
BigInteger biggestNumber = null;
Scanner s = new Scanner(new FileReader(args[0]));
while( s.hasNext() ){
if( s.hasNextBigInteger() ){
BigInteger number = s.nextBigInteger();
if( biggestNumber == null || number.compareTo(biggestNumber) == 1 ){
biggestNumber = number;
}
}
else {
s.next();
}
}
System.out.println("Biggest Number: " + biggestNumber.toString());
}
You can play with an online example at: http://ideone.com/zKI5rM . It doesn't read from a file but uses a string in the code instead.
One place this would fail is if the book splits large numbers across lines. I'm not sure what your source material is, but that is something to keep in mind.
Store the largest number seen so far (initially, negative infinity), then go through the entire file extracting each number and if it's greater than the largest number you've stored, store it. At the end, the number stored is the largest number. Use double rather than long to account for very large numbers and noninteger numbers. The simple way to find all integers is to use a Scanner, feeding next() into parseDouble(...) and comparing anything that doesn't throw a NumberFormatException.
The easiest way would be to parse the text file line by line.
You can do this using regular expressions to see if you have any number formats located in the current line. If you do then you can check to see if it's larger than the previously found number.
Here is an excellent tutorial on regular expressions if you haven't came across them yet.
http://www.vogella.com/articles/JavaRegularExpressions/article.html
You can use BigInteger
public class Test {
public static void main(String[] arg) {
String line = "215,485,454,648,464";
String line1 = "5,454,546,545,645";
List<BigInteger> list = new ArrayList<BigInteger>();
list.add(new BigInteger(line.replaceAll(",", "")));
list.add(new BigInteger(line1.replaceAll(",", "")));
Collections.sort(list);
System.out.println("largest: " + list.get(list.size() - 1));
}
}
Output: largest: 215485454648464
For your situation
public static void main(String[] args){
Scanner input = new Scanner(new File("yourFile.txt");
List<BigInteger> list = new ArrayList<BigInteger>();
while (input.hasNextLine()){
String line = input.nextLine();
String[] tokens = line.split("\\s+");
String number = token[5].trim(); // gets only the last part of String
list.add(new BigInteger(line.replaceAll(",", "")));
}
Collections.sort(list);
System.out.println("largest: " + list.get(list.size() - 1));
}
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm doing the Java MOOC by Helsinki University. Stuck on the following problem:
Write a program which prints the integers from 1 to a number given by the user.
Sample output
Where to? 3
1
2
3
The code below outputs the expected results but is not accepted as valid. Any suggestions or pointers are welcome, thank you!
import java.util.Scanner;
public class FromWhereToWhere {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = Integer.valueOf(scanner.nextLine());
int start = 1;
while (start <= userInput) {
System.out.println(start);
start++;
}
}
}
Most likely the system that tests your program is stuffing values into standard input (System.in) with spaces, and assumes that you will read with .nextInt().
If that's not it, double check the program description; what is supposed to happen if I enter -1? 0? 1985985410395831490583440958230598? FOOBAR?
If it doesn't say, then presumably the verifier won't throw those inputs at you (if it does, file a bug with the MOOC provider, the course itself needs fixing if that is the case), but if it does, you're going to have to code those rules in, probably.
This shouldn't be it, but to exactly mirror the desired result, it's System.out.print("Where to? "); - note, no ln, and a trailing space.
You did not check if the user input is valid, I would suggest starting off with the following:
check if userInput is a valid number (includes numeric characters).
check if userInput is larger or equal to 1.
your answer is ok but can be optimized to the beginners levels if that is what your teacher is expecting because:
you can get an int directly from scanner, no need to use the wrapper class Integer.
you can use another loop ... a for loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = scanner.nextInt();
System.out.println("ok!");
for (int i = 1; i <= userInput; i++)
{
System.out.println(i);
}
}
Just try by Removing
System.out.println("Where to?");
with
System.out.print("Where to?");
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I can see that this topic has been heavily discussed, however, I was not able to find an answer to my problem within previous discussions. That being said, I have a very simple problem where I want to ask a user to input a list of cities. After being entered, I am storing the list in an ArrayList cities and using collections.sort to sort them. For some reason, collections.sort is not sorting my ArrayList. Example: User input is "Atlanta, Washington DC, New York". My output, when running the program, is unsorted.
public class CitySortDemo {
public static void main(String[] args) {
ArrayList<String> cities = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("enter as many cities as you can!");
cities.add(input.nextLine());
Collections.sort(cities);
for (int i = 0; i < cities.size(); i++){
System.out.println(cities.get(i));
}
}
}
Your code adds a single string to the collection, "Atlanta, Washington DC, New York". A collection with only one entry is unaffected by sorting. :-)
You probably meant to break that string up, perhaps by splitting it on a comma:
cities.addAll(Arrays.asList(input.nextLine().split("\\s*,\\s*")));
Live Example
That splits the one string into an array of them on a comma optionally preceded and/or followed by whitespace, and adds them all to the collection.
Either you can ask the user how many cities are expected to sort or specify a character that when it is seen, stop taking input and sort them. In this your code, it just takes one line as a string. For example, it takes cities until the user enters the specifier character in which the code is ! then sort.
import java.util.*;
class CitySortDemo {
public static void main(String[] args) {
final String specifier = "!";
String str;
ArrayList<String> cities = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("enter as many cities as you can!");
str = input.nextLine();
while (! str.equals(specifier)) {
cities.add(str);
str = input.nextLine();
}
Collections.sort(cities);
cities.forEach(System.out::println);
}
I am working on a project for school and am having trouble with one part of it. I have a text file in Notepad which contains data concerning each team in the NHL:
Washington Capitals
3.02
2.33
85.2
30.6
28.4
True
Dallas Stars
3.23
2.78
82.3
32.0
28.9
True
...
I am trying to place all of the doubles in an array, but I can't seem to figure out how to skip all of the lines that contain Strings or booleans.
Here is the code that I have so far:
double data[][] = new double[30][6];
int indexRow = 0, indexCol = 0, tracker = 0;
File file = new File(fileName);
Scanner input = new Scanner(file);
while(input.hasNext())
{
if(tracker == 0 || tracker == 6)
{
//skip line
if(tracker == 6)
tracker = 0;
}
data[indexRow][indexCol] = input.nextDouble();
if(indexCol < 6) indexCol++;
if(indexRow < 30 && indexCol % 6 == 0)
{
indexRow++;
indexCol = 0;
}
tracker++;
}
Is there anyway to skip just lines containing Strings and booleans? Thanks in advance.
You could try it like this...
try {
double d = Double.valueOf(currentLine);
// is double
} catch(NumberFormatException e) {
// isn't
}
You cannot skip a line because you need to read it first to see if it is a line you want or a line to throw away. With the format you give, just read the first character of the line and throw away the rest of the line if the first character is a letter. If the first character is a digit then keep the line.
Since an answer was already accepted I wasn't going to offer a solution but the more I thought about it, the more I felt compelled to do so. The issue I see with the accepted answer is that it makes assumptions about the input data, leaving the door open for runtime exceptions down the road. The whole point of OOP is to create robust, reusable code, and to offer such a limited scope solution to a someone who is just learning instills bad practices IMO.
One solution that comes to my mind is using regex to check if the string is numeric:
public static boolean isNumeric (String s)
{
return s.matches("[+-]?\\d*\\.?\\d*");
}
(Note: Depending on the range of your numeric values, you may need to modify the regex pattern to allow commas)
As a check to ensure everything is working properly:
public static void main (String[] args) {
String[] nhlData = { "Washington Capitals",
"3.02",
"2.33",
"85.2",
"30.6",
"28.4",
"True",
"Dallas Stars",
"3.23",
"2.78",
"82.3",
"32.0",
"28.9",
"True",
"0",
"-5.",
"+100"};
for (String s : nhlData) {
System.out.print(s);
if (isNumeric(s)) {
System.out.println(" is numeric");
} else {
System.out.println(" is not numeric");
}
}
}
Another solution would be to take leverage the power of a third-party library like Apache Commons which has static methods that include this functionality: See StringUtils.IsNumeric()
Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.
Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.
I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.
By the way Heres a simple input output
Input
10
0
-1
Q
Output
Average = 3.0
Max = 10.0
My code
public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{
String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}
}
I'm getting an error at double x = inputTwo.nextDouble();.
Heres my thought process.
Lets make a flag and keep looping asking the user for a number until we hit Q. Now my issue is that of course the number needs to be a double and the Q will be a string. So my attempt was to make two scanners
Heres how my understanding of scanner based on chapter two in my book.
Alright so import Scanner from java.util library so we can use this package. After that we have to create the scanner object. Say Scanner input = new Scanner(System.in);. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely input here). The reason this is nice is that it allows us to set our Scanner to doubles and ints etc, when it comes as a default string ( via .nextDouble(), .nextInt());
So since I set result to a string, I was under the impression that I couldn't use the same Scanner object to get a double, so I made another Scanner Object named inputTwo, so that if the user doesn't put Q (i.e puts numbers) it will get those values.
How should I approach this? I feel like i'm not thinking of something very trivial and easy.
You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!
I'm teaching myself how to code with java and I use exercises I find in the Internet to practice what I learn.
Anyway, I'm in a middle of an exercise that asks me to build a method that get two strings containing only the characters "0" and "1" from the user and returns one string of them both (binary)combined
example:
BinaryAdder("0","0") - > "0"
BinaryAdder("1","1") - > "10"
BinaryAdder("10100","111") - > "11011"
what I did is:
import java.util.Scanner;
public class assigment03
{
private static String whichIsBigger(String a, String b)
{
if(a.length()>b.length())
return a;
if(a.length()<b.length())
return b;
if(a.length()==b.length())
return a;
else return null;
}
private static String binaryAdder(String a,String b)
{
int[] binaryResult= new int[maxlength(a,b)+1];
String result="";
if(whichIsBigger(a,b)==a)
{
for(int i=0;i<b.length();i++)
{
binaryResult[i]=a.charAt(i)+b.charAt(i);
}
for(int i=b.length();i<a.length();i++)
{
binaryResult[i]+=a.charAt(i);
}
}
else
{
for(int i=0;i<a.length();i++)
{
binaryResult[i]=b.charAt(i)+a.charAt(i);
}
for(int i=a.length();i<b.length();i++)
{
binaryResult[i]+=b.charAt(i);
}
}
for(int i=0;i<binaryResult.length-1;i++)
{
if(binaryResult[i]>=2)
{
binaryResult[i]=binaryResult[i]%2;
binaryResult[i+1]++;
}
}
for(int i=binaryResult.length-1;i>=0;i--)
{
result+=Integer.toString(binaryResult[i]);
}
return result;
}
private static int maxlength(String a, String b)
{
if(a.length()>b.length())
return a.length();
else
return b.length();
}
public static void main(String[] args)
{
Scanner temp= new Scanner(System.in);
System.out.print(binaryAdder(temp.next(),temp.next()));
}
}
But it doesn't return the right result.
Do you mind help me out here?
thanks a lot!
Reading your question, I understood that you might be looking for some help implementing the methods to actually add two binary numbers, and then giving back the result in base two (which btw might be complicated in Java). However, I believe that this exercise lacks of a very important restriction like the what is max length allowed for the binary numbers to be read (overflows can arise while processing the values with primitive data types like int or String). Also this exercise needs some planning when dealing with none significant zeroes like in these cases because "00110b" = "0110b" = "0110b" and when dealing with rolling over the carry of any addition that yields 2 ("10b") or 3 ("11b"). More information on those topics can be found here, in chapter 2.
At least in Java, when tackling these type of exercises, an option is to avoid dealing with such restrictions and conditions. Java provides a class called BigInteger that takes care of huge values, none significant zeroes, and the carries taking away the burden of dealing with those things from the programmers. Java BigInteger also offers a constructor that can initialize their objects in any base. (Well not any, there are some restrictions to this too, please see this link for more information).
With that said, here is my solution to this exercise:
import java.util.Scanner;
import java.util.ArrayList;
import java.math.BigInteger;
public class BinaryAdder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> numbers = new ArrayList<String>();
String number = "";
int count = 1;
System.out.print("Instructions:\nPlease enter a set of binary numbers. When you are ready to calculate their addition, enter \"done\",\n\n");
System.out.print("Number " + count + ": ");
while(!(number = scanner.next()).equals("done")){
numbers.add(number);
count++;
System.out.print("Number " + count + ": ");
}
System.out.print("Result = " + binaryAdder(numbers) + "b");
scanner.close();
}
public static String binaryAdder(ArrayList<String> numbers){
BigInteger accumulator = new BigInteger("0");
for(String number: numbers){
accumulator = accumulator.add(new BigInteger(number, 2));
}
return accumulator.toString(2);
}
}
Example:
Instructions: Please enter a set of binary numbers. When you are ready
to calculate their addition, enter "done",
Number 1: 00001
Number 2: 011
Number 3: done
Result = 100b
Between lines 8-11 some variables are declared: a scanner to read the binary numbers entered, an array list to store the binary numbers entered, a string to hold a number once is entered, and a int to keep track of how many numbers have been entered, since I extended this solution to add 0,1,2,3,...,n numbers).
Line 13 prints the instructions of this solution. Line 14 only prints "Number 1: ".
The while loop between lines 16-20 sets the value entered to the variable number and checks if it is equal to "done". Given the case it steps out of the loop, otherwise, it adds the number to the array list.
Line 22 prints the result of the addition of all the binary numbers entered.
But the "magic" really happens between lines 27-35 in the method "binaryAdder" (Note that "binaryAdder" receives that ArrayList holding all the numbers entered as a parameter). At line 28 an accumulator of type BigInteger is initialized to zero to hold the addition of all the numbers in the ArrayList. Then, a for loop travels through all the numbers in the array list to add them to the accumulator. Finally, the accumulated value is returned in base two.