I'm trying to count up the values stored in an array, here is my code:
public void printScores()
{
String sep = ":";
File inputfile = new File ("P:/SD/Assignment1/fbScores.txt");
String [] stringArr;
String line = "";
try {
Scanner filescan = new Scanner(inputfile);
while(filescan.hasNext())
{
line = filescan.nextLine();
stringArr = line.split(sep);
if(stringArr.length == 4)
{
System.out.println(stringArr[0]+"\t [" +stringArr[2]+"]\t|" + stringArr[1]+"\t["+ stringArr[3]+" ]\n");
}
else
{
throw new IllegalArgumentException("String " + line + " does not contain " + sep);
}
}
filescan.close();
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
public void totalGoals()
{
int count;
for (int i = 0; i<stringArr.length; i++)
{
//int num[i] = Integer.parseInt(stringArr);
}
}
}
Basically I only want to add the numbers up that are stored in [2] and [3], my totalGoals method at the bottom is where I started, but can't figure out how to change from a string to an integer, any help would be much appreciated!
UPDATE:
public void totalGoals()
{
int[] num = new int[stringArr.length];
int count = 0;
for (int i = 0; i<stringArr.length; i++)
{
num[i] = Integer.parseInt(stringArr[i]);
count = count + num[i];
System.out.println(count);
}
}
You want to parse each string individually - you seem to be trying to do the whole array
int[] num = new int[stringArr.length]; //don't forget to declare your num[] array
for (int i = 0; i<stringArr.length; i++)
{
num[i] = Integer.parseInt(stringArr[i]); // stringArr[i] instead of stringArr
}
Note what this code is actually doing when you break it out of the for loop format.
int[] num = new int[4];
num[0] = Integer.parseInt(stringArr[0]); //the for loop is starting at 0 and stopping
num[1] = Integer.parseInt(stringArr[1]); //when it hits 4
num[2] = Integer.parseInt(stringArr[2]);
num[3] = Integer.parseInt(stringArr[3]);
In truth, you only need 2 and 3.. and all you need to do is add them together. You already have a count variable you could use instead of num
So lets say you only want to loop through 2 and 3... look at the for loop
for (int i = 0; i < stringArr.length; i++)
int i = 0 //your loop is starting at 0
i < stringArr.length; //its ending when i is the array's length (should be 4 judging by your other code)
i++ // i increases by 1 at the end of each time through
So if 0 and 1 are useless, try using int i = 2
You have a count variable. Maybe it should start at 0.. and rather than setting the num variable, you could add the value to your count variable.
About your method.. By itself it should be working.
I'm also not sure which line is line 73
If it is the first line: int[] num = new int[stringArr.length]; Then either your stringArr doesn't exist (for this method) or your stringArr isn't initialized (again, for this method)
Looking at the code you've shown me, I'm guessing the problem is on that first line.
public void printScores() {
//other code
String[] stringArr;
//other code
}
public void totalGoals() {
int[] num = new int[stringArr.length];
int count = 0;
for (int i = 0; i<stringArr.length; i++)
{
num[i] = Integer.parseInt(stringArr[i]);
count = count + num[i];
System.out.println(count);
}
}
Done simply like this, you wouldn't even be able to compile. stringArr would not exist for totalGoals. The two methods are separate and cannot "see" each other's variables.
If you have your code like below - then you are declaring stringArr twice and you have two separate variables named the same thing!
{
String[] stringArr; //This is what totalGoals would be using - it is never assigned
public void printScores() {
String[] stringArr; //This one is used and assigned within printScores
//but totalGoals cannot see/use it
}
public void totalGoals() {
}
}
Use Integer.parseInt(String s) or Integer.parseInt(String s, int radix) to convert your Strings to Integers or primitive ints.
For instance:
try {
String s = "42";
int i = Integer.parseInt(s);
}
catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
You can also use Scanner.nextInt if that suits your context better.
Use integer.parseint to parse string to int
if(stringArr.length == 4)
{
for(int i=0;i<stringArr.length;i++)
{
int c = Integer.parseInt(stringArr[2])+ Integer.parseInt(stringArr[3]);
}
}
Related
I am reading multiple lines from the command line looking like this:
10 12
71293781758123 72784
1 12345677654321
Then I calculate stuff with the data of each line and output exactly the same amount of lines.
Unfortunately, I never get more than one line output in the end, namely the result of the last one.
The input function looks like that:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
String line = input.nextLine();
String[] lines = line.split(" ");
System.out.println(fct(lines[0], lines[1]));
}
input.close();
}
fct outputs a String.
Is there something weird happening I am not aware of?
Edit: I have added fct,since this could also be the problem:
public static String fct(String stringA, String stringB) {
int [] a = new int[stringA.length()];
int [] b = new int[stringB.length()];
for(int i=0; i< stringA.length(); i++) {
a[i] = stringA.charAt(i) - '0';
}
for(int i=0; i< stringB.length(); i++) {
b[i] = stringB.charAt(i) - '0';
}
if(a.length < b.length) {
int[] c = a.clone();
a = b.clone();
b = c.clone();
}
Stack<Integer> s = new Stack<Integer>();
int carry = 0;
int b_ind = b.length -1;
for(int i=a.length-1; i>=0; i--) {
if(b_ind >= 0) {
int diff = a[i] - b[b_ind] - carry;
if(diff < 0) {
carry = 1;
diff = 10 + diff;
} else {
carry = 0;
}
s.push(diff);
} else {
if(carry==0) {
s.push(a[i]);
} else {
s.push(a[i]-carry);
carry = 0;
}
}
b_ind -= 1;
}
String all = "";
while(!s.empty()) {
all = all + s.pop();
}
return all.replaceFirst("^0+(?!$)", "").trim();
}
The output would then be:
2
71293781685339
12345677654320
Being directly on the console on the line after the input finished.
Add one line break after last input line 1 12345677654321. Otherwise program won't read last line till you press enter(return) key.
If you want output on console like this:
10 12
71293781758123 72784
1 12345677654321
98
71293781685339
12345677654320
But you are getting this:
10 12
71293781758123 72784
1 1234567765432198
71293781685339
Notice, 98 is getting appended to last input line. And the second output is on the next line. You actually have two outputs.
And the third input has not been read by the program because third input line doesn't end in new line. If you press Enter key here the program will process the third input.
You need to make sure that there is a new line character after last input line before pasting entire input in to console.
Just a sidenote:
I would use java.math.BigInteger in this context (math with big integers).
import java.util.Scanner;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
try (var scanner = new Scanner(System.in)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] lines = line.split(" ");
System.out.println(fct(lines[0], lines[1]));
}
}
}
public static String fct(String numberA, String numberB) {
var a = new BigInteger(numberA);
var b = new BigInteger(numberB);
return a.subtract(b).abs().toString();
}
}
I have a scanner which reads in strings as coordinate inputs. I have to convert these strings into integers and store them in an Arraylist of coordinates but the last values I input are not being stored in the arraylist.
I have tried using the startEndLineScan.nextLine(); outside the for-loop but still no change I have also tried using a while loop instead of a for loop when storing and parsing the strings but I get the same results.
ArrayList<Integer> convertedCoords = new ArrayList<Integer>();
String samplePointsCoords[];
Scanner startEndLineScan = new Scanner(System.in);
int count = 1;
while (startEndLineScan.hasNextLine()) {
startEndPointsInputs = startEndLineScan.nextLine();
samplePointsCoords = startEndPointsInputs.split(",");
if (count < 2) {
for (int i = 0; i < samplePointsCoords.length; ++i) {
convertedCoords.add(Integer.parseInt(samplePointsCoords[i]));
}
count++;
} else {
break;
}
}
System.out.print("Points: " + convertedCoords)
Input:
1,2
3,4
Expected results:
Points: [1,2,3,4]
Actual Results
Points: [1,2]
ArrayList<Integer> convertedCoords = new ArrayList<Integer>();
String samplePointsCoords[];
Scanner startEndLineScan = new Scanner(System.in);
int count;
while (startEndLineScan.hasNextLine()) {
count = 1;
startEndPointsInputs = startEndLineScan.nextLine();
samplePointsCoords = startEndPointsInputs.split(",");
if (count < 2) {
for (int i = 0; i < samplePointsCoords.length; ++i) {
convertedCoords.add(Integer.parseInt(samplePointsCoords[i]));
}
count++;
} else {
break;
}
}
System.out.print("Points: " + convertedCoords)
Notice int count; is declared and reinitialized at the start of every loop
This will fix your code but you should really try to understand what you are writing! cheers.
So I made this to print primes between two numbers of my choice; however, it prints out a comma after the last number and I don't know how to take it off.
Example
in: 0 10
out: 2, 3, 5, 7,
I want 2,3,5,7
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
for (int i = a; i <= b; i++){
int j;
for (j = 2; j<i; j++){
int p = i%j;
if(p==0){break;}
}
if(i == j){System.out.printf("%d,", i);}
}
}
Use a boolean to keep track of whether you've printed anything yet. Then your format string could be something like
anythingPrinted ? ",%d" : "%d"
That is, only include the comma in the format string if there's something printed.
Use a StringBuilder and write to the console at the end of your program.
StringBuilder sb = new StringBuilder();
for (int i = a; i <= b; i++){
int j;
for (j = 2; j<i; j++){
int p = i%j;
if(p==0){break;}
}
if(i == j){
// If the length of the StringBuilder is 0, no need for a comma
if(sb.length() != 0) {
sb.append(",");
}
sb.append(i);
}
}
System.out.println(sb);
This might seem like overkill, and for many cases it might be, but I have been writing a source code transcoder and I find this situation coming up a lot. Where I need commas in between values, or a prefix value which is only printed once. So I found it handy to create a class which simplifies things.
Again, you wouldn't probably want to use this if you code had one or two print loops in it, but maybe if you had more than a few. Perhaps you would remove in "on first" part if you were never going to use it.
public class FirstPrintOptions {
private PrintStream printStream;
private String onFirst;
private String remaining;
private boolean trip = false;
public FirstPrintOptions(PrintStream printStream, String onFirst, String remaining) {
this.printStream = printStream;
this.onFirst = onFirst;
this.remaining = remaining;
}
public void print() {
if (!trip) {
if (onFirst != null) {
printStream.print(onFirst);
}
trip = true;
} else {
if (remaining != null) {
printStream.print(remaining);
}
}
}
}
Then use it like this..
FirstPrintOptions firstPrintOptions = new FirstPrintOptions(System.out, null, ",");
for (int x=0;x<10;x++) {
firstPrintOptions.print();
System.out.print(x);
}
The results are..
0,1,2,3,4,5,6,7,8,9
I was testing and I came up with this. I was using compilejava.net so scanner doesn't work. I bypassed that part and just set a and b manually. Basically, it builds a string with the numbers and ends in a comma. Then it prints a substring including everything except the last comma.
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
//Scanner s = new Scanner(System.in);
int a = 2;
int b = 18;
String c = "Output = ";
for (int i = a; i <= b; i++){
int j;
for (j = 2; j<i; j++){
int p = i%j;
if(p==0){break;}
}
if(i == j){c=c+ Integer.toString(i) + ",";}
}
System.out.print(c.subSequence(0, c.length()-1));
}
}
this program for finding factors of a number
for(i=1;i<=number;i++)
{
if(number%i==0)
{
system.out.print(i);
if(i!=0)
{system.out.print(",");}
}
}
so i get the output for 10 as
1,2,5,10
I'm attempting to write a program that would read a file "data.txt" which has an undefined amount of numbers in random order, separated by line. It would add these numbers into an array and print out the numbers in one line, each separated by a comma "x, x1". Then on the next line it would print out (in the same format) the list of numbers which has been sorted from smallest to largest size.
Data type is integer.
Currently, I have coded for 3 methods which would allow the array to be sorted (I think they have no error).
I've created another method to read the file and am using a two-step process - once to figure out the number of lines in the file (I ask that this two-step process remain). This method seems to have trouble returning the "lineCount" and apparently I need to make this variable an array (which I find bizarre). How can I fix this code?
You may notice that my method for printing is empty; I have not figured out a way to print the array so that each number is separated by a comma. How do I code for this?
My code so far:
import java.util.*;
import java.io.*;
public class SortAndSearch {
public static void main(String[] args) {
readFile2Array();
printArray();
selectionSort();
printArray();
}
public static void printArray(int[] a) {
}
public static void selectionSort(int[] a) {
int minI = 0;
for (int k = 0; k < a.length - 1; ++k) {
minI = findMinIdx(a, k); // findMinIdx at k-th
swapElement(a, k, minI);// swapElement at k-th
}
}
public static int findMinIdx(int[] a, int k) {
int minIdx = k;
for (int i = k + 1; i < a.length; ++i)
if (a[i] < a[minIdx])
minIdx = i;
return minIdx;
}
public static void swapElement(int[] a, int i, int j) {
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static int[] readFile2Array(String fileName) {
File dat = new File("data.txt");
int lineCount = 0;
int[] a = new int[lineCount];
int i;
try{ Scanner sc = new Scanner(dat);
while (sc.hasNextLine()){ //first read to count -> int lineCount;
lineCount++;
return lineCount; //I have trouble with this line
}
while (sc.hasNextLine()){ //second read to array -> hasNext(),
a[i] = sc.nextInt();
return a;
}
}
catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
e.printStackTrace();
}
}
public static int binarySearch(int[] arr, int val){
int minIdx, maxIdx, index = -1;
while(){ int middleIdx = (minIdx + maxIdx)/2;
if( arr[???] ==val){
index = middleIdx;
break } // update minIdx, maxIdx //if smaller then cut right, if larger then cut left
}
return index; }
}
The last method in the program would attempt to locate the element number of a user inputted number by using this (pseudo)code:
1. Let min = 0 and max = n-1 (where n is the array’s length)
2. If max < min, then stop: target is not present in array. return false.
3. Compute guess as the average of max and min, rounded down (so that it is an integer).
4. If array[guess] equals target, then stop. You found it! Return guess.
5. If the guess was too low, that is, array[guess] < target, then set min = guess + 1.
6. Otherwise, the guess was too high. Set max = guess - 1.
7. Go back to step 2.
How would I code for this?
I would really appreciate any help in any area of this program!
Managed to fix the first part of the code:
readFile2Array method:
public static int[] readFile2Array(String fileName) {
try {
int lineCount = 0;
Scanner sc = new Scanner(new File("data.txt"));
while (sc.hasNext()) { // first read to count -> int lineCount;
lineCount++; // second read to array -> hasNext(),
sc.nextLine();
}
sc.close();
sc = new Scanner(new File("data.txt"));
int[] x = new int[lineCount];
int n = 0;
while (sc.hasNext()) {
x[n] = Integer.parseInt(sc.nextLine());
n++;
}
sc.close();
return x;
} catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
e.printStackTrace();
}
return null;
}
Print array separated by comma:
public static void printArray(int[] a) {
try {
int lineCount = 0;
Scanner sc = new Scanner(new File("data.txt"));
while (sc.hasNext()) {
lineCount++;
sc.nextLine();
}
sc.close();
for (int i = 0; i < a.length; ++i) {
System.out.print(a[i]);
if (i < lineCount-1) System.out.print(", ");
}
} catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
}
System.out.println();
}
Last method is still a mystery to me though!
I agree with VGR that you haven't actually asked a question, but by reading your code I guess that you were describing what you wanted to achieve...
There are some flaws in your readFile2Array-method, which might solve the problem:
1)
int lineCount = 0;
int[] a = new int[lineCount]; //The size of a will always be 0, so you can't add anything to it, even though you are trying to do this later. Consider using a List instead, as the size of the list can increase dynamically.
2)
while (sc.hasNextLine()){ //first read to count -> int lineCount;
lineCount++;
return lineCount; //I have trouble with this line
}
//The problem is the return type: You method signature states that you will return int[], but here you are trying to return an int.
//It will also just increase lineCount once and try to return this.
3)
//Your scanning will be at the 2nd line because of 2) and not going through the entire file again. To do this you need to create a new instance of Scanner. And the int[] a has a size of 0 at this point.
while (sc.hasNextLine()){ //second read to array -> hasNext(),
a[i] = sc.nextInt();
return a;
}
So in order to solve this you should refactor your code to something like:
public static List<Integer> readFile2Array(String fileName) {
File dat = new File("data.txt");
List<Integer> a = new ArrayList<>();
try{ Scanner sc = new Scanner(dat);
while (sc.hasNextLine()){
a.add(sc.nextInt());
}
sc.close(); //Always remember to close, when done :)
System.out.println("Added " + a.size() + " lines to the list.");
return a;
} catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
e.printStackTrace();
return new ArrayList<>();
}
}
What I changed:
removed the lineCount as this is implicit stored in the size of the list called a.
Changed the int[] a to a List as this always will allow adding elements by increasing its size when needed.
Removed i as was never used, only initialized.
Removed the first while-loop as we don't need to know the amount of lines that is going to be added.
Added a return-statement in the catch-closure. We need to return something (even an empty array or maybe the not-yet-finished array)
I hope this helps. :)
I'm glad you got that part working. :)
To print out the array, it will be best to use whatever data you have of the array. By calling a.length, you don't have to count the number of lines from the input again, which you are not guaranteed are still the same if the input has changed in the mean time.
So this piece of code should do the trick:
public static void printArray(int[] a) {
for (int i = 0; i < a.length; ++i) {
System.out.print(a[i]);
if (i < a.length-1) System.out.print(", ");
}
System.out.println();
}
I need help sorting this array in alphabetical order using the bubble sort algorithm.
My code is:
public class Strings
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t=0; t<t1.length-1; t++)
{
for (int i = 0; i<t1.length -1; i++)
{
if(t1[i+1].compareTo(t1[1+1])>0)
{
tempStr = t1[i];
t1[i] = t1[i+1];
t1[i+1] = tempStr;
}
}
}
for(int i=0;i<t1.length;i++)
{
System.out.println(t1[i]);
}
}
}
The code compiles, but it does not sort alphabetical. Please help me.
You have three errors in your code.
The first error is in the inner for loop, in the place where you do the check statement, it should be i < t1.length - t -1 not i < t1.length -1. You subtract t because you do not want to loop through the whole array again, only the first part of it.
The second and third errors are in the if statement. You need to turn the greater than symbol into a lesser than symbol, because the way you have the compareTo method set up, it will return a negative number.
The other error in this line is that in the compareTo parameter you put 1 + 1 it actually should be just i, because you want one less than the object it is comparing to.
The fixed working code is below (Comments are what you originally had):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t = 0; t < t1.length - 1; t++) {
for (int i= 0; i < t1.length - t -1; i++) {
if(t1[i+1].compareTo(t1[i])<0) {
tempStr = t1[i];
t1[i] = t1[i + 1];
t1[i + 1] = tempStr;
}
}
}
for (int i = 0; i < t1.length; i++) {
System.out.println(t1[i]);
}
}
please change
String[] t1 = s1.split(", ");
to
String[] t1 = s1.split("");
This will solve the issue.