I have to read in a file to my project and then read the file line by line to find the percent of upper case and lower case letters. My output should be 4 lines stating the percent of upper and lower for that specific line in the file. This is what I have to far but it doesn't quite work:
Scanner inFile = new Scanner(new File("file.txt"));
int upper = 0;
int lower = 0;
int total;
double percentU = 0.0;
double percentL = 0.0;
while (inFile.hasNext()) {
String line = inFile.nextLine();
for (int x = 0; x < line.length(); x++)
{
if (Character.isUpperCase(line.charAt(x)))
{
upper++;
}
if (Character.isLowerCase(line.charAt(x)))
{
lower++;
}
total = upper + lower;
percentU = upper/total;
percentL = lower/total;
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
}
}
When you divide an int by another int the result will be also an int. So for example if you divide 30 by 50 the result will be 0 instead of 0.6.
More information:
How to make the division of 2 ints produce a float instead of another int?
Integer division: How do you produce a double?
Division of integers in Java
I Just change these lines removed if (Character.isLowerCase(line.charAt(x))):
if (Character.isUpperCase(line.charAt(x))) {
upper++;
}
if (Character.isLowerCase(line.charAt(x))) {
lower++;
}
To:
if (Character.isUpperCase(line.charAt(x))) {
upper++;
} else {
lower++;
}
And moved these lines out of while loop:
total = upper + lower;
percentU = (float)upper/total;
percentL = (float)lower/total;
System.out.println("total: " + total);
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
Try this solution it's ok:
public static void main(String[] args) {
Scanner inFile = null;
int upper = 0;
int lower = 0;
int total = 0;
double percentU = 0.0;
double percentL = 0.0;
try {
inFile = new Scanner(new File("C:\\temp\\file.txt"));
while (inFile.hasNext()) {
String line = inFile.nextLine();
for (int x = 0; x < line.length(); x++) {
if (Character.isUpperCase(line.charAt(x))) {
upper++;
} else {
lower++;
}
}
}
total = upper + lower;
percentU = (float)upper/total;
percentL = (float)lower/total;
System.out.println("total: " + total);
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Related
I'm trying to get multiple integer values from the same scanner inside a while loop. I need to store all the values so I can use them later. However I can only get the last value from the scanner when the while loop finishes.
int antalHeltal = Integer.parseInt(Antal);
int noll = 1;
int heltal = 0;
String tal1 = "";
Scanner tal = new Scanner(System.in);
while (noll <= antalHeltal) {
noll += 1;
heltal += 1;
System.out.print("ange heltal " + heltal + ": ");
tal1 = tal.next();
try {
Integer.parseInt(tal1);
} catch (NumberFormatException e) {
System.out.println("Ogiltigt värde");
noll -= 1;
heltal -=1;
}
My variables are written in Swedish so sorry in advance but I hope someone can help me with this. It would be much appreciated.
Use a List since it can grow dynamically:
Scanner tal = new Scanner(System.in);
List<Integer> list = new ArrayList<>(); // *** Add this
while (noll <= antalHeltal) {
noll += 1;
heltal += 1;
System.out.print("ange heltal " + heltal + ": ");
tal1 = tal.next();
try {
// **********************************
int num = Integer.parseInt(tal1);
list.add(num);
// **********************************
} catch (NumberFormatException e) {
System.out.println("Ogiltigt värde");
noll -= 1;
heltal -=1;
}
To later access the List:
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
or....
for (int val : list} {
System.out.println(val);
}
New to programming here. I need to write application that does the following...
Squaring application instructions
The code I have so far follows. I am running into a problem where my code will not read from negative integers to strings and properly prompt the user to enter valid data. I believe I need to nest my loops but am having trouble doing so. Any help would be greatly appreciated. Thanks.
import java.util.Scanner;
public class Squaring {
public static int getValidInt(int greaterThan, Scanner scan) {
System.out.println("Enter an integer greater than " + greaterThan + ":" );
int input;
while ( !scan.hasNextInt() ) {
String garbage = scan.next();
scan.nextLine();
System.out.println(garbage + " is not valid input.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
while ( !((input = scan.nextInt()) > greaterThan )) {
int garbage = input;
System.out.println(garbage + " is not greater than 1.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 1 ;
int total = 0;
a = getValidInt(a,scan);
int b = a;
System.out.println(a);
long n = a;
while ( n < 1000000 ) {
System.out.println(n*n);
n = n * n;
total = total + 1;
}
System.out.println(b + " exceeded 1,000,000 after " + total + " squarings.") ;
}
}
Without any try-catch:
public static int getValidInt(int greaterThan, Scanner scan) {
int input = 0;
boolean valid = false;
while (!valid) {
System.out.println("Enter an integer greater than " + greaterThan + ":");
if (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
} else {
input = scan.nextInt();
if (input <= greaterThan) {
System.out.println(input + " is not greater than " + greaterThan);
} else {
valid = true;
}
}
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = getValidInt(1, scan);
System.out.println(a);
int total = 0;
long n = a;
while ( n < 1000000 ) {
n = n * n;
System.out.println(n);
total++;
}
System.out.println(a + " exceeded 1,000,000 after " + total + " squarings.") ;
}
I've come up with the following:
public static int getValidInt(int greaterThan, Scanner scan) {
int number = greaterThan;
do {
while (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
}
number = scan.nextInt();
if (number < greaterThan) {
System.out.println("input is: " + number + " minimum is: " + greaterThan);
}
} while (number < greaterThan);
return number;
}
It has a do while loop which makes sure number cannot be smaller than greaterThan, if it is it will do the while loop again.
Inside the do while loop is another loop which tells the user that their input is garbage, and will continue doing so until a number is inserted.
I have a question with this program I wrote for class. It is functioning exactly the way I need it to except for one minor detail. My while-loop is adding an extra "+" on the end of my print statement.
public class Fractions
{
public static void main (String[] args)
{
//-----declare variables-----
int numOfFractions = 0,
numerator = 0;
double total = 0;
DecimalFormat df1 = new DecimalFormat("#0.##");
Scanner stdIn = new Scanner(System.in);
//----Welcome MSG------
System.out.println("");
System.out.println("\t* * * Welcome to Fractions * * * ");
System.out.println("");
//-----get numOfFractions------
System.out.print("Enter the number of fractions: ");
numOfFractions = stdIn.nextInt();
//----begin loop-------
numerator = 1;
while(numerator <= numOfFractions)
{
while(numOfFractions > 0)
{
System.out.print("" + numerator + "/" + numOfFractions + " " + "+" + " ");
total += (double)numerator / numOfFractions;
numOfFractions--;
numerator++;
}
}
System.out.println("");
System.out.println("");
System.out.print("The total: " + df1.format(total));
System.out.println("");
System.out.println("\nThanks for using the Fraction Adder program\n");
} // end main
} // end pgm
Here is a picture of my output
There are many ways to do this a simplest approach can be by simply using if/else condition, try this:
public class Fractions
{
public static void main(String[] args)
{
// -----declare variables-----
int numOfFractions = 0, numerator = 0;
double total = 0;
DecimalFormat df1 = new DecimalFormat("#0.##");
Scanner stdIn = new Scanner(System.in);
// ----Welcome MSG------
System.out.println("");
System.out.println("\t* * * Welcome to Fractions * * * ");
System.out.println("");
// -----get numOfFractions------
System.out.print("Enter the number of fractions: ");
numOfFractions = stdIn.nextInt();
// ----begin loop-------
numerator = 1;
while (numerator <= numOfFractions)
{
while (numOfFractions > 0)
{
if (numOfFractions > 1)
{
System.out.print("" + numerator + "/" + numOfFractions + " " + "+" + " ");
}
else
{
System.out.print("" + numerator + "/" + numOfFractions + " ");
}
total += (double) numerator / numOfFractions;
numOfFractions--;
numerator++;
}
}
System.out.println("");
System.out.println("");
System.out.print("The total: " + df1.format(total));
System.out.println("");
System.out.println("\nThanks for using the Fraction Adder program\n");
} // end main
} // end pgm
Usually you check if the element you want to print is the last (or the first) element and then add the separator, or not. Here's a simplified example, since I think it's easier to understand what's happening:
String[] arr = new String[] { "a", "b", "c" };
for (int i = 0; i < arr.length; i++) {
if (i > 0)
System.out.print("+");
System.out.print(arr[i]);
}
We print the separator + only for elements at index > 0 and before the actual value. You could also reverse this and print the separator for all elements at index < arr.length - 1 after the actual value.
When using Java 8 you could also use StringJoiner and print the contents after the loop, like this:
String[] arr = new String[] { "a", "b", "c" };
StringJoiner joiner = new StringJoiner("+");
for (int i = 0; i < arr.length; i++)
joiner.add(arr[i]);
In your code this would look something like this:
// ...
StringJoiner joiner = new StringJoiner(" + ");
while (numerator <= numOfFractions) {
while (numOfFractions > 0) {
joiner.add(numerator + "/" + numOfFractions);
total += (double) numerator / numOfFractions;
numOfFractions--;
numerator++;
}
}
System.out.println(joiner.toString());
// ...
Iam developing a program to analyze the source code of programs. Now, I'm having a trouble counting results, here comes my source code:
public void walk(String path) throws FileNotFoundException {
File root = new File(path);
File[] list = root.listFiles();
int countFiles = 0;
if (list == null) {
return;
}
for (File f : list) {
if (f.isDirectory()) {
walk(f.getAbsolutePath());
}
if (f.getName().endsWith(".java")) {
System.out.println("File:" + f.getName());
countFiles++;
Scanner sc = new Scanner(f);
int count = 0;
while (sc.hasNextLine()) {
count++;
sc.nextLine();
}
Scanner sc2 = new Scanner(f);
int lower = 0;
int upper = 0;
int digit = 0;
int whiteSpace = 0;
while (sc2.hasNextLine()) {
String str = sc2.nextLine();
for (int i = 0; i < str.length(); i++) {
if (Character.isLowerCase(str.charAt(i))) {
lower++;
} else if (Character.isUpperCase(str.charAt(i))) {
upper++;
} else if (Character.isDigit(str.charAt(i))) {
digit++;
} else if (Character.isWhitespace(str.charAt(i))) {
whiteSpace++;
}
}
}
System.out.println("Your code contains: " + count + " Lines!, Out of them:");
System.out.println("lower case: " + lower);
System.out.println("upper case: " + upper);
System.out.println("Digits: " + digit);
System.out.println("White Spaces: " + whiteSpace);
}
System.out.println("You have in total: " + countFiles);
}
}
First question: when it comes to countFiles ( which is supposed to tell how many .java files or classes you have in your code) its counting and printing results like the following:
you have in total= 1 file
you have in total= 2 file
so how can i make it to print me the final result directly which is 2 in this case ?
Second question: how can I print the sum of the lines in the code in totally, instead of showing them for each class by it self?
Thanks
it has been solved by adding an if statment outside the for loop as the following:
if(!(countFiles<=0) ){
System.out.println("You have in total: " + countFiles);
}
You're printing the result of countFiles for every java file (it is inside your loop). To print the final results, you need only print out countFiles after you've passed them all.
So simply move the statement outside the loop.
public void walk(String path) throws FileNotFoundException {
// ...
int countFiles = 0;
// ...
for (File f : list) {
// ...
if (f.getName().endsWith(".java")) {
// ...
}
// System.out.println("You have in total: " + countFiles);
}
System.out.println("You have in total: " + countFiles);
}
The answer to your second question is really the same. Move the statements outside the loop.
public void walk(String path) throws FileNotFoundException {
// ...
int countFiles = 0;
// ...
int count = 0;
int lower = 0;
int upper = 0;
int digit = 0;
int whiteSpace = 0;
for (File f : list) {
// ...
// int count = 0;
// int lower = 0;
// int upper = 0;
// int digit = 0;
// int whiteSpace = 0;
if (f.getName().endsWith(".java")) {
// ...
}
// System.out.println("You have in total: " + countFiles);
}
System.out.println("You have in total: " + countFiles);
System.out.println("Your code contains: " + count + " Lines!, Out of them:");
System.out.println("lower case: " + lower);
System.out.println("upper case: " + upper);
System.out.println("Digits: " + digit);
System.out.println("White Spaces: " + whiteSpace);
}
Note that I moved the counters out of the loop because keeping track of results between loop passes requires that I have variables in the scope outside the code block.
my code (reads a text file, uses a class I built to sort through the data, and then outputs onto console), is not printing anything! Can somebody please tell me where my little mistake is! I know the VERY end is not finished yet. Please help!!!!!!!!
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Project02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Product> products = new ArrayList<Product>();
// Enter file name
System.out.print("Enter database file name: ");
String fileName = in.nextLine();
try {
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
System.out.println();
while (inputFile.hasNext()) {
Product p = new Product();
String title = inputFile.nextLine();
String code = inputFile.nextLine();
Integer quantity = inputFile.nextInt();
Double price = inputFile.nextDouble();
inputFile.nextLine();
String type = inputFile.nextLine();
Integer userReview = inputFile.nextInt();
// read in title
p.setName(title);
// read in iCode
p.setInventoryCode(code);
// read in quantity
p.setQuantity(quantity);
// read in price
p.setPrice(price);
// read in type
p.setType(type);
// read in user reviews
while (!userReview.equals(-1)) {
p.addUserRating(userReview);
userReview = inputFile.nextInt();
}
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
inputFile.close();
} catch (IOException e) {
System.out.println("There was an error reading from " + fileName);
}
}
private static String highRating(ArrayList<Product> p) {
int highestR = 0;
int indexOfHighestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() > highestR) {
highestR = p.get(i).getAvgUserRating();
indexOfHighestR = i;
}
}
int zero = 0;
String Star = " ";
while (highestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfHighestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static String lowestRating(ArrayList<Product> p) {
int lowestR = 0;
int indexOfLowestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() < lowestR) {
lowestR = p.get(i).getAvgUserRating();
indexOfLowestR = i;
}
}
int zero = 0;
String Star = " ";
while (lowestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfLowestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static double maxDollar(ArrayList<Product> p) {
double largestP = 0;
int indexOfLargestP = 0;
for (int i = 0; i < p.size(); i++) {
double price = p.get(i).getPrice();
if (p.get(i).getPrice() > largestP) {
largestP = p.get(i).getPrice();
indexOfLargestP = i;
}
}
return largestP;
}
private static int minDollar(ArrayList<Product> p) {
double smallestP = p.get(0).getPrice();
int indexOfSmallestP = 0;
for (int i = 0; i < p.size(); i++) {
if (p.get(i).getPrice() < smallestP) {
smallestP = p.get(i).getPrice();
indexOfSmallestP = i;
}
}
return indexOfSmallestP;
}
private static void inventoryList(ArrayList<Product> p) {
int count =
System.out.println("Product Summary Report: ");
System.out
.println("------------------------------------------------------------");
for (int i = 0; i < count; i++) {
System.out.println("Title: " + p.get(i).getName());
System.out.println("I Code: " + p.get(i).getInventoryCode());
System.out.println("Product Type: " + p.get(i).getType());
System.out.println("Rating: " + p.get(i).getAvgUserRating());
System.out.println("# Rat.: " + p.get(i).getUserRatingCount());
System.out.println("Quantity: " + p.get(i).getQuantity());
System.out.println("Price: " + p.get(i).getPrice());
System.out.println();
}
System.out
.println("-----------------------------------------------------------------");
// System.out.println("Total products in database: " + count);
System.out.println("Highest total dollar item: "
+ p.get(maxDollar(p)) + " ($"+ p.(maxDollar(p)) + ")");
System.out.println("Smallest quantity item: "
+ p.get(minQuantity(quantities)) + " ("
+ types.get(minQuantity(quantities)) + ")");
System.out.println("Lowest total dollar item: "
+ titles.get(minDollar(prices)) + " ($"
+ prices.get(minDollar(prices)) + ")");
System.out
.println("-----------------------------------------------------------------");
}
First...
After you've create an instance of Product, p, you will need to add it to the products list, otherwise you will lose it's reference and won't be able to use it again...
while (inputFile.hasNext()) {
Product p = new Product();
//...
products.add(p);
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
Second...
You will need to pass the products List to something that want's to use/display the information, for example inventoryList...
But wait, that's not working?
If we take a closer look at the the inventoryList method...
int count = 0;
//...
for (int i = 0; i < count; i++) {
We can see that count is always 0, so it will never print anything! You should be using p.size() instead, which is the actually length of the products List
//...
for (int i = 0; i < p.size(); i++) {