Program only seems to be reading every other line of .txt file - java

I'm working on an assignment in which I use scanners to read lines and tokens of a .txt file. I need to do some conversions and rearrange a few strings, which I have done using some helper methods. The problem is that the code is only working for every other line that it reads from the file. I think I may have messed something up somewhere in the beginning of the code. Any hints or tips on what I would need to modify? Here's what I have thusfar:
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("PortlandWeather2013.txt"));
while (input.hasNextLine()) {
String header = input.nextLine();
System.out.println(header);
Scanner input2 = new Scanner(header);
while (input2.hasNextLine()){
String bottomHeader = input.nextLine();
System.out.println(bottomHeader);
String dataLines = input.nextLine();
Scanner linescan = new Scanner(dataLines);
while (linescan.hasNext()){
String station = linescan.next();
System.out.print(station+ " ");
String wrongdate = linescan.next();
String year = wrongdate.substring(0,4) ;
String day = wrongdate.substring(6);
String month = wrongdate.substring(4,6);
System.out.print(month + "/" + day + "/" + year);
double prcp = linescan.nextDouble();
System.out.print("\t "+prcpConvert(prcp));
double snwd = linescan.nextDouble();
System.out.print("\t " + snowConvert(snwd));
double snow = linescan.nextDouble();
System.out.print("\t" + snowConvert(snow));
double tmax = linescan.nextDouble();
System.out.print("\t" + tempConvert(tmax));
double tmin = linescan.nextDouble();
System.out.println("\t" + tempConvert(tmin));
}
}
}
}
public static double prcpConvert(double x){
double MM = x/1000;
double In = MM * 0.039370;
double rounded = Math.round(In * 10)/10;
return rounded;
}
public static double snowConvert(double x){
double In = x * 0.039370;
double rounded = Math.round(In * 10)/10;
return rounded;
}
public static double tempConvert(double x){
double celsius = x/10;
double fahrenheit = (celsius *9/5)+32;
double rounded = Math.round(fahrenheit *10)/10;
return rounded;
}

nextLine() doesn't just fetch the last line, it also advances a line. Before your second loop you are calling nextLine() twice causing you to advance two lines each iteration of the loop.
You can fix your problem by setting dataLines = bottomHeader instead of calling nextLine() again.

Related

Java throwing exception for "No line found" when attempting to gather input from Scanner object

I am fairly new to Java and am attempting to build a "Top 10 Java Projects for Beginners" project, more specifically, a temperature converter. My code throws the following error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at TempConvert.convertToFar(TempConvert.java:78)
at TempConvert.main(TempConvert.java:15)
I was originally using the scanner "*.nextDouble()" method to grab the double but changed it to the "parseDouble" method as I thought this was perhaps the issue. Alas, this has not helped. Any help resolving this would be greatly appreciated!
public static double convertToFar()
{
Scanner in = new Scanner(System.in);
String userEntry;
double formula, userDouble;
System.out.print("Enter degrees in Celsius: ");
userEntry = in.nextLine();
userDouble = Double.parseDouble(userEntry);
in.close();
formula = (userDouble - 32) * (5/9);
return formula;
}
I think that the in.nextLine() in the methods you wrote eventually collided with the string that was inputted by the user before the input stream had been closed.
I created one Scanner object and sent it to the methods so that they will be able to use that same object. I close it only when the program ends once the user enters 'E'. It worked for me:
import java.util.*;
public class TempConvert {
public static void main(String[] args)
{
double far, cel;
char userChoice;
Scanner in = new Scanner(System.in); // I added this line
userChoice = displayMenu(in);
while (userChoice != 'E')
{
if (userChoice == 'F')
{
far = convertToFar(in);
System.out.println("Converted: " + far + "\u00B0");
userChoice = displayMenu(in);
}
else if (userChoice == 'C')
{
cel = convertToCel(in);
System.out.println("Converted: " + cel + "\u00B0");
userChoice = displayMenu(in);
}
else
{
System.out.println("Invalid Entry");
userChoice = displayMenu(in);
}
}
in.close(); // closing the input stream when the program ends
}
public static void displayTitle()
{
String title = "||---- TEMPERATURE CONVERTER ----||";
String one = "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-";
String two = "|| ** Auth: Arranic ||";
String three = "|| ||";
System.out.println(one + "\n" + three + "\n" + title + "\n" + three + "\n" + two + "\n" + three + "\n" + one);
}
public static char displayMenu(Scanner input)
{
ClearScreen();
displayTitle();
System.out.println("\n");
String choiceString;
char choice;
System.out.println("F - FARENHEIGHT C - CELSIUS E - EXIT");
System.out.print("CONVERT TO: ");
choiceString = input.nextLine();
// input.close() --> removed this line
choice = Character.toUpperCase(choiceString.charAt(0));
return choice;
}
public static void ClearScreen()
{
System.out.print("\033[H\033[2J");
System.out.flush();
}
public static double convertToCel(Scanner in)
{
String userEntry;
double formula, userDouble;
System.out.print("Enter degrees in Fahrenheit: ");
userEntry = in.nextLine();
// in.close() --> removed this line
userDouble = Double.parseDouble(userEntry);
formula = (userDouble - 32) * (5.0/9);
return formula;
}
public static double convertToFar(Scanner in)
{
String userEntry;
double userDouble, formula;
System.out.print("Enter degrees in Celsius: ");
userEntry = in.nextLine();
// in.close() --> removed this line
userDouble = Double.parseDouble(userEntry);
formula = (userDouble * (9.0/5)) + 32;
return formula;
}
}
BTW your calculations are not precise. You should remember that integer/integer = integer. That said, writing 5/9 or 9/5 is not accurate, since the result is an integer type number, and not a double type number, as I assume you wanted to get. (5/9 = 0, 9/5 = 1) So you should have added a 5.0 or 9.0 to the calculations so that Java would understand that you want to get a double type result (double/int = double).
And one more thing, your calculations where misplaced (fahrenheit to celsius gave me the opposite result and vice versa) so I switched them up ;).

Exception in thread "main" java.lang.NumberFormatException: empty String

my program is meant to read from a txt and print certain parts of it. when i try to set Double d4 it gives me an error saying that string is
empty although it's not. and it's also not an issue of formatting since d1-5 worked fine when i removed the line. i also printed data[5] and that showed the proper line from the txt.
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class AAAAAA {
public static void main (String[] args)throws IOException {
final String fileName = "classQuizzes.txt";
//1)
Scanner sc = new Scanner(new File(fileName));
//declarations
String input;
double total = 0.0;
double num = 0;
double count = 0;
double average = 0;
String lastName;
String firstName;
double minimum;
double max;
//2) process rows
input = sc.nextLine();
System.out.println(input);
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
// split the line into pieces of data separated by the spaces
String[] data = line.split(" ");
// get the name from data[]
System.out.println("d5 " +data[4]);
firstName = data[0];
lastName = data[1];
Double d1 = Double.valueOf(data[2]);
Double d2 = Double.valueOf(data[3]);
Double d3 = Double.valueOf(data[4]);
Double d4 = Double.valueOf(data[5]);
Double d5 = Double.valueOf(data[6]);
// do the same...
System.out.println("data " + d3);
total += d1 + d2 + d3 + d5;
count++;
//find average (decimal 2 points)
System.out.println(count);
average = total / count;
System.out.println("Total = " + total);
System.out.println("Average = " + average);
//3) class statistics
//while
}
System.out.println("Program created by");
}
}
The line might not be empty, but when you split it at spaces, if there are two spaces in a row, you will get empty strings in the split. To prevent this, change
String[] data = line.split(" ");
to
String[] data = line.split(" *");
or, perhaps better, since it will deal with tabs and other white space:
String[] data = line.split("\\s*");
To track down these kinds of problems yourself (and to verify that I've diagnosed the problem correctly), you should print out each element of the split array, as well as verify the array length is what you expect.

Having Issues With Fraction To Decimal Converter

I have tested the numbers and they hold the correct values but it is printing out the end result completely wrong. E.X: If I put 2/4, it outputs 1
Here is my code:
import java.util.Scanner;
public class FractionConverter {
public static void main(String[] args) {
System.out.println("Welcome To The JEM Fraction Converter!\n");
Scanner sc = new Scanner(System.in);
String num = "0", choice;
System.out.println("Would You Like To Convert From 'Fraction - Decimal'(a) or 'Decimal - Fraction'(b)?");
choice = sc.nextLine();
if (choice.equalsIgnoreCase("a")) {
System.out.println("Please Enter A Fraction (x/y)");
num = sc.nextLine();
String[] parts = num.split("/");
String numerator = parts[0];
String denominator = parts[1];
double result = Double.parseDouble(numerator);
double result2 = Double.parseDouble(numerator);
System.out.println("\n" + numerator + "/" + denominator + " In Decimal Form Is: " + (result/result2));
}
}
}
Appreciate the help!
Replace this line:
double result2 = Double.parseDouble(numerator);
with this:
double result2 = Double.parseDouble(denominator);
double result = Double.parseDouble(numerator);
double result2 = Double.parseDouble(numerator);
... I suppose is a copy/paste problem, isn't it? (both times numerator)

Java.Lang.Stringindexoutofboundsexception index out of range (0)

each time the program tries to loop, the error "java.lang.stringindexoutofboundsexception" comes up and highlights
ki=choice.charAt(0);
Does anyone know why that happens?. I'm brand new to programming and this has me stumped. Thanks for any help. Any solution to this problem would be amazing.
import java.util.Date;
import java.util.Scanner;
public class Assignment2
{
public static void main(String Args[])
{
Scanner k = new Scanner(System.in);
Date date = new Date();
double Wine = 13.99;
double Beer6 = 11.99;
double Beer12 = 19.99;
double Beer24 = 34.99;
double Spirit750 = 25.99;
double Spirit1000 = 32.99;
int WinePurchase = 0;
double WineTotal=0.0;
double GrandTotal = 0.0;
double GST = 0.0;
String complete = " ";
String choice;
char ki = ' ';
double Deposit750 = 0.10;
double Deposit1000 = 0.25;
System.out.println("------------------------------\n" +
"*** Welcome to Yoshi's Liquor Mart ***\nToday's date is " + date);
System.out.println("------------------------------------\n");
do{
if(ki!='W' && ki!='B' && ki!='S')
{
System.out.print("Wine is $13.99\nBeer 6 Pack is $11.99\n" +
"Beer 12 pack is $19.99\nBeer 24 pack is $34.99\nSpirits 750ml is $25.99\n"+
"Spirits 100ml is $32.99\nWhat is the item being purchased?\n"+
"W for Wine, B for beer and S for Spirits, or X to quit: ");
}
choice = k.nextLine();
ki= choice.charAt(0);
switch (ki)
{
case 'W':
{
System.out.print("How many bottles of wine is being purchased: ");
WinePurchase = k.nextInt();
System.out.println();
WineTotal = Wine*WinePurchase;
GST = WineTotal*0.05;
WineTotal += GST;
System.out.println("The cost of "+WinePurchase+ " bottles of wine including" +
" GST and deposit is " + WineTotal);
System.out.print("Is this customers order complete? (Y/N) ");
complete = k.next();
break;
}
}
}while (ki!='X');
The error means there the index "0" is outside the range of the String. This means the user typed in no input, such as the case when you start the program and hit the enter key. To fix this, simply add the following lines of code:
choice = k.nextLine();
if(choice.size() > 0){
//process the result
}
else{
//ignore the result
}
Let me know if this helps!
As you pointed out, the problem is in:
choice = k.nextLine();
ki= choice.charAt(0);
From the docs nextLine(): "Advances this scanner past the current line and returns the input that was skipped."
So in case the user pressed "enter" the scanner will go to the next line and will return an empty String.
In order to avoid it, simply check if choice is not an empty string:
if (!"".equals(choice)) {
// handle ki
ki= choice.charAt(0);
}
Try this:
Your problem was with the Scanner (k) you need to reset it everytime the loop start over.
import java.util.Date;
import java.util.Scanner;
public class Assignment2
{
public static void main(String Args[])
{
Scanner k;
Date date = new Date();
double Wine = 13.99;
double Beer6 = 11.99;
double Beer12 = 19.99;
double Beer24 = 34.99;
double Spirit750 = 25.99;
double Spirit1000 = 32.99;
int WinePurchase = 0;
double WineTotal=0.0;
double GrandTotal = 0.0;
double GST = 0.0;
String complete = " ";
String choice;
char ki = ' ';
double Deposit750 = 0.10;
double Deposit1000 = 0.25;
System.out.println("------------------------------\n" +
"*** Welcome to Yoshi's Liquor Mart ***\nToday's date is " + date);
System.out.println("------------------------------------\n");
do{
if(ki!='w' && ki!='b' && ki!='s')
{
System.out.print("Wine is $13.99\nBeer 6 Pack is $11.99\n" +
"Beer 12 pack is $19.99\nBeer 24 pack is $34.99\nSpirits 750ml is $25.99\n"+
"Spirits 100ml is $32.99\nWhat is the item being purchased?\n"+
"W for Wine, B for beer and S for Spirits, or X to quit: ");
}
k= new Scanner(System.in);
choice = k.nextLine();
ki= choice.toLowerCase().charAt(0);
switch (ki)
{
case 'w':
System.out.print("How many bottles of wine is being purchased: ");
WinePurchase = k.nextInt();
System.out.println();
WineTotal = Wine*WinePurchase;
GST = WineTotal*0.05;
WineTotal += GST;
System.out.println("The cost of "+WinePurchase+ " bottles of wine including" +
" GST and deposit is " + WineTotal);
System.out.print("Is this customers order complete? (Y/N) ");
complete = k.next();
break;
}
if(complete.toLowerCase().equals("y"))
break;
}while (ki!='x');
}
}

Java fraction calculator, global variables?

This is my second time asking this question because this assignment is due tomorrow, and I am still unclear how to progress in my code! I am in an AP Computer programming class so I am a complete beginner at this. My goal (so far) is to multiply two fractions. Is there any way to use a variable inside a particular method outside of that method in another method? I hope that wasn't confusing, thank you!!
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3 {
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args){
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for input
intro();
}
public static void intro(){
Scanner input = new Scanner(System.in);
String user= input.nextLine();
while (!user.equals("quit") & input.hasNextLine()){ //processes code when user input does not equal quit
StringTokenizer chunks = new StringTokenizer(user, " "); //parses by white space
String fraction1 = chunks.nextToken(); //first fraction
String operand = chunks.nextToken(); //operator
String fraction2 = chunks.nextToken(); //second fraction
System.out.println("Fraction 1: " + fraction1);
System.out.println("Operation: " + operand);
System.out.println("Fraction 2: " + fraction2);
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for more input
while (user.contains("*")){
parse(fraction1);
parse(fraction2);
System.out.println("hi");
int num = num1 * num2;
int denom = denom1 * denom2;
System.out.println(num + "/" + denom);
user = input.next();
}
}
}
public static void parse(String fraction) {
if (fraction.contains("_")){
StringTokenizer mixed = new StringTokenizer(fraction, "_");
int wholeNumber = Integer.parseInt(mixed.nextToken());
System.out.println(wholeNumber);
String frac = mixed.nextToken();
System.out.println(frac);
StringTokenizer parseFraction = new StringTokenizer(frac, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}
else if (!fraction.contains("_") && fraction.contains("/")){
StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}else{
StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
int num = Integer.parseInt(whiteSpace.nextToken());
System.out.println(num);
}
}}
Is there any way to use a variable inside a particular method outside of that method in another method?
Yes you can do that. You can declare a variable in a method, use it there and pass it to another method, where you might want to use it. Something like this
void test1() {
int var = 1;
System.out.println(var); // using it
test2(var); // calling other method and passing the value of var
}
void test2(int passedVarValue) {
System.out.println(passedVarValue); // using the passed value of the variable
// other stuffs
}

Categories

Resources