Paragraph character count - java

I have a txt file where there are multiple paragraphs and they are delimited by a "%". I'm trying to find the maximum characters for every line in every separate paragraphs in order to make a padding. My problem is that it finds the maximum number of character overall, instead of finding the max in every paragraph/
int nmar = 0;
int max = 0;
while (input.hasNextLine()) {
input.useDelimiter("%");
String nume = input.next();
lines = linii;
Scanner scan = new Scanner(nume);
while (scan.hasNextLine()) {
String linecount = scan.nextLine();
nmar = linecount.length();
if (nmar > max) {
max = nmar;
} else if (nmar == 0) {
break;
}
System.out.println(max);
}
}

I moved the nmar and max inside the while to reset them at every paragraph, seems to work.
int nmar, max;
while (input.hasNextLine()) {
nmar = 0;
max = 0;
input.useDelimiter("%");
String nume = input.next();
Scanner scan = new Scanner(nume);
while (scan.hasNextLine()) {
String linecount = scan.nextLine();
nmar = linecount.length();
if (nmar > max) {
max = nmar;
} else if (nmar == 0) {
break;
}
}
System.out.println(max);
}
With this input
dkdjdhd\ndpepe%nd\njkfdlfrkefjrekl%dffd
I get
7
15
4

Related

Issue reading integers from file using Scanner

I am having an issue reading integers from an input file using scanner. Here is the bit of code I am having trouble with:
String path = sc.nextLine();
File filename = new File(path);
Scanner reader = null;
reader = new Scanner(filename);
for(int i = 0; i < 4; i++)
{
while(reader.hasNextInt())
{
System.out.println(reader.nextLine());
pid[i] = reader.nextInt();
arrivaltime[i] = reader.nextInt();
burstTime[i] = reader.nextInt();
}
}
The input file I am using contains this information:
1 1 1
2 2 2
3 3 3
4 4 4
Using this file, I am trying to make it so that pid[] = [1,2,3,4], arrivaltime[] = [1,2,3,4] and bursttime[] = [1,2,3,4]. However, each of these arrays are instead being shown as [4,0,0,0] and I can't figure out why for the life of me. Any help would be appreciated.
Try this:
Read the line first
Then split it!
int i = 0
while(reader.hasNextLine()){
String[] line = reader.nextLine().split(" ");
pid[i] = Integer.parseInt(line[0]);
arrivaltime[i] = Integer.parseInt(line[1]);
burstTime[i] = Integer.parseInt(line[2]);
i++;
}
When you use scanner.nextLine() the scanner pointer in the file skips first line.
You can use this if you don't want to print each line or use the other solution with splitting.
int i = 0;
while(reader.hasNextInt()) {
pid[i] = reader.nextInt();
arrivaltime[i] = reader.nextInt();
burstTime[i] = reader.nextInt();
i++;
}
Try This:
for(int i = 0; i < 4; i++)
{
if (reader.hasNextInt()) {
pid[i] = reader.nextInt();
arrivaltime[i] = reader.nextInt();
burstTime[i] = reader.nextInt();
}
}

Problem with this error : Exception in thread "main" java.lang.NumberFormatException: For input string: ""

This is the problem wherein, we will subtract two numbers using 9's complement.
import java.io.*;
public class NinesComplement {
public static void main(String[] args)throws java.io.IOException {
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
while (true) {
System.out.print("Enter Minuend: ");
int min = Integer.parseInt(br.readLine());
System.out.print("Enter Subtrahend: ");
String sub = br.readLine();
int max = Integer.toString(min).length();
for (int i = 0; sub.length() < max; i++) {
sub = 0 + sub;
}
String [] subArr = sub.split("");
int[] num = new int[subArr.length];
for (int i = 0; i < subArr.length; i++) {
num[i] = Integer.parseInt(subArr[i]);
}
int[] n = new int[num.length];
for (int i = 0; i < num.length; i++) {
for (int ii = 0; num[i] < 9; ii++) {
num[i]++;
n[i]++;
}
}
String str = "";
for (int i = 0; i < num.length; i++) {
str += Integer.parseInt(Integer.toString(n[i]));
}
int add = Integer.parseInt(str);
String ans = Integer.toString(min + add);
if (ans.length() > max) {
String temp1 = ans.substring(0, 1);
String temp2 = ans.substring(1, ans.length());
int fin = Integer.parseInt(temp2) + Integer.parseInt(temp1);
System.out.println("Answer: " + fin);
} else if (ans.startsWith("9") && ans.endsWith("9")) {
System.out.println("Answer: 0");
}
System.out.print("Do you want to try again? \n[y][n]: ");
String choice = br.readLine();
if (choice.equals("n")) {
System.out.println("Thank you!!!");
System.exit(0);
}
}
}
}
Exception in thread "main" java.lang.NumberFormatException: For input
string: ""
You're just trying to parse an empty string into a number. You should always validate user input before trying to use it :).
Add a pre-condition (just an if statement check) before using the input and print a nice message to the user if the input was bad, and just go back to waiting for more good input.
Also, to debug this issue, just make your life easier and add some print statements surrounded by quotes before you try and use the user input so you can see it.

How is my String Index Out of Bounds?

GOAL: To ask user for # of points. Then user will input "1 4", where 1 is the x and 4 is the y. I will take the sub-string to get 1 and 4 separately then make them an int so I can make them a Point.
I keep getting "java.lang.StringIndexOutOfBoundsException: String index out of range: -1"
this is taking place on line 25, but not 24. When I use 3 instead of the length it also gives me this error.
This is a fragment of code:
public String run() {
String line = "";
String first = "";
String second = "";
int j = 0; int n = 0;
System.out.println("How many inputs do you want to enter?");
Scanner sc = new Scanner(System.in);
while(j == 0){
if(sc.hasNextInt()){
n = sc.nextInt();
Point[] points = new Point[n];
sc.close();
j++;
}
else {
System.out.println("invalid input");
}
}
Scanner scan = new Scanner(System.in);
for(int i = 0; i <= n; i++){
System.out.println("Enter x and y:");
line = scan.next();
first = line.substring(0,1);
second = line.substring(2,line.length());
}
scan.close();
origin(points);
return "";
}
See if this works for you. I'm not sure what your j variable was doing, your for-loop for the points was going out of bounds on the array, you are closing System.in between two separate Scanners, and obviously something wrong is happening with your substring logic.
This code fixes all those problems and runs great for me.
public String run() {
Scanner sc = new Scanner(System.in);
int n = numberPrompt("How many inputs do you want to enter?\n", "Invalid input");
Point[] points = new Point[n];
for(int i = 0; i < n; i++){
System.out.println("Enter x and y:");
String line = sc.nextLine();
String[] data = line.split("\\s+");
if (data.length >= 2)
{
int x = Integer.parseInt(data[0]);
int y = Integer.parseInt(data[1]);
points[i] = new Point(x, y);
}
}
System.out.println(Arrays.asList(points));
origin(points);
return "";
}
private int numberPrompt(String prompt, String error) {
Integer number = null;
boolean isValid;
String input;
Scanner sc = new Scanner(System.in);
do {
isValid = true; // reset the validity
System.out.print(prompt);
input = sc.nextLine();
try {
number = Integer.parseInt(input);
} catch (NumberFormatException e) {
isValid = false;
if (!(error == null || error.isEmpty())) {
System.out.println(error);
}
}
} while (!isValid);
return number;
}

Why won't my program continue on once I enter as the itemName?

I can't figure out why my program won't continue past the while loop once I enter the string "end" as one of the items. I tried putting println statements after the while loop and they didn't print after I typed "end". I also tried putting a print statement at the end of the while loop and it did not print once I typed "end", so it isn't running the while loop after I type "end", but it also isn't running anything after it. Any ideas? Here's the code:
package a1;
import java.util.Scanner;
public class A1Adept {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
process(s);
}
public static void process(Scanner s) {
int[] numbers = new int[10];
double[] cost = new double[10];
String itemName = "";
int categoryNumb;
int quantities;
double costs;
System.out.println("Please enter the names of the items, their category, their quantity, and their cost.");
while(!itemName.equals("end")){
itemName = s.next();
categoryNumb = s.nextInt();
quantities = s.nextInt();
costs = s.nextDouble();
numbers[categoryNumb] += quantities;
cost[categoryNumb] += (costs*quantities);
}
System.out.println("win");
int qMax = 0;
int qMin = 0;
int cLarge = 0;
int cLeast = 0;
int max = 0;
int min = 100;
double large = 0;
double least = 100;
for (int i = 0; i < 10; i++){
if (numbers[i] >= max)
{
max = numbers[i];
qMax = i;
}
if (numbers[i] <= min){
min = numbers[i];
qMin = i;
}
if (cost[i] >= large){
large = cost[i];
cLarge = i;
}
if (cost[i] <= least){
least = cost[i];
cLeast = i;
}
}
System.out.println("Category with the most items:"+qMax);
System.out.println("Category with the least items:"+qMin);
System.out.println("Category with the largest cost:"+cLarge);
System.out.println("Category with the least cost:"+cLeast);
}
}
It will stop if you write "end" followed by an int, another int and a double.
This is because you are first checking for "end", then asking for the 4 inputs.
The while(condition) is evaluated at the beginning of every loop.
So your program goes like this :
Check if itemName equals "end"
Ask itemName
Ask categoryNumb
Ask quantities
Ask costs
Do your stuff
Go back to 1
If you want to exit as soon as the user types "end" change it to :
while (true) { // Creates an "endless" loop, will we exit from it later
itemName = s.next();
if (itemName.equals("end")) break; // If the user typed "end" exit the loop
// Go on with the rest of the loop

storing an integer array into a list integer array and accessing those variables in order

okay so i have this code and i would like to store the values of an array of integers intwholef[x] and store those values in the array wholelist[y]. the only problem is that the way i have it set up is that im taking the first three values of the array and storing them in intwholef[x] and then x is resetting as it passes on the the next line. a graphical representation is below
This is the contents of the file stored in an array of strings
intwholef[0] = 1 3 10
intwholef[1] = 2 4 15
intwholef[2] = 3 6 8
intwholef[3] = 4 7 3
intwholef[4] = 5 9 12
now what i WANT is those values to be stored like this.
wholelist[] = 1,3,10,2,4,15,3,6,8,4,7,3,5,9,12
and be accessible like
wholelist[2] * wholelist[5] = 150;
the problem that im running into is that im not able to save the values in a list like this, any ideas?
here is the whole code, the part im talking about is at the bottom
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class project1
{
#SuppressWarnings("null")
public static void main(String[] args)
{
System.out.println("These are your following choices: ");
System.out.println("1. First-Come First-Served (FCFS): ");
System.out.println("2. Shortest Job Next (SJN): ");
System.out.println("3. Shortest Remaining Time (SRT): ");
System.out.println("4. Round Robin (RR) with time quantum = 4 ms: ");
System.out.println("please enter your choice by entering 1, 2, 3, 4");
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
if(choice ==1)
{
System.out.println("your choice was first come first serve");
}
else if(choice == 2)
{
System.out.println("your choice was shortest job next");
}
else if(choice == 3)
{
System.out.println("your choice was shortest job remaining");
}
else if(choice == 4)
{
System.out.println("your choice was round robin (rr) with time quantum = 4 ms");
}
else
{
System.out.println("you entered an invalid choice");
}
BufferedReader file = null;
System.out.println("Please enter the file path for your input");
Scanner fp = new Scanner(System.in);
String input = fp.nextLine();
String fileloc;
String[] wholef = null;
int fline = 0;
try
{
file = new BufferedReader(new FileReader(input));
fileloc = file.readLine();
fline = Integer.parseInt(fileloc); // this stands for file contents from the file to be read
wholef = new String[fline];
int i = 0;
while((fileloc = file.readLine()) != null)
{
wholef[i] = fileloc;
System.out.print("the contents of this file are: ");
System.out.println(fileloc);
i++;
}
System.out.println("This is the contents of the file stored in an array of strings");
for(int n = 0; n < fline; n++)
{
System.out.println(wholef[n]);
}
} catch (IOException er)
{
er.printStackTrace();
}
finally
{
try
{
if(file != null)
{
file.close();
}
} catch(IOException erx)
{
erx.printStackTrace();
}
}
System.out.println("This is the size of the contents of the file");
for(int n = 0; n < fline; n++)
{
System.out.println(wholef[n].length());
}
System.out.println("this is the input file converted and stored into an array of integers");
String[] parts = null;
int[] intwholef = null;
int[] wholelist =null;
for(int x = 0; x < fline; x++)
{
parts = wholef[x].split(" ");
intwholef= new int[parts.length];
for(int n = 0; n < parts.length; n++)
{
intwholef[n] = Integer.parseInt(parts[n]);
System.out.println(/*"intwholef[" + n + "] = " + */intwholef[n]);
for(int m = 0; m < parts.length; m++)
{
//wholelist[m]= intwholef[n];
}
}
}
System.out.println("this is the list of number from the conversion dumped into a singular array list");
for(int i = 0; i < 15; i++)
{
System.out.println("intwholef[" + i + "] = " + wholelist[i]);
}
/*
System.out.println("operations done with array of ints");
for(int i = 0; i < 20; i++)
{
System.out.println(intwholef[i]);
}
//System.out.println(intwholef[0] * intwholef[3]);
*/
}
}
I suggest you use a List (like ArrayList) instead of an array as the size of it can change. As such:
ArrayList wholeList = new ArrayList<Integer>();
for(int x = 0; x < fline; x++)
{
parts = wholef[x].split(" ");
for(int n = 0; n < parts.length; n++)
{
wholeList.add(Integer.parseInt(parts[n]));
}
}
Then you can access the different values with wholeList.get(index).
You can do it simply using an ArrayList. If you want to end up with an Array, use the toString method. Split the string with \\s, so that any whitespace can serve as delimiter. Also, you only need only loop, like this:
int[] myArray = new int[10];
List<Integer> list = new ArrayList<Integer>();
while ((fileloc = file.readLine()) != null) {
for (String s : fileloc.split("\\s+")) {
list.add(Integer.parseInt(s));
}
System.out.println(Arrays.toString(myArray));
}
int[] wholelist = list.toArray();

Categories

Resources