Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to read integers from a file in Java and display the highest value, but I'm having a difficult time thinking about it.
import java.util.Scanner;
import java.util.*;
import java.io.*;
public class MyFile
{
public static void main(String[] args) throws Exception
{
String filename;
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the file.");
filename = in.nextLine();
File file = new File("myFile.txt");
Scanner inputfile = new Scanner(file);
while(inputfile.hasNext())
{
int compare = inputfile.nextInt();
}
}
}
The file is simply called myFile.txt and has the integers 23, 34, 45, and 2.
if you require to find the highest value from the file, you can do:
int max = Integer.MIN_VALUE;
while(inputfile.hasNext()) {
int compare = inputfile.nextInt();
if (compare > max){
max = compare;
}
}
System.out.println("highest value:"+ max);
Is this what you are looking for?
Declare a variable maxValue. Initialize this value with the file value in file. Loop through rest of the file comparing the newly read value with the maxValue. If the newly read value is greater than the maxValue. Assign maxValue to that value.
Javadoc states:
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. Your file should contain
23 34 45 2
without commas in between
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
In Codechef and similar sites, the inputs are taken in a single line.While taking two integer inputs in single line is no issue.But how can i can take a string input and a long input in a single line in java.Because if i enter the String first and after giving a space,I enter the the long number, won't the total line be considered as a string.So my question is how can i take a string input and a long input in a single line in Java?
An example -(Source-Codeforces)
5 //no of test cases
Jett 012345678 //String input and long input in a single line.
Viper 111111111
Neon 987654321
Raze 512610294
Reyna 192830492
To get the string and long from one input you need to get the text and the number as a single String and then extract the number from the String. The following code shows how to get a long number from a text which are separated by a space:
public class Test{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input1 = scanner.nextLine();
Long a = Long.parseLong(input1.substring(input1.indexOf(' ') + 1 ));
System.out.println(a);
}
}
import java.util.Scanner;
public class MainApplication{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String input1 = scanner.next();
long input2 = scanner.nextLong();
System.out.println("input1:" + input1);
System.out.println("input2:" + input2);
}
}
> javac MainApplication.java
> java MainApplication
viper 111111111
input1: viper
input2: 111111111
You can use next() first to capture the String datatype, then nextLong() to capture Long datatype.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I was required to make a code that accepted a binary number (1's and 0's) and then counted how many ones were in that binary number. My code fulfills this purpose.
The second part of the exercise is this: if the user enters a number that is NOT binary, I must output that there is an error and keep prompting the user until they give a binary number.
Can someone show me how to incorporate this? I have tried several times but cannot make it click. Thanks! Here is my code.
import java.util.Scanner;
public class NewClass
{
public static void main( String [] args )
{
Scanner scan = new Scanner( System.in);
int i = 0, count = 0;
String number;
System.out.println("Please enter a binary number.");
number = scan.next();
String number1 = "1";
while ((i = number.indexOf(number1, i++)) != -1) {
count++;
i += number1.length();
}
System.out.println("There are "+ count + " ones in the binary number.");
}
}
You already know how to find all of the 1's; you should be able to do something similar to find all of the 0's.
If the sum of those two counts is not the length of the string, there must be at least one illegal character in it.
If you use the parseInt method you can do
Integer.parseInt("1100110", 2) returns 102
or in your case
int intVal = Integer.parseInt(number, 2);
as per the javadocs
Throws:
NumberFormatException - if the String does not contain a parsable int.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to validate input values to pass only integers that are divisible by 10. The code below is failing.
public static void main(String args[]) {
Scanner scan =new Scanner(System.in);
ArrayList<Integer> liste = new ArrayList<Integer>(); // I have filled my array with integers
int x=scan.nextInt();
int y=x%10;
do{
if(y==0){
liste.add(x);}
else if(y!=0){
System.out.println("It is not valid"); continue;
}
else
{System.out.println("Enter only integer"); continue;
}
}while(scan.hasNextInt()); }
System.out.println(liste);
System.out.println("Your largest value of your arraylist is: "+max(liste));
You're calling scan.nextInt() twice. Each time you call it, it will read another int from the input. Thus, if your input was something like
10
5
13
then the 10 would pass the scan.nextInt()%10==0 check, and then 5 would be added to the list. Store the result of scan.nextInt() in a variable first, so the value won't change.
Instead of
if(scan.nextInt()%10==0){
liste.add(scan.nextInt());}
do
int num = scan.nextInt();
if(num%10 == 0){
liste.add(num);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble with an assignment. What's happening is that a file is being read that reads numbers and validates if they're correct values. One of these values contains a letter and I'm trying to get my program to detect that and save the total value that should not be there. Here's the code. I'm reading the data as Strings and then converting the strings into doubles to be compared. I want to validate if the strings being read in are all numbers and then save that value for a later use. Does that make sense? for example the numbers have to be between 0 and 99999 and one value is 573S1, which wouldn't work because it contains an S. I want to save that value 573S1 to be printed as an error from the file at a later point in the code.
public static void validateData() throws IOException{
File myfile = new File("gradeInput.txt");
Scanner inputFile = new Scanner(myfile);
for (int i=0; i<33; i++){
String studentId = inputFile.next();
String toBeDouble = studentId;
Double fromString = new Double(toBeDouble);
if (fromString<0||fromString>99999){
System.out.println();
}
Any help would be greatly appreciated. Thanks a lot!
Edit: Here's what I get if I try to run the program.
Exception in thread "main" java.lang.NumberFormatException: For input string: "573S1"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.valueOf(Double.java:475)
at java.lang.Double.<init>(Double.java:567)
at Paniagua_Grading.validateData(Paniagua_Grading.java:23)
at Paniagua_Grading.main(Paniagua_Grading.java:6)
Because you are using Scanner on a file, Scanner can actually tell you this information with hasNextDouble.
while(inputFile.hasNext()) {
if(inputFile.hasNextDouble()) {
// the next token is a double
// so read it as a double
double d = inputFile.nextDouble();
} else {
// the next token is not a double
// so read it as a String
String s = inputFile.next();
}
}
This kind of convenience is the main reason to use Scanner in the first place.
You could try something like the method below, which will check if a string contains only digits -
private static boolean onlyDigits(String in) {
if (in == null) {
return false;
}
for (char c : in.toCharArray()) {
if (Character.isDigit(c)) {
continue;
}
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(onlyDigits("123"));
System.out.println(onlyDigits("123A"));
}
The output is
true
false
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hi i have a program that doesnt seem to be registering. I am fairly new so I would appreciate any help and there might be stupid mistakes made :/
But the point of the program is the enter a name and then find the name in a file called names.txt and then show the popularity of the name throughout the century. I currently have a program that doesnt seem to be working. Help Please
import java.io.*;
import java.util.Scanner;
public class Babynames{
public static void main (String[] args)throws FileNotFoundException{
Scanner reader = new Scanner(new File("names.txt"));
Scanner input=new Scanner(System.in);
System.out.print("What name would you like to search up: ");
String name = input.nextLine();
Scanner lineScan = new Scanner(name);
String thisname = lineScan.next();
if (name.equals(name))
{
while (lineScan.hasNextInt())
{
int next = lineScan.nextInt();
for (int i = 1900; i <=2000; i+=10)
{
System.out.print(i + next);
}
}
}
else
{
System.out.println("File not found! Try again: ");
String filename = input.nextLine();
Scanner lineScan2 = new Scanner(name);
}
}
}
Edit
it just asks for the name and after that the program ends
Your assignment seems to be:
Accept a baby name as input
find that name in a file that includes some information about that name
output the result which includes the info about the name.
From your code, I'm making an educated guess that a line in your file looks like:
name value value value value value value value value value value value
Where the values represent the popularity of the name 1900 - 2000 by decade (11 values)
So, your program would need to:
Get the user input (name) from System.in using a Scanner .
Open the file
Loop, reading a line from the file
Split the line by space (" ") into a String[] array
Compare the first element (array[0]) to see if it's your name
if it is, go through the rest of the array and output the values