Need help reading in 2 digit numbers in a text file - java

This is my code for the project currently. I have any number 10 or above it reads each individual digit instead of the whole number. Any help?
Numbers I am using:
1 3
1 1
-1 -5
5 3
45 45
1001001100 1001001100
import java.util.Scanner;
import java.io.*;
import java.io.PrintWriter;
public class comparison_rylan_howard {
public static void main(String[] args) throws IOException {
Scanner reader = new Scanner(new
File("H:\\NetBeansProjects\\Unit1\\comparison.txt"));
try (PrintWriter writer = new PrintWriter("Results.txt")) {
while (reader.hasNext()) {
double first = reader.nextDouble();
double second = reader.nextDouble();
if (first <= -1 || second <= -1) {
writer.println("Error");
}
if (first > second) {
writer.println(">");
writer.println(" ");
}
if (first < second) {
writer.println("<");
writer.println(" ");
} else {
writer.println("=");
writer.println(" ");
}
}
}
}
}

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class comparison_rylan_howard {
public static void main(String[] args) throws IOException {
Scanner reader = new Scanner(new
File("H:\\NetBeansProjects\\Unit1\\comparison.txt"));
try (PrintWriter writer = new PrintWriter("Results.txt")) {
while (reader.hasNext()) {
double first = reader.nextDouble();
double second = reader.nextDouble();
writer.println(first+","+second );
if (first <= -1 || second <= -1) {
writer.println("Error");
writer.println("");
}
else if (first > second) {
writer.println(">");
writer.println("");
}
else if (first < second) {
writer.println("<");
writer.println("");
} else {
writer.println("=");
writer.println("");
}
}
}
}
}
Output:
1.0,3.0
<
1.0,1.0
=
-1.0,-5.0
Error
5.0,3.0
>
45.0,45.0
=
1.0010011E9,1.0010011E9
=

What you could do is split each line by the whitespace and then parse each element as an entire Integer. Something like:
String[] ints = reader.nextLine().split(' ');
double first = Double.parseDouble(ints[0]);
double second = Double.parseDouble(ints[1]);
What that basically does is take the next line, creates an array where each element is split by a space, and then attempts to process the Strings before and after the space as separate doubles.

Related

Converting Binary to Decimal using a text file

I'm creating a program made up of two java files. The first one involves creating a class that accepts a binary from the user and returns its decimal value. The second involves creating a class that reads a list of binary strings from a text file and writes their decimal values to the console. This class should call methods from the first java class in order to achieve its tasks, and should be able to indicate if one of the strings in this file is not binary.
I have the first java class completed, but I'm having difficulty on the second, specifically on how I can get the program to read each individual String from the text file and then either print out their values or declare that they are not a binary. I also need some help on how to call methods from the first class. Could someone help lead me in the right direction?
Here are both codes:
Class 1:
import java.util.*;
public class BinaryDecoder {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a binary: ");
String binary = input.nextLine();
System.out.println("---------------");
boolean isBinary = binaryDetector(binary);
if(isBinary) {
int count = 0;
for(int i=0; i<binary.length(); i++) {
if(binary.charAt(i) != ' ') {
count++;
}
}
int binarySize = Integer.valueOf(count);
System.out.println("Binary size: " + binarySize);
int decimalValue = binaryToDecimal(binary);
System.out.println("Value = " + decimalValue);
}
else {
System.out.println("Not a binary");
}
}
public static boolean binaryDetector(String x) {
int copyOfInput = Integer.valueOf(x);
while(copyOfInput != 0) {
if(copyOfInput % 10 > 1) {
return false;
}
copyOfInput = copyOfInput/10;
}
return true;
}
public static int binaryToDecimal(String n) {
String num = n;
int dec_value = 0;
int base = 1;
int len = num.length();
for(int i = len - 1; i>= 0; i--) {
if(num.charAt(i) == '1') {
dec_value += base;
}
base = base * 2;
}
return dec_value;
}
}
Class 2
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BinaryToDecimalTester {
public static void main(String[] args) throws Exception{
Scanner inFile = new Scanner(new File("Strings.txt"));
while(inFile.hasNext()) {
String inString = inFile.next();
}
}
}
And let's say for reference that the text file has these numbers in it:
1011010011101
1011101110101
1201234000100
1234456000110
1011010100011
Please let me know if you need any more clarification or information. Thank you all very much!
In order to use methods from BinaryDecoder in BinaryToDecimalTester you will have to import them. The best way would be to declare package in each class and import that using it, for example
Decoder class:
package binarynumbers;
import java.util.*;
public class BinaryDecoder {
public static void main(String[] args) { ...
and then import specific ( or all ) methods in BinaryToDecimalTester:
package stackoverflow;
import java.io.File;
import java.util.Scanner;
import static stackoverflow.BinaryDecoder.binaryToDecimal;
public class BinaryToDecimalTester { ...
importing it this way lets you use it normally as you woud expect :
System.out.println(binaryToDecimal(inString));
Concept of packages and imports is more complicated than this and essential to writing programs.
As to reading each individual line as String from the text file and processing it your class is sufficient, FileInputReader is one of another options to read from file. My example would be this:
package binarynumbers;
import java.io.BufferedReader;
import java.io.FileReader;
import static binarynumbers.BinaryDecoder.binaryToDecimal;
import static binarynumbers.BinaryDecoder.binaryDetector;
public class BinaryToDecimalTester {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("Strings.txt"));
String line = "";
while ((line = br.readLine()) != null)
{
System.out.println(binaryDetector(line));
System.out.println(binaryToDecimal(line));
}
}
}
in terms of implementing method detecting binary numbers I can suggest this article
You have to select which class should be your main.
If you keep 2 as your main and then instead of main in 1 you can read both files in 2 and used the static methods you have created in 1 by importing them in 2.
import BinaryDecoder.binaryToDecimal;
I would recommend you do the check for a binary digit as you try to convert the value. Then throw an exception and print the message if the digit is not binary.
There is no need to first check and then convert the value.
Here is an easy way to do the conversion.
public static int binaryToDecimal(String n) {
int val = 0;
for(char c : n.toCharArray()) {
if (c != '1' && c != '0') {
throw new IllegalArgumentException("Number not binary");
}
val = val*2;
val += c-'0';
}
return val;
}
Now all you need to do is read in the values and call the method. In lieu of the exception you could also return an optional.
public static OptionalInt binaryToDecimal(String n) {
int val = 0;
for(char c : n.toCharArray()) {
if (c != '1' && c != '0') {
return OptionalInt.empty();
}
val = val*2;
val += c-'0';
}
return OptionalInt.of(val);
}
Now just check to see if the returned Optional is empty before you print the result. To read in the values from a file, I would recommend using a scanner instance. Here is an example using the data mentioned in your question along with the required imports.
import java.io.File;
import java.io.IOException;
import java.util.OptionalInt;
import java.util.Scanner;
try (Scanner input = new Scanner(new File("f:/numbers.txt"))) {
while (input.hasNextLine()) {
String str = input.nextLine();
OptionalInt op = binaryToDecimal(str);
System.out.printf("%s -> %s%n", str, op.isPresent() ?
op.getAsInt() : "Non binary string");
}
} catch (IOException ie) {
ie.printStackTrace();
}
prints
1011010011101 -> 5789
1011101110101 -> 6005
1201234000100 -> Non binary string
1234456000110 -> Non binary string
1011010100011 -> 5795

Finding largest value in an array from a text file

I'm programming in Java. I'm not good at programming, but I'm trying.
I managed to create a file that generates an array of 10k random (in range 1 through 1 million) numbers into a text file. This class is called 'CreateDataFile'
What I'm trying to do now is read the array from the text file created in 'CreateDataFile' from a completely different class. This new class is called 'ProcessDataFile'
The first thing I thought about doing is 'extends' the class. So both classes communicate.
The thing is, I know how to create a for loop in a program and then find the largest number. I just don't understand how to read this text file, and create a for loop that processes from the text file and finds the max value.
Here's my CreateDataFile class
import java.io.*;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int [] integers = new int[10000];
Random r = new Random();
try{
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i <integers.length; i++) {
int number = r.nextInt(1000000)+1;
p.print(" " + number);
}
p.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Now this generates the numbers I need into a text file called dataset529.
If everything was in one class, I'd just create a for loop.. something like
int max = integers[0];
for(int i = 0; i<integers.length; i++){
if (integers[i] > max)
System.out.println(integers[i]);
}
But as I'm creating my ProcessDataFile class, I'm having a hard time reading the text file created from the CreateDataFile class.
Any ideas on how I can read this text file and run a for loop over it to find the max number like I used above?
Thanks, any help would be appreciated.
First of all, you should write in the file each number on one line so that it's easier when you read the numbers from the file. This can be done just by doing:
p.print(number + "\n");
After that, you can use this code to get the max of all the numbers:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
String fileName = "dataset529.txt";
String temp;
int max = Integer.MIN_VALUE;
int i = 0;
int[] numbers = new int[10000];
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while((temp = br.readLine()) != null) {
if(temp.isEmpty())
break;
numbers[i++] = Integer.parseInt(temp);
}
}
for(i = 0; i < numbers.length; i++)
if(max < numbers[i])
max = numbers[i];
System.out.println(max);
}
Write the content of each number on new line. While reading the file, maintain a max element.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int[] integers = new int[10000];
Random r = new Random();
try {
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i < integers.length; i++) {
int number = r.nextInt(1000000) + 1;
p.print(number + "\n");
}
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now read the file line by line.
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
int max = Integer.MIN_VALUE;
String line = null;
BufferedReader br = new BufferedReader(new FileReader("dataset529.txt"));
while ((line = br.readLine()) != null) {
int num = Integer.parseInt(line);
if (max < num) {
max = num;
}
}
}
System.out.println(max);
}

Java Scanner issues, Notecard class

I am trying to make a program that is basically virtual notecards. Each notecard has a string for a question and an answer as well as a count for now many times it has been asked. I am using a scanner in many instances and I think i am using it incorrectly, and am not quite sure why. The program will let me answer the first 2 questions, tell me they are incorrect no matter what, and skip letting me answer the last one. Here is the notecard class:
public class Notecard {
public String ans;
public String q;
public int count;
public Notecard(String q, String ans) {
this.q = q;
this.ans = ans;
this.count = 0;
}
public Boolean answer(String effort) {
if (this.q.toUpperCase().equals(effort.toUpperCase())) {
System.out.println("Correct!");
return true;
} else {
System.out.println("Incorrect! Correct answer:" + this.ans);
count++;
return false;
}
}
public void clearCount() {
this.count = 0;
}
public String getQ() {
return this.q;
}
}
and here is my other file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class CreateNotecard {
int trys;
public static void main(String[] args) {
System.out.println("Get ready to be quizzed \n\n");
ArrayList<Notecard> notecards = makeCards();
quiz(notecards);
}
static ArrayList<Notecard> makeCards() {
ArrayList<Notecard> notecards = new ArrayList<Notecard>();
try {
BufferedReader in = new BufferedReader(new FileReader(
"notecards.txt"));
String str;
str = in.readLine();
while ((str = in.readLine()) != null) {
String[] argg = str.split(",");
notecards.add(new Notecard(argg[0], argg[1]));
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
return notecards;
}
static void quiz(ArrayList<Notecard> notecards) {
ArrayList<Notecard> backupList = notecards;
Scanner sc = new Scanner(System.in);
long seed = System.nanoTime();
Collections.shuffle(notecards, new Random(seed));
int total = notecards.size();
int correct = 0;
for (Notecard x : notecards) {
System.out.println(x.getQ());
String effort = sc.next();
Boolean nailedIt = x.answer(effort);
if (nailedIt) {
correct++;
}
}
System.out.println("Total Notecards: " + total + "\nTotal Correct: "
+ correct);
System.out.println("Accuracy: " + (correct / total));
System.out.println("Do you want to repeat? Put \"y\" or \"n\"");
String choice1 = sc.nextLine();
if (choice1.toUpperCase().equals("Y")) {
System.out.println("Use only cards missed or all? Type \"missed\" or \"all\"");
String choice2 = sc.nextLine();
if (choice2.toUpperCase().equals("MISSED")) {
quiz(notecards);
} else {
quiz(backupList);
}
} else {
return;
}
}
}
I have a text file which I am using for this program, it contains
19-9,10
square root of 4,2
capitol of Missouri,Jefferson City
Blastoise's 1st evolution,squirtle
and my output is
Get ready to be quizzed
square root of 4
2
Incorrect! Correct answer:2
capitol of Missouri
Jefferson City
Incorrect! Correct answer:Jefferson City
Blastoise's 1st evolution
Incorrect! Correct answer:squirtle
Total Notecards: 3
Total Correct: 0
Accuracy: 0
Do you want to repeat? Put "y" or "n"
You are comparing the wrong things:
public Boolean answer(String effort) {
if (this.q.toUpperCase().equals(effort.toUpperCase())) {
Should be
if (this.ans.toUpperCase().equals(effort.toUpperCase())) {
The problem is that the Scanner class is looking for a delimiter to create tokens with, which is by default whitespace. Since you enter "2", the Scanner.next() finds no delimiters, so no token.
For example, if you enter "Jefferson City", the Scanner found one delimiter, so two tokens. sc.next in that case would be "Jefferson" only (no "City", that's the next token).
Solution? Read the line from stdin and using sc.nextLine()

Can some one help me with this message java Exception?

i have an assignment in java to sort numbers in ascending order and find the max, min , mean and standard deviation
i have done that already but i wanted to change the program to work with double values but there is an exception showing and i cant solve the problem please help can someone fix it.
import java.io.*;
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class FileJava2 {
static double min,max,sum,k;
static double PS1,PS2;
static double stdev=0;
static double aa, x[]=new double[1000], no;
static String source= "",source2= "";
public static void main (String args[]) throws Exception
{
FileJava2.fileinput();
FileJava2.fileoutput();
FileJava2.sort();
FileJava2.display();
}
public static void sort() throws Exception
{
sum=0;
for(int j=0;j<k;j++){
sum+=x[j];
System.out.print(x[j]+" ");
}
double t;
for(int dd=0; dd<k; dd++){
for(int in=0;in<k-1;in++){
if(x[dd]<x[in])
{t=x[dd];
x[dd]=x[in];
x[in]=t;
}
}
}
min=x[0];max=0;
System.out.print("\nSorted Elements: ");
for(int j=0;j<k;j++){
if(x[j]<min)
min=x[j];
if(x[j]>max)
max=x[j];
source2+=x[j];
System.out.print(x[j]+" ");
source+=x[j];
}
PS1=0;PS2=0;
for( int i=0; i<k;i++) {
PS1 += x[i];
PS2 += Math.pow(x[i], 2);
stdev = Math.sqrt(i*PS2 - Math.pow(PS1, 2))/i;
}
byte buf1[]=source2.getBytes();
OutputStream fo1=new FileOutputStream("SortData.txt");
for (int i=0;i<buf1.length;i++)
{
fo1.write(buf1[i]);
}
}
public static void fileinput() throws Exception{
Scanner s = new Scanner(System.in);
do{
System.out.print("Enter Numbers: ");
aa=s.nextDouble();
if(aa==0)
break;
else
source+=(aa+" ");
} while(aa!=0);
System.out.println("YOUR INPUT: "+source);
k=0;
byte buf[]=source.getBytes();
OutputStream fo=new FileOutputStream("waitingtime");
for (int i=0;i<buf.length;i++)
{
fo.write(buf[i]);
}
System.out.println("\nElements successfuly saved into waitingtime.dat ");
}
public static void fileoutput() throws Exception{
BufferedReader inputStream = null;
try {
inputStream =
new BufferedReader(new FileReader("waitingtime"));
String l;
while ((l = inputStream.readLine()) != null) {
// System.out.println(l);
for ( int i = 0; i < l.length(); i++ ) {
String cc=" "+l.charAt( i );
x[(int)k++]=Integer.parseInt(cc);
// System.out.println(no);
}
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
public static void display(){
System.out.println("\nElements successfuly saved into SortData.dat ");
System.out.print("\nMinimum: "+min);
System.out.print("\nMaximun:"+max);
System.out.print("\nMean:"+sum/k);
System.out.print("\nMidrange:"+(min+max)/2);
System.out.println("\nStandard Deviation:"+stdev);
}
}
and the exception message
Enter Numbers: 1
Enter Numbers: 1
Enter Numbers: 2
Enter Numbers: 5
Enter Numbers: 0
YOUR INPUT: 1.0 1.0 2.0 5.0
Elements successfuly saved into waitingtime.dat
Exception in thread "main" java.lang.NumberFormatException: For input string: "."
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at FileJava2.fileoutput(FileJava2.java:110)
at FileJava2.main(FileJava2.java:21)
and can someone tell me why when i enter 1 it shows 1.0?
Replace this on your for loop of fileoutput() method
for (int i = 0; i < l.length(); i++) {
if (l.charAt(i) != '.' && l.charAt(i) != ' ') {
String cc = (" " + l.charAt(i)).trim();
int result = Integer.parseInt(cc);
if (result != 0) {
x[(int) k++] = result;
}
}
}
You are trying to parse each individual character in the string to an integer. After reading the line "1.0 1.0 2.0 5.0" you need to split the numbers and pass the substrings to parse int/double. You can split using the triple whitespace characters like so:
while ((l = inputStream.readLine()) != null) {
for(String ss:l.split(" ") {
x[(int)k++] = Double.parseDouble(ss);
}
}
This exception:
java.lang.NumberFormatException: For input string: "."
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
Tells you that you that the String . could not be parsed to an int.
And makes sense, because what int could be represented by . ?
import java.io.*;
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class FileJava2 {
static double min,max,sum,k;
static double PS1,PS2;
static double stdev=0;
static double aa, x[]=new double[1000], no;
static String source= "",source2= "";
public static void main (String args[]) throws Exception
{
FileJava2.fileinput();
FileJava2.fileoutput();
FileJava2.sort();
FileJava2.display();
}
public static void sort() throws Exception
{
sum=0;
for(int j=0;j<k;j++){
sum+=x[j];
System.out.print(x[j]+" ");
}
double t;
for(int dd=0; dd<k; dd++){
for(int in=0;in<k-1;in++){
if(x[dd]<x[in])
{t=x[dd];
x[dd]=x[in];
x[in]=t;
}
}
}
min=x[0];max=0;
System.out.print("\nSorted Elements: ");
for(int j=0;j<k;j++){
if(x[j]<min)
min=x[j];
if(x[j]>max)
max=x[j];
source2+=x[j];
System.out.print(x[j]+" ");
source+=x[j];
}
PS1=0;PS2=0;
for( int i=0; i<k;i++) {
PS1 += x[i];
PS2 += Math.pow(x[i], 2);
stdev = Math.sqrt(i*PS2 - Math.pow(PS1, 2))/i;
}
byte buf1[]=source2.getBytes();
OutputStream fo1=new FileOutputStream("SortData.txt");
for (int i=0;i<buf1.length;i++)
{
fo1.write(buf1[i]);
}
}
public static void fileinput() throws Exception{
Scanner s = new Scanner(System.in);
do{
System.out.print("Enter Numbers: ");
aa=s.nextDouble();
if(aa==0)
break;
else
source+=(aa+" ");
} while(aa!=0);
System.out.println("YOUR INPUT: "+source);
k=0;
byte buf[]=source.getBytes();
OutputStream fo=new FileOutputStream("waitingtime");
for (int i=0;i<buf.length;i++)
{
fo.write(buf[i]);
}
System.out.println("\nElements successfuly saved into waitingtime.dat ");
}
public static void fileoutput() throws Exception{
BufferedReader inputStream = null;
try {
inputStream =
new BufferedReader(new FileReader("waitingtime"));
String l;
while ((l = inputStream.readLine()) != null) {
// System.out.println(l);
String numbers[] = l.split(" ");
for (String cc : numbers) {
x[(int)k++]=Double.parseDouble(cc);
// System.out.println(no);
}
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
public static void display(){
System.out.println("\nElements successfuly saved into SortData.dat ");
System.out.print("\nMinimum: "+min);
System.out.print("\nMaximun:"+max);
System.out.print("\nMean:"+sum/k);
System.out.print("\nMidrange:"+(min+max)/2);
System.out.println("\nStandard Deviation:"+stdev);
}
}
Your FileJava2.output() has been changed solve your issue. Using split to get values then converting string to double instead of int.

CS106A handout 6 Exception java.lang.NullPointerException

Got an Error with NullPointerException . (cs106A handout 6 - Name Count using hash map)
Debugger told me the problem located # String input variable. I got no idea how to solve it.
thanks for reading.
import acm.io.*;
import acm.program.*;
import acm.util.*;
import java.util.*;
import java.io.*;
import java.io.BufferedReader.*;
import java.lang.*;
public class NameCounts extends ConsoleProgram{
// hashmap
static HashMap<String,Integer> myUniq = new HashMap<String,Integer>();
static String input ;
static public void insertName(){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Enter name:");
// if keyboard input contain new unique name ,
// store it in the hashmap and count the value +1
input = br.readLine();
if(input.equals("")) break;
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
}
}
catch (IOException e){ };
}
// print and show every single hash map and count value
static public void releaseUnique(){
for(int i= 1 ; i < myUniq.size() ; i++){
System.out.println("Entry"+"[" + input + "]"+"has count"+myUniq.get(input));
}
}
public static void main (String[] args){
insertName();
releaseUnique();
}
}
I think you should change
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
to
if(myUniq.containsKey(input)) {
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input, temp);
} else {
myUniq.put(input, 1);
}

Categories

Resources