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.
Related
I have an array called myArray that contains words separated by a space and trimmed from a PDF from the first page to the last page. I wrote a simple print array method that iterates through and prints each element one by one and it looks great!
Immediately after I have it go through another for loop for the length of the array and checks if (myArray[i].equals("(19)")) {//print something} When printing the array to the console it is clear that the value (19) exists in the array.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class Main {
static File file;
static PDFTextStripper textStripper;
static PDDocument pdDoc;
static COSDocument cosDoc;
static String parsedText;
static int sum = 0;
static String[] myArray;
static String[] events = {"400", "800", "1500",
"3000", "5000", "10000"};
public static void main(String[] args) {
//Read the PDF file into instance variable file
readFile();
try {
parsePDF(file);
} catch (IOException e) {
e.printStackTrace();
}
myArray = parsedText.split(" ");
removeWhiteSpace(myArray);
printArray(myArray);
//System.out.println();
String currentEvent = "";
for (int i = 0; i < myArray.length; i++) {
if (contains(myArray[i])) {
currentEvent = myArray[i];
}
if (!currentEvent.equals("")) {
if (myArray[i].charAt(0) == '(' && (myArray[i].charAt(myArray[i].length() - 1) == ')')) {
String formatedRunners = "";
//It is possible to see some numbers such as (19)) or (19)
if (containsCharacter(myArray[i], ')') == 2) {
formatedRunners = myArray[i].substring(1, myArray[i].length() - 2);
} else {
formatedRunners = myArray[i].substring(1, myArray[i].length() - 1);
}
int numberOfRunners = Integer.parseInt(formatedRunners);
int distance = Integer.parseInt(currentEvent);
sum += numberOfRunners * distance;
//reset currentEvent
currentEvent = "";
}
}
}
//Print total distance in meters
System.out.println(sum + " meters");
//Convert meters to miles using the following equation: meters / 1609.344
System.out.println( Math.round((sum / 1609.344)) + " miles");
}
public static void readFile() {
Scanner c = new Scanner(System.in);
System.out.println("Enter a file path: ");
String filePath = c.nextLine();
file = new File(filePath);
}
public static void parsePDF(File file) throws IOException {
textStripper = new PDFTextStripper();
pdDoc = PDDocument.load(file);
//Parse PDF
textStripper.setStartPage(1);
//textStripper.setEndPage();
//Parsed String
parsedText = textStripper.getText(pdDoc);
}
public static boolean contains(String s) {
for (int i = 0; i < events.length; i++) {
if (s.equals(events[i])) {
return true;
}
}
return false;
}
public static void printArray(String[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
public static void removeWhiteSpace(String[] a) {
for (int i = 0; i < myArray.length; i++) {
if (myArray[i].equals("")) {
//Use some filler to avoid crashes when checking characters
myArray[i] = "NULL";
}
//Trim off all extra whitespace
myArray[i] = myArray[i].trim();
}
}
public static int containsCharacter(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
}
Here is what I want:
Parsing and trimming etc. (OK)
Iterating over myArray (in the main method) and detecting events (OK)
If an event occurred then the next value must be (Any number) like (19)
(NOK)
The number from step 3. will be used to compute another number
Reset the current event to repeat the process over and
over again.
It seems like that it is reading each event correctly but only picks up (19)) instead of (19).
There are several problems in you code (No Exceptionhandling, everything static, small bugs etc.) but I will focus on the major issue. (I removed the code which I did not change)
public class Main {
static File file;
static PDFTextStripper textStripper;
static PDDocument pdDoc;
static COSDocument cosDoc;
static String parsedText;
static int sum = 0;
static String[] myArray = {"Seeded", "3000", "random", 25, "(44)", "1500", "random", "(13)"};
static String[] events = {"400", "800", "1500", "3000", "5000", "10000", "200.000"};
public static void main(String[] args) {
//Read the PDF file into instance variable file
readFile();
try {
parsePDF(file);
} catch (IOException e) {
e.printStackTrace();
}
myArray = parsedText.split(" ");
removeWhiteSpace(myArray);
String currentEvent = "";
for (int i = 0; i < myArray.length; i++) {
if (contains(myArray[i])) {
currentEvent = myArray[i];
}
else if (!currentEvent.isEmpty()) {
Integer value = extractNumber(myArray[i]);
if (!myArray[i].isEmpty() && value!=null) {
int distance = Integer.parseInt(currentEvent);
sum += value.intValue() * distance;
//reset currentEvent
currentEvent = "";
}
}
}
//Print total distance in meters
System.out.println(sum + " meters");
//Convert meters to miles using the following equation: meters / 1609.344
System.out.println( Math.round((sum / 1609.344)) + " miles");
}
public static Integer extractNumber(String toCheck) {
Pattern r = Pattern.compile("^.*?\\([^\\d]*(\\d+)[^\\d]*\\).*$");
Matcher m = r.matcher(toCheck);
if(m.find()) {
return Integer.valueOf(m.group(1));
}
return null;
}
public static void removeWhiteSpace(String[] a) {
for (int i = 0; i < myArray.length; i++) {
//Trim off all extra whitespace
myArray[i] = myArray[i].trim();
}
}
The result is
151500 meters
94 miles
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.
Simply not printing the same output as the line above and I can't figure out why this is happening, I've noticed that it's printing the last N numbers from the end backwards, whatever i input into the parameter it prints that amount a second time.
Here's the main
public class main {
public static void main(String args[]) {
ScalesSolution s1 = new ScalesSolution(11);
s1.println();
ScalesSolution s2 = new ScalesSolution(s1.GetSol());
s2.println();
}
}
Heres the ScalesSolution Class
import java.util.ArrayList;
import java.util.Random;
public class ScalesSolution {
private String scasol;
public void print() {
System.out.print(scasol);
}
// Display the string with a new line
public void println() {
print();
System.out.println();
}
public String GetSol()
{
return scasol;
}
}
Heres the randomOther Class
import java.util.*;
import java.io.*;
public class randomOther {
// Shared random object
static private Random rand;
// Create a uniformly distributed random integer between aa and bb inclusive
static public int UI(int aa, int bb) {
int a = Math.min(aa, bb);
int b = Math.max(aa, bb);
if (rand == null) {
rand = new Random();
rand.setSeed(System.nanoTime());
}
int d = b - a + 1;
int x = rand.nextInt(d) + a;
return (x);
}
// Create a uniformly distributed random double between a and b inclusive
static public double UR(double a, double b) {
if (rand == null) {
rand = new Random();
rand.setSeed(System.nanoTime());
}
return ((b - a) * rand.nextDouble() + a);
}
static public ArrayList<Double> ReadNumberFile(String filename) {
ArrayList<Double> res = new ArrayList<Double>();
Reader r;
try {
r = new BufferedReader(new FileReader(filename));
StreamTokenizer stok = new StreamTokenizer(r);
stok.parseNumbers();
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF) {
if (stok.ttype == StreamTokenizer.TT_NUMBER) {
res.add(stok.nval);
}
stok.nextToken();
}
} catch (Exception E) {
System.out.println("+++ReadFile: " + E.getMessage());
}
return (res);
}
}
Here is the issue the Output:
00101001010101101011001011010101101001011010001011010010101101001001011010010
01011010010
I believe that both outputs should be the same and I see that there is a problem here, not sure why they aren't
I see that the way your are using System.out.print inside your RandomBinaryString(int n) is causing confusion. It is printing and appending to the String s. Try to avoid that. Replacing the System.out.print(s += '0'); and System.out.print(s += '1'); with s += '0'; and s += '1';in the RandomBinaryString will fix your output.
Use the snippet below in your code:
private static String RandomBinaryString(int n) {
String s = new String();
// Code goes here
// Create a random binary string of just ones and zeros of length n
for (int i = 0; i < n; i++) {
int y = randomOther.UI(0, 1);
if (y == 0) {
s += '0';// this line here was changed
} else {
s += '1';// and this line here was changed too
}
}
return (s);
}
Hope this helps!
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()
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);
}