Java reading file and do different function - java

I have the textfile as follow, it has 2 section PLUS and MINUS and 2 question in each section. I would want to write a program to solve them. I attached my code below as I could not get to the MINUS potion. The result I got for Minus is still using Plus operator.
math.txt
[Plus]
Question = 0
num1 = 2
num2 = 3
Question = 1
num1 = 4
num2 = 5
[Minus]
Question = 0
num2 = 6
num1 = 5
Question = 1
num2 = 7
num1 = 2
CODE
:
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" = ");
if (file_Array[0].equalsIgnoreCase("num1")) {
num1 = file_Array[1];
} else if (file_Array[0].equalsIgnoreCase("num2")) {
num2 = file_Array[1];
int sum = Integer.parseInt(num1) + Integer.parseInt(num2);
System.out.println("Answer :" + sum);
}
else if (file_Array[0].equalsIgnoreCase("[Minus]")) {
if (file_Array[0].equalsIgnoreCase("num2")) {
num2 = file_Array[1];
} else if (file_Array[0].equalsIgnoreCase("num1")) {
num1 = file_Array[1];
int minus = Integer.parseInt(num2) - Integer.parseInt(num1);
System.out.println("Answer :" + minus);
}
}
}
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
}

My solution is as below :
public static void main(String arg[]) {
BufferedReader in = null;
InputStream fis;
String file = "math.txt";
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
String section=null;
String num1 = null;
String num2 = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" = ");
if (file_Array[0].equalsIgnoreCase("[Minus]"))
{
section="Minus";
}
if (file_Array[0].equalsIgnoreCase("[Plus]"))
{
section="Plus";
}
if (file_Array[0].equalsIgnoreCase("num1")) {
num1 = file_Array[1];
} else if (file_Array[0].equalsIgnoreCase("num2")) {
num2 = file_Array[1];
}
//Solution depends on the fact that there will be a blank line
//after operands.
if (file_Array[0].equals("")){
printResult(section,num1,num2);
}
}
//There is no blank line at the end of the file, so call printResult again.
printResult(section,num1,num2);
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
}
}
private static void printResult(String section,String num1,String num2) {
if (section.equals("Minus")){
int minus = Integer.parseInt(num2) - Integer.parseInt(num1);
System.out.println("Answer :" + minus);
}
if (section.equals("Plus")){
int sum = Integer.parseInt(num1) + Integer.parseInt(num2);
System.out.println("Answer :" + sum);
}
}

Related

Format the output in JAVA

I am little confused about how I can format my output cleanly like the output given below:
My code:
import java.io.*;
import java.util.Scanner;
public class CountChar {
public static void main(String[] args) {
File file = new File("test1.txt");
BufferedReader reader = null;
int numCount = 0;
int otherCount = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please specify the # of intervals: ");
int N = sc.nextInt();
while (true) {
if (N == 2 || N == 4 || N == 5 || N == 10) {
break;
} else {
System.out.println("Your input is not supported, please choose another value: ");
N = sc.nextInt();
}
}
int interval_at = 100 / N;
int[] histogram = new int[N];
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
int num = 0;
try {
num = Integer.parseInt(text);
if (num > 0 && num <= 100) {
numCount++;
int inRange = (num - 1) / interval_at;
histogram[inRange] = histogram[inRange] + 1;
} else {
otherCount++;
}
} catch (NumberFormatException e) {
otherCount++;
continue;
}
}
// creating a file in which the output is stored
File myObj = new File("result1.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
// Writting in a file
FileWriter myWriter = new FileWriter("result1.txt");
myWriter.write("Please specify the # of intervals: ");
myWriter.write("\n" + N);
myWriter.write("\nNumber of integers in the interval [1,100]: " + numCount);
myWriter.write("\nOthers: " + otherCount);
for (int i = 0; i < N; i++) {
myWriter.write("\n" + ((i * interval_at) + 1) + " - " + ((i + 1) * interval_at) + " | ");
for (int j = 0; j < histogram[i]; j++) {
myWriter.write("*");
}
}
myWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
My code output:
1 - 25 | ****************
26 - 50 | *******************
51 - 75 | ***********************
76 - 100 | **********************
I need to format my output as given in the picture above.

How do I place code in IPO format?

I have written code for a program but I have not used methods in my code, and I was wondering how I would implement methods in the code?
I know the basic structure should have the Input, Processing, and Output.
It's all here:
import java.io.*;
public class Question {
public static void main(String[] args) throws IOException {
String name = null;
float mark, total, average, totalAverage = 0;
int totalNumberOfPeople = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Average Calc.\n");
do {
total = 0;
System.out.print("Name: ");
try {
name = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
if(!name.equalsIgnoreCase("end")) {
totalNumberOfPeople++;
System.out.println("Enter marks for " + name + ".");
for(int i=1; i <= 5; i++) {
System.out.print("Enter mark #" + i + " of 5: ");
try {
mark = Float.parseFloat(br.readLine());
}
catch(NumberFormatException nfe) {
mark = 0;
}
catch (IOException e) {
mark = 0;
}
total = total + mark;
}
average = (float)total / 5;
System.out.println("\nThe average of the 5 marks entered is " + average);
totalAverage = totalAverage + average;
}
}
while(!name.equalsIgnoreCase("end"));
System.out.println("Total number of people = " + totalNumberOfPeople);
System.out.println("Final average = " + totalAverage / totalNumberOfPeople );
}
}
You may try to separate in methods like this :
import java.io.*;
public class Question {
public static void main(String[] args) throws IOException {
String name = null;
float mark, total, average, totalAverage = 0;
int totalNumberOfPeople = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("This program will calculate the average of five marks for each person.\n");
do {
total = 0;
name = readName(name, br);
if(!name.equalsIgnoreCase("end")) {
totalNumberOfPeople++;
total = getMarksForStudent(name, total, br);
totalAverage = calculateAverage(total, totalAverage);
}
}
while(!name.equalsIgnoreCase("end"));
printOutput(totalAverage, totalNumberOfPeople);
}
private static float getMarksForStudent(String name, float total, BufferedReader br) {
float mark;
System.out.println("\nPlease enter 5 marks for " + name + ".");
for(int i=1; i <= 5; i++) {
System.out.print("Enter mark #" + i + " of 5: ");
mark = getMark(br);
total = total + mark;
}
return total;
}
private static float calculateAverage(float total, float totalAverage) {
float average;
average = (float)total / 5;
System.out.println("\nThe average of the 5 marks entered is " + average);
totalAverage = totalAverage + average;
System.out.println("============================================================");
return totalAverage;
}
private static void printOutput(float totalAverage, int totalNumberOfPeople) {
System.out.println("============================================================");
System.out.println("Total number of people = " + totalNumberOfPeople);
System.out.println("The overall average for all the people entered = " + totalAverage / totalNumberOfPeople );
}
private static float getMark(BufferedReader br) {
float mark;
try {
mark = Float.parseFloat(br.readLine());
}
catch(NumberFormatException nfe) {
mark = 0;
}
catch (IOException e) {
mark = 0;
}
return mark;
}
private static String readName(String name, BufferedReader br) {
System.out.print("Please enter student name <or enter 'end' to exit> : ");
try {
name = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return name;
}
}

Not reading a line and a while loop and I don't know why

I was trying to figure out why the while loop was not working So I added print statements for depIn1 and value. Why is it skipping over the line depValue1 = Double.parseDouble(depIn1)? If so, wouldn't the while loop still work because of the check that value is not true?
String depIn1 = "";
double originBalance1 = 0.00;
double newBalance1 = 0.00;
double depValue1 = 0.00;
String newNewBalance1 = "";
String originStringBalance1 = "";
boolean value;
BufferedReader depositInput1 = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Amount to withdraw: ");
depIn1 = depositInput1.readLine();
value = isInt(depIn1);
System.out.println("depIn1: " + depIn1);
System.out.println("Value: " + value);
depValue1 = Double.parseDouble(depIn1);
System.out.println("depValue1: " + depValue1);
double doubleBalanceValue = Double.parseDouble(users.get(i).getBalance());
while((depValue1 > bankBalance) || (depValue1 <= 0) || (depValue1 > doubleBalanceValue) || (value != true)){
System.out.print("No! Invalid input! Try again! Amount to withdraw: ");
depIn1 = depositInput1.readLine();
depValue1 = Double.parseDouble(depIn1);
}
System.out.println("Thanks!");
Current output:
Amount to withdraw: asfd
depIn1: asfd
Value: false
You can try that:
public class test {
public static void main(String[] args) throws IOException {
String depIn1 = "";
double originBalance1=0.00;
double newBalance1=0.00;
double depValue1=0.00;
String newNewBalance1 = "";
String originStringBalance1 = "";
boolean value=false;
double bankBalance = 5000.00;
double doubleBalanceValue =5000.00;
BufferedReader depositInput1 = new BufferedReader(new InputStreamReader(System.in));
do{
System.out.print("Amount to withdraw: ");
depIn1 = depositInput1.readLine();
System.out.println("depIn1: " + depIn1);
System.out.println("Value: " + value);
try{
depValue1 = Double.parseDouble(depIn1);
value=true;
}
catch(NumberFormatException e){
value=false;
}
System.out.println("depValue1: " + depValue1);
if(!value){
System.out.print("No! Invalid input! Try again!");
}
else{
System.out.println("Thanks!");
}
}
while((depValue1 > bankBalance) || (depValue1 <= 0) || (depValue1 > doubleBalanceValue) || (value != true));
}
}

Reading from a .txt file

You are given a text file (customer.txt) in which name, lastname and age of customers are stored:
Ali Aslan 25
Ayse Demir 35
Ahmet Gemici 17 .
.
.
You should process this file and find number of customers for each of the following ranges:
0 - 19
20 - 59
60 -
This is my code:
import java.io.*;
import java.util.*;
public class ass11 {
public static void main(String[] args) {
Scanner inputStream = null;
try {
inputStream = new Scanner(new FileInputStream("customer.txt"));
}
catch (FileNotFoundException e) {
System.out.println("file customer.txt not found");
System.exit(0);
}
int next, x = 0, y = 0, z = 0, sum = 0;
while(inputStream.hasNextInt()) {
next = inputStream.nextInt();
sum = sum + next;
if (next >= 60)
x++;
else if (next >= 19 && next <= 59)
y++;
else
z++;
}
inputStream.close();
System.out.println(x + " customer bigger than 60");
System.out.println(y + " customer between 19 and 59");
System.out.println(z + " customers smaller then 19");
}
}
It reads only numbers. When I write a name and surname to the text file, it doesn't work and I don't use the split() method...
I would recommend testing with the original file:
Ali Aslan 25
Ayse Demir 35
Ahmet Gemici 17
Each line is a name plus age, so you would get a code like:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("path/to/file" ), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
String[] contents = line.split(" ");
// Assume contents is 3 long: name, surname, age
System.out.printf("%s %s is %d", contents[0], contents[1], Integer.parseInt(contents[2]));
}
Yes, this does make use of the split method, which makes it easier in my opinion. You could also use the Scanner by calling it in a loop with next(), next() and nextInt()
Try this code. It works.
import java.io.BufferedReader;
import java.io.FileReader;
public class MyProject {
public static void main(String [] args){
String path = "C:/temp/stack/scores.txt";
processTextFile(path);
}
public static void processTextFile(String filePath) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filePath));
String line = br.readLine();
String [] tokens = null;
int score = 0;
int x = 0;
int y = 0;
int z = 0;
while (line != null) {
tokens = line.split(" ");
score = Integer.parseInt(tokens[tokens.length -1]);
if(score >= 0 && score < 20){
x++;
}
if(score >= 20 && score < 60){
y++;
}
if(score > 60){
z++;
}
line = br.readLine();
}
if (br != null) {
br.close();
}
System.out.println("0-20 = " + x + ", 20-60 = " + y + ", 60+ = " + z);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Sorting highscore . Diffuculties with sorting time input

I'm having diffuculties with sorting the input i want it to sort by lowest time first. I'm new to java so i dont know so much I've done a guees a number game but I cant manage to sort the highscore by lowest time here is what i've done so far.
import java.io.*;
import java.util.*;
public class teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeest {
private static void start() throws IOException {
int number = (int) (Math.random() * 1001);
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
String scorefile = "p-lista_java";
int försök = 0;
int gissning = 0;
String namn;
String line = null;
String y;
String n;
String val ;
String quit = "quit";
System.out.println("Hello and welcome to this guessing game" +
"\nStart guessing it's a number between 1 and 1000:");
long startTime = System.currentTimeMillis();
while (true){
System.out.print("\nEnter your guess: ");
gissning = input.nextInt();
försök++;
if (gissning == number ){
long endTime = System.currentTimeMillis();
long gameTime = endTime - startTime;
System.out.println("Yes, the number is " + number +
"\nYou got it after " + försök + " guesses " + " times in " + (int)(gameTime/1000) + " seconds.");
System.out.print("Please enter your name: ");
namn = reader.readLine();
try {
BufferedWriter outfile
= new BufferedWriter(new FileWriter(scorefile, true));
outfile.write(namn + " " + försök +"\t" + (int)(gameTime/1000) + "\n");
outfile.close();
} catch (IOException exception) {
}
break;
}
if( gissning < 1 || gissning > 1000 ){
System.out.println("Stupid guess! I wont count that..." );
--försök;
}
else if (gissning > number)
System.out.println(" Your guess is too high");
else
System.out.println("Your guess is too low");
}
try {
BufferedReader infile
= new BufferedReader(new FileReader(scorefile));
while ((line = infile.readLine()) != null) {
System.out.println(line);
}
infile.close();
} catch (IOException exception) {
}
System.out.println("Do you want to continue (Y/N)?");
val=reader.readLine();
if ((val.equals("y"))||(val.equals("Y"))){
teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeest.start();
}
else
System.out.print("Thanks for playing");
System.exit(0);
}
}
Create a value object that holds all your scoring, time and other details. Create a Comparator that compares the components between two of these holders. The sorting can be achieved by creating a Set of Holder with a Comparator.
If you wish to sort by other properties in a different order simply update the Comparator as appropriate.
Holder {
long time;
int score;
String name;
}
Comparator<Holder> {
int compare( Holder holder, Holder other ){
int result = holder.time - other.time;
if( 0 == result ){
result = holder.score - other.score;
}
return result;
}
}

Categories