Java outputting different row numbers for each output - java

I have this code that prints out the max value of each row I have. But I am having trouble also printing out the row number for each output.I tried using i to add 1 to each row. Obviously this does not work with it, just wanted to show my attempt. Without the i the code works fine for finding the max value of my string from a text file. If there is another way to change my row number for each output it would be much appreciated. For example,
Row 1: 5
Row 2: 67
row 3: 43
is what i want. All i have been able to get is:
Row 1: 5
Row 1: 67
row 1: 43
My java code
import java.util.Scanner;
public class maxValue {
public static void main(String[] args) throws Exception {
int i=0;i<3;i++;
String fileName="C:\\Users\\Michael\\Documents\\input.csv";
File f = new File(fileName);
Scanner fileScan= new Scanner(f);
while(fileScan.hasNext()) {
String line=fileScan.nextLine();
System.out.println("ROW " + i + ": " + (extractMaximum(line)));
}
fileScan.close();
}
static int extractMaximum(String str) {
int num = 0;
int res = 0;
// Start traversing the given string
for (int i = 0; i<str.length(); i++) {
// If a numeric value comes, start converting
// it into an integer till there are consecutive
// numeric digits
if (Character.isDigit(str.charAt(i)))
num = num * 10 + (str.charAt(i)-'0');
// Update maximum value
else {
res = Math.max(res, num);
// Reset the number
num = 0;
}
}
// Return maximum value
return Math.max(res, num);
}
}

You need to increment i in the loop:
public static void main(String[] args) throws Exception
{
String fileName="C:\\Users\\Michael\\Documents\\input.csv";
File f = new File(fileName);
Scanner fileScan = new Scanner(f);
// One option: a for loop
for (int i = 1; fileScan.hasNext(); i++) {
String line = fileScan.nextLine();
// I prefer printf
System.out.printf("ROW %d: %d%n", i, extractMaximum(line));
}
fileScan.close();
}
// Re-written to use streams
// Even if you don't want to use stream,
// Using the regex to split the string is an improvement
static int extractMaximum(String str)
{
return Arrays.stream(str.split("\\D+"))
.map(x -> Integer.parseInt(x))
.max(Integer::compare)
.get();
}

Related

how do i detect a double line break in a data file

I have a data file that consists of a calorie count.
the calorie count it separated by each elf that owns it and how many calories are in each fruit.
so this represents 3 elves
4323
4004
4070
1780
5899
1912
2796
5743
3008
1703
4870
5048
2485
1204
30180
33734
19662
all the numbers next to each other are the same elf. the separated ones are seperate.
i tried to detect the double line break like so
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String [] args) throws FileNotFoundException
{
int[] elf = new int[100000];
int cnt = 0;
Scanner input = new Scanner(new File("Elf.dat"));
while(input.hasNext())
{
elf[cnt] += input.nextInt();
if (input.next().equals("\n\n"));
{
cnt++;
}
}
int big = elf[0];
for (int lcv = 0; lcv < elf.length; lcv++)
{
if (big < elf[lcv])
{
big = elf[lcv];
}
}
System.out.println(big);
}
}
I'm trying this to detect the double line break
if (input.next().equals("\n\n"));
but its giving me errors. how would i detect it
Here is another alternative way to do this sort of thing. read comments in code:
public static void main(String[] args) throws FileNotFoundException {
List<Integer> elfSums; // Can grow dynamically whereas an Array can not.
int sum;
// 'Try With Resources' used here to auto close the reader and free resources.
try (Scanner input = new Scanner(new File("Elf.dat"))) {
elfSums = new ArrayList<>();
String line;
sum = 0;
while (input.hasNextLine()) {
line = input.nextLine();
if (line.trim().isEmpty()) {
elfSums.add(sum);
sum = 0; // Reset sum to 0 (new elf comming up)
}
// Does the line contain a string representation of a integer numerical value?
if (line.matches("\\d+")) {
// Yes...add to current sum value.
sum += Integer.parseInt(line);
}
}
}
if (sum > 0) {
elfSums.add(sum);
}
// Convert List to int[] Array (There are shorter ways to do this)
int[] elf = new int[elfSums.size()];
for (int i = 0; i < elfSums.size(); i++) {
elf[i] = elfSums.get(i);
// For the heck of it, display the total sum for this current Elf
System.out.println("Elf #" + (i+1) + " Sum: -> " + elf[i]);
}
/* The elf[] int array now holds the data you need WITHOUT
all those empty elements with the array. */
}
Welcome to Advent of Code 22.
As a good rule, never mix nextXXX methods with any other next.
To break up the Blocks you have 2 good options:
Read line by line and fill a new list when you encounter a empty/blank line
Read the whole text fully, then split by the \n\n Combination

Find the occurrence of each character in a given string

"I want to find and print the occurrence of each character of given string and i have build my own logic but there is some problem.for example if i gave input as 'JAVA'.
the output that my program produce will be
J 1
A 2
V 1
A 1
Expected output :
J 1
A 2
V 1
i doesn't want to print A again. I hope you all get it what is the problem in my code."
import java.util.Scanner;
public class FindOccuranceOfCharacter {
public static void main(String[] args) {
// TODO Auto-generated method stub
String x;
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
x = input.nextLine();
x = x.toUpperCase();
int size = x.length();
for(int i =0;i<size;i++) {
int count=1;
char find = x.charAt(i);
for(int j=i+1;j<size;j++) {
if(find == x.charAt(j)) {
count++;
}
}
System.out.printf("%c\t%d",x.charAt(i),count);
System.out.println();
}
}
}
The reason your code prints the way it does is that your loop prints each character (and subsequent matches) for a given index. You really need to store the character and counts in a data structure with one loop, and then display the counts with a second. A LinkedHashMap<Character, Integer> is perfect for your use case (because it preserves key insertion order, no additional logic is needed to restore input order). Additional changes I would make include using String.toCharArray() and a for-each loop. Like,
Map<Character, Integer> map = new LinkedHashMap<>();
for (char ch : x.toUpperCase().toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for (char ch : map.keySet()) {
System.out.printf("%c\t%d%n", ch, map.get(ch));
}
Which I tested with x equal to JAVA and got (as requested)
J 1
A 2
V 1
Using hashMap it's easy to accumulate the number of occurrences and you can easily print iterating the HashMap.
This is the code:
public class FindOccuranceOfCharacter {
public static void main(String[] args) {
String x;
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
x = input.nextLine();
HashMap<Character,Integer> occurance = new HashMap<Character,Integer>();
x = x.toUpperCase();
int size = x.length();
for(int i =0;i<size;i++) {
int count=1;
char find = x.charAt(i);
occurance.put(find, occurance.getOrDefault(find, 0) + 1);
}
for (Character key : occurance.keySet()) {
Integer value = occurance.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
}
This is not an optimal solution, but I have tried to change your code as little as possible:
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
// use a StringBuilder to delete chars later on
StringBuilder x = new StringBuilder(input.nextLine().toUpperCase());
for(int i=0;i<x.length();i++) {
int count=1;
char find = x.charAt(i);
// go through the rest of the string from the end so we do not mess up with the index
for(int j=x.length()-1;j>i;j--) {
if(find == x.charAt(j)) {
count++;
// delete counted occurences of the same char
x.deleteCharAt(j);
}
}
System.out.printf("%c\t%d",x.charAt(i),count);
System.out.println();
}
}
My more preferred Java stream would look like this:
input.nextLine().toUpperCase().chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.forEach((k, v) -> System.out.println(k + "\t" + v));

Java Reversedigit check program

I've written a Reverse digit program but need to check this program to see if it is working correctly. What am I missing an if/else statement?
import java.util.*;
public class IT145_Homework_7_3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// input int parameter
System.out.print("Enter number to reverse: ");
//sets variables
int original = scanner.nextInt();
int reverse = 0;
int remainder;
//original number equals 542
while (original != 0) {
remainder = original % 10; //2 //4 //5
reverse = reverse * 10 + remainder; //2 //24 //245
original = original / 10; //54 //5 //0
}
//Prints out numbers in Reverse
System.out.println("Reverse of number is: " + reverse);
}
}
Here's one way to do the check, but you have to keep an int of the original before you change the original. I called it originalInt
// sets variables
int original = scanner.nextInt();
int originalInt = original; // Save it off here
// all of your code to run the reverse...
// Code to run the check...
String revStr = String.valueOf(reverse);
String orgStr = String.valueOf(originalInt);
// In case you are inputting negative ints
orgStr = orgStr.replace("-", "");
revStr = revStr.replace("-", "");
// remove all trailing zeros from original and check if they are equal
// This is for the cases where the input is '900' and your reverse is '9'
orgStr = orgStr.replaceAll("0*$", "");
boolean worked = true;
// if the lengths are equal, then check if the chars match in opposite directions.
if (revStr.length() == orgStr.length())
{
int len = orgStr.length();
for (int i = 0; i < len; i++)
{
if (orgStr.charAt(i) != revStr.charAt(len - (i+1)))
{
worked = false;
break;
}
}
}
else
{
worked = false;
}
System.out.println("Worked: " + worked);
EDIT: First code had bug.
it can also be done as
int no=scanner.nextInt();
StringBuffer sb= new StringBuffer(no+"");
System.out.println(Integer.parseInt(new String(sb.reverse())));

Changing input so in can take any length of string, problems with output

Currently I have a method that asks user for an input string but only outputs the first 16 characters! The method is supposed to take in any length of string then output the characters in 4x4 blocks after it does the following: first row remains the same. Shift the second row one position to the left, then shifts the third row two positions to the left. Finally, shift the fourth row three positions to the left. As of now it will only output the first 4x4 block
Also I am not sure how I can change the method so it doesnt ask for user input
I would like it to use a given string like:
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
"WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO" is the given encrypted string I would like to use. but without asking for user input..I keep getting errors and incorrect outputs..please show how I might fix this
code I am using:
public class shiftRows {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] input= new String[4];
String[] output= new String[4];
System.out.println("Enter a String");
String inputStr = sc.next();
for (int i = 0, n = 0; i < 4; i++, n+=4) {
input[i] = inputStr.substring(0+n, 4+n);
}
// -
output[0] = input[0];
for(int i=1; i<4; i++)
{
output[i] = Shift(input[i],i);
}
for(int i=0; i<4; i++)
{
System.out.println(output[i]);
}
}
public static String Shift(String str, int shiftNum)
{
char[] out = new char[4];
if(shiftNum==1)
{
out[0]=str.charAt(1);
out[1]=str.charAt(2);
out[2]=str.charAt(3);
out[3]=str.charAt(0);
}
if(shiftNum==2)
{
out[0]=str.charAt(2);
out[1]=str.charAt(3);
out[2]=str.charAt(0);
out[3]=str.charAt(1);
}
if(shiftNum==3)
{
out[0]=str.charAt(3);
out[1]=str.charAt(0);
out[2]=str.charAt(1);
out[3]=str.charAt(2);
}
return new String(out);
}
}
Here's a good way to do it :
import java.util.Scanner;
public class shiftRows {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String inputStr = "WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO";
for (int i = 0 ; i < inputStr.length() ; i++){
System.out.print(inputStr.charAt(i));
if ((i + 1)%4 == 0) System.out.println();
}
}
}
If you want to stock it into a String, just concatenate at each loop and add a "\n" each time the if test is valid.

How to count length of words in a File? Java

I am trying to write a code which would count the number of words of a certain length in a file.
For example:
How are you?
would print:
Proportion of 3-letter words: 100% (3 words)
I want to count words of length 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13+
Can you please guide me?
I am NOT trying to find the number of words. I am already able to do with this code:
public static int WordCount() throws FileNotFoundException
{
File file = new File("sample.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count=0;
while(keyboard.hasNext())
{
keyboard.next();
count++;
}
return count;
}
I want to find words of a certain length.
UPDATE
I have written the following code:
public static int WordLengthCount() throws FileNotFoundException
{
File file = new File("hello.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count5 = 0;
int hell = 0; //This is just for the else command to compile
while(keyboard.hasNext())
{
if ( keyboard.next().length() == 5 )
{
count5++;
keyboard.next();
return count5;
}
} return hell;
}
You can use the length() method to count the number of characters in a string (word). From there on, it's just a matter of saving it somewhere. E.g., in Map:
public static Map<Integer, Integer> lengthCounts() throws FileNotFoundException
Map<Integer, Integer> countMap = new HashMap<>();
while(keyboard.hasNext())
{
String word = keyboard.next();
int length = word.length();
Integer currCount = countMap.get(length);
if (currCount == null) {
countMap.put (length, 1);
else {
countMap.put (length, currCount + 1);
}
}
return countMap;
}
Now you could check the number of words with any particular length, or even print all of them.
EDIT:
If the only thing you need is the percentage of words of a certain length, all you need are two counters - one for the words of that length, and one for all the words:
public static double lengthPercentage(int requiredLength) throws FileNotFoundException
int allWords = 0;
int requiredWords = 0;
while(keyboard.hasNext())
{
String word = keyboard.next();
int length = word.length();
if (length == requiredLength) {
++requiredWords;
}
++allWords;
}
// implicit assumption: there's at least on word in the file
return ((double) requiredWords) / allWords;
}
File file = new File("sample.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count=0;
while(keyboard.hasNext())
{
keyboard.next();
// Use a hash map
// Check the string length and add it to the hash map by checking it already exists. If already exists then get the actual value from hashmap and increment it by one and save it again to the map.
count++;
}
So that your final output will be of map with one letter string count, two letter string count etc..
The other answers are great, but if you are trying to find words of a specific length in a file and you don't like the answers above, then you could also try REGEX. You can test each word and then do what you want with it. If you are looking for a count of words in a file of each length, I think the answer above is better, but if you're looking to detect a word of a specific length you could use .length() or the regex below. Using a strings .lenght() function in my opinion is better, but I'm just giving you an alternative answer and example.
I'll put a small example below.
public class Words{
public static void main(String [] args){
String [] words = {"Pizzaaa", "Pizza", "Party"};
int fives = 0;
for( String s : words){
if(s.matches(".{5}")){
5++;
}
}
System.out.println(fives);
}
}
Or a better version:
public class Words{
public static void main(String [] args){
String [] words = {"Pizzaaa", "Pizza", "Party"};
int fives = 0;
for( String s : words){
if(s.length() == 5){
5++;
}
}
System.out.println(fives);
}
}
Edited Below: To demonstrate how it can be used in a file based loop
// other code needed
while(in.hasNext())
{
String s = in.next();
if(s.length() == 5)
fives++;
}
For example, I have text file named TextFile.txt at C:\ has content:
Ut porttitor libero sodales quam sagittis, id facilisis lectus semper.
and Java code:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
File file = new File("C:\\TextFile.txt");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
if (dis.available() != 0) {
// Get the line.
String s = dis.readLine();
// Put words to array.
String[] sParts = s.split(" ");
// Initialize word longest length.
int longestLength = 1;
for (String strx : sParts) { // Go through each sPart, the next one is called strx
// If the document has word longer than.
if (longestLength < strx.length())
// Set new value for longest length.
longestLength = strx.length();
}
// Because array index from "0".
int[] counts = new int[longestLength + 1];
for (String str : sParts) {
// Add one to the number of words that length has
counts[str.length()] += 1;
}
// We use this type of loop since we need the length.
for (int i = 1; i < counts.length; i++) {
System.out.println(i + " letter words: " + counts[i]);
}
}
}
}
// Result:
// 1 letter words: 0
// 2 letter words: 2
// 3 letter words: 0
// 4 letter words: 1
// 5 letter words: 0
// 6 letter words: 2
// 7 letter words: 2
// 8 letter words: 0
// 9 letter words: 3

Categories

Resources