Extra + signs on my program - java

I wrote a program for my Computer Science class where it reads a file and imports the data and then just adds the numbers but it seems to be adding an extra addition sign.
import java.io.*; //necessary for File and IOException
import java.util.*; //necessary for Scanner
public class Tester
{
public static void main( String args[] ) throws IOException
{
Scanner sf = new Scanner(new File("/Volumes/DVLUP Flash/Numbers.txt"));
int maxIndx = -1; //-1 so when we increment below, the first index is 0
String text[] = new String[1000]; //To be safe, declare more than we
while(sf.hasNext( ))
{
maxIndx++;
text[maxIndx] = sf.nextLine( );
//System.out.println(text[maxIndx]); //Remove rem for testing
}
sf.close();
for(int j =0; j <= maxIndx; j++)
{
Scanner sc = new Scanner(text[j]);
}
String answer = ""; //We will accumulate the answer string here.
int sum; //accumulates sum of integers
for(int j = 0; j <= maxIndx; j++)
{
Scanner sc = new Scanner(text[j]);
sum = 0;
answer = "";
while(sc.hasNext())
{
int i = sc.nextInt();
answer = answer + i + " + ";
sum = sum + i;
}
//sc.next();
answer = answer + " = " + sum;
System.out.println(answer);
}
}
}
The output is
12 + 10 + 3 + 5 + = 30
18 + 1 + 5 + 92 + 6 + 8 + = 130
2 + 9 + 3 + 22 + 4 + 11 + 7 + = 58
There's an extra after the last number, how do I fix that?

After the last iteration you are having an "extra" plus sign because that´s the way you are printing it. You are ending the String with a + as it can be seen in your while loop.
to change it either add the + before the value as
if(sc.hasNext()) {
int i = sc.nextInt();
answer = i + "";
sum += i;
while(sc.hasNext())
{
i = sc.nextInt();
answer = answer + " + " + i;
sum = sum + i;
}
}
Or if you use Java 8 you could use the StringJoiner as
StringJoiner joiner = new StringJoiner(" + ");
while(sc.hasNext())
{
i = sc.nextInt();
// This automaticly includes a " + " between the values.
joiner.add(String.valueOf(i));
sum = sum + i;
}

After
while(sc.hasNext())
{
int i = sc.nextInt();
answer = answer + i + " + ";
sum = sum + i;
}
put
answer = answer.substring(0, answer.length()-1);

One option would be to conditionally prepend a plus sign before appending each number in any case other than the first number:
answer = "";
while(sc.hasNext()) {
int i = sc.nextInt();
if (answer.length() > 0) {
answer += " + ";
}
answer = answer + i;
sum = sum + i;
}

Related

how to store strings in a while loop in java

I am trying to store the data that's created in the while loop in the list variable so that I can use it later with the JOptionPane.INFORMATION_MESSAGE.
I tried using an array to store the data but it would not work.
Please let me know what I am missing.
package loops;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Statistics
{
public static void main(String[] args)
{
int observations = 1,
num = 0,
sum = 0,
max = Integer.MIN_VALUE,
min = Integer.MAX_VALUE;
double mean = 0.0;
String userEntry = "",
result,
list = " ",
seperator = "\n***********\nYou entered the following observations: ";
DecimalFormat twoDigits = new DecimalFormat ("0.00");
userEntry = JOptionPane.showInputDialog ("Enter observation # " + observations +
" (or \"end\" to quit) ");
//num = Integer.parseInt(userEntry);
String[] list2 = new String[num];
while(!userEntry.equalsIgnoreCase("end"))
{
num = Integer.parseInt(userEntry);
observations ++;
userEntry = JOptionPane.showInputDialog ("Enter observation #" + observations +
" (or \"end\" to quit) ");
//num = Integer.parseInt(userEntry);
//num = Integer.parseInt(userEntry);
//list = "\n" + num;
//list = list.toString();
sum += num;
if(num > max)
{
max = num;
}
if(num < min)
{
min = num;
}
//Integer.toString(num);
//ArrayList<String> list = new ArrayList<String>();
//list.add(num);
//list = "\n" + Integer.toString(num);
//String[] list2 = new String[num];
//for(String list1 : list2)
//{
list = "\n" + num;
//}
}
observations --;
mean = sum / (double)observations;
//twoDigits.format(mean);
if(observations == 0)
{
result = "no observations selected";
}
else
{
result = "You entered " + observations +
(observations == 1 ? " observation" : " observations");
result = result + "\nThe minimum is " + min;
result = result + "\nThe maximum is " + max;
result = result + "\nThe sum is " + sum;
result = result + "\nThe mean is " + twoDigits.format(mean);
result = result + seperator;
result = result + list;
}
JOptionPane.showMessageDialog(null, result,
"Results", JOptionPane.INFORMATION_MESSAGE);
//observations --;
System.exit(0);
}
}
Try using ArrayList instead of []. Example based on your code is shown below.
package loops;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Statistics {
public static void main(String[] args) {
// method local variables
int observations = 0;
int num = 0;
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
double mean = 0.0;
String userEntry = "";
String result;
String list = " ";
String seperator = "\n***********\nYou entered the following observations: ";
DecimalFormat twoDigits = new DecimalFormat("0.00");
ArrayList<Integer> intList = new ArrayList<Integer>();
// get user entry from JOptionPane
userEntry = JOptionPane.showInputDialog("Enter observation # " + observations + " (or \"end\" to quit) ");
// iterate until user enters end
while (userEntry.equalsIgnoreCase("end") == false) {
observations++;
num = Integer.parseInt(userEntry);
userEntry = JOptionPane.showInputDialog("Enter observation #" + observations + " (or \"end\" to quit) ");
sum = sum + num;
// change number to max if > max
if (num > max) {
max = num;
}
// change number to min if < min
if (num < min) {
min = num;
}
// add the number to the string and to the list
list = list + "\n" + num;
intList.add(num);
}
echoList(intList);
mean = sum / (double) observations;
if (observations == 0) {
result = "no observations selected";
}
else {
result = "You entered " + observations + (observations == 1 ? " observation" : " observations");
result = result + "\nThe minimum is " + min;
result = result + "\nThe maximum is " + max;
result = result + "\nThe sum is " + sum;
result = result + "\nThe mean is " + twoDigits.format(mean);
result = result + seperator;
result = result + list;
}
// show results and exit
JOptionPane.showMessageDialog(null, result, "Results", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
private static void echoList(ArrayList<Integer> intList) {
System.out.println("------------------------------");
System.out.println("Got " + intList.size() + " integers.");
for(Integer i : intList) {
System.out.println("\t" + i);
}
System.out.println("------------------------------");
}
}
JOptionPane.showInputDialog() will return the string the user has entered if the user hits ok, and returns null otherwise.
Therefore, if the user hits cancel, your while condition (userEntry.equalsIgnoreCase("end") == false) will throw a NullPointerException.
Therefore, it's safer to change the while condition to (userEntry != null).
Now, if you want to store all the user entries, use a list of integers, say List<Integer> userEntries
List<Integer> userEntries = new ArrayList<>();
while (userEntry.equalsIgnoreCase("end") == false)
{
observations++;
num = Integer.parseInt(userEntry);
userEntries.add(num);
...
}

Problems with while() loop [duplicate]

This question already has answers here:
Comparing two integer arrays in Java
(10 answers)
Closed 7 years ago.
The statement before the begining of while loop System.out.println("Value of i before loop = " + i); is not being printed and the value of i in the loop is not being printed starting from 1. Instead it starts printing from a random big int.
package main;
import java.util.Random;
public class Main {
public static void main(String args[]){
Random ran = new Random();
int[] in = {2,5,9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while(!(c_gen.equals(in))){
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for(int x : in)
System.out.print(x + " ");
System.out.print("\n" + "c_gen = ");
for(int x : c_gen)
System.out.print(x + " ");
System.out.println("\n" + "i = " + i);
}
}
You are directly comparing arrays resulting in an infinite loop. Those results are being printed but are going to be at the top of tons and tons of output. Fix your comparison.
Sotirios' intuition is correct - your bug is in the line while(!(c_gen.equals(in))). You can't compare arrays for equality using the .equals(...) method because "arrays inherit their equals-method from Object, [thus] an identity comparison will be performed for the inner arrays, which will fail, since a and b do not refer to the same arrays." (source). Thus because c_gen and in will always refer to different arrays (even if their contents are the same), your loop will go forever.
Try Arrays.equals(..) instead:
public static void main(String[] args) {
Random ran = new Random();
int[] in = {2,5,9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while(!Arrays.equals(in, c_gen)){
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for(int x : in)
System.out.print(x + " ");
System.out.print("\n" + "c_gen = ");
for(int x : c_gen)
System.out.print(x + " ");
System.out.println("\n" + "i = " + i);
}
This works (terminates in finite time) for me, with sample output:
Value of i before loop = 0
1 9 9 ..................1
5 4 1 ..................2
1 1 6 ..................3
1 3 6 ..................4
.... //Omitted because of space
6 5 8 ..................1028
2 5 9 ..................1029
in = 2 5 9
c_gen = 2 5 9
i = 1029
I get:
Value of i before loop = 0
2 2 1 ..................1
2 2 4 ..................2
...
Suggest you rebuild the project and try again.
As originally posted your code will not terminate because int[].equals(int[]) will not do what you expect.
You could try this though.
private static boolean equals(int[] a, int[] b) {
if (a == null && b == null) {
// Both null
return true;
}
if (a == null || b == null) {
// One null
return false;
}
if (a.length != b.length) {
// Differ in length.
return false;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
// Mismatch
return false;
}
}
// Same.
return true;
}
public void test() {
Random ran = new Random();
int[] in = {2, 5, 9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while (!equals(c_gen, in)) {
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for (int x : in) {
System.out.print(x + " ");
}
System.out.print("\n" + "c_gen = ");
for (int x : c_gen) {
System.out.print(x + " ");
}
System.out.println("\n" + "i = " + i);
}

NullPointer Exception Jcreator, Java

I am having an incredibly difficult time trying to figure out why I am getting this error.
When I use a driver file to test the program it fails horribly.
Here's my code:
import java.util.Scanner;
import java.lang.Math.*;
public class Histogram
{
private int[] arrayData;
private int[] arrayRange;
private final int LOW = 1;
private final int HIGH = 100;
public Histogram()
{
int[] arrayData = new int[11];
}
public void getInput()
{
int[] arrayRange = new int[11];
for(int count = 1; count < arrayRange.length; count++)
{
arrayRange[count] = count * 10;
}
Scanner input = new Scanner(System.in);
System.out.println("Enter numbers from 1 to 100, Type -999 to quit.");
int nextNumb = input.nextInt();
while(nextNumb != -999)
{
if(nextNumb >= LOW && nextNumb <= HIGH)
{
for(int i = 0; i <= arrayRange.length; i++)
{
if(nextNumb > arrayRange[i] && nextNumb <= arrayRange[i+1])
arrayData[i]++;
}
nextNumb = input.nextInt();
}
else arrayData[10]++;
nextNumb = input.nextInt();
}
}
public String starPrint(double count)
{
String star = "";
count = (Math.round(count) / 5);
for(int i = 1; i <= count; i++)
{
star = star + "*";
}
return star;
}
public String toString()
{
String results = " Range | Histogram" + "\n";
results = results + "1 - 10 | " + starPrint(arrayData[0]) + "\n";
results = results + "11 - 20 | " + starPrint(arrayData[1]) + "\n";
results = results + "21 - 30 | " + starPrint(arrayData[2]) + "\n";
results = results + "31 - 40 | " + starPrint(arrayData[3]) + "\n";
results = results + "41 - 50 | " + starPrint(arrayData[4]) + "\n";
results = results + "51 - 60 | " + starPrint(arrayData[5]) + "\n";
results = results + "61 - 70 | " + starPrint(arrayData[6]) + "\n";
results = results + "71 - 80 | " + starPrint(arrayData[7]) + "\n";
results = results + "81 - 90 | " + starPrint(arrayData[8]) + "\n";
results = results + "91 - 100 | " + starPrint(arrayData[9]) + "\n";
results = results + "Outliers: " + starPrint(arrayData[10]) + "\n";
return results;
}
}
I believe that the problem is in my getInput method
right here to be precise:
if(nextNumb > arrayRange[i] && nextNumb <= arrayRange[i+1])
arrayData[i]++;
I have no idea what's wrong with it though I am a beginner programmer and couldn't find a solution to this particular problem.
Thanks for any help you're able to give!
public Histogram()
{
int[] arrayData = new int[11];
}
You're shadowing your arrayData field in the constructor. This is creating a local variable with the same name as your class's arrayData field, initializing it, then immediately discarding it. When you try to use the field later in your code, it's null. Get rid of the int[] part.
Note that your next exception will be an ArrayIndexOutOfBoundsException ... you should look at your loop ;)
this: for(int i = 0; i <= arrayRange.length; i++)
wont work since you are trying to access arrayRange[i] and arrayRange[i+1]
which dont exists for i = arrayRange.length-1 and further
so change it to:
for(int i = 0; i < arrayRange.length-1; i++)

I'm trying to use 2 user inputs to populate a 2d list array

I'm trying to populate a 2d list array using 2 user inputs.
Problem I'm having is that in the code below, the 1st for statement isn't producing the outcome I'm expecting, the 2nd for is doing what is needed. Also, with the code below I'm unable to close scanner.
public static void main(String[] args) {
ArrayList<String> listCon = new ArrayList<String>();
ArrayList<String> listCol = new ArrayList<String>();
Scanner txtInput = new Scanner(System.in);
char addTo = 'y';
do {
System.out.println("\nCurrent list is " + listCon + listCol + "\n");
System.out.println("Would you like to add a country to the list?\n\t"
+ "( y ) = YES\n\t( n ) = NO");
addTo = txtInput.next().toLowerCase().charAt(0);
if (addTo == 'y') {
System.out.println("Enter country name: ");
listCon.add(txtInput.next().toLowerCase());
System.out.println("Enter colour: ");
listCol.add(txtInput.next().toLowerCase());
} else if (addTo == 'n') {
int i = 1;
int countCon = listCon.size();
if(countCon == 0) {
System.out.println("No countries have been entered.");
} else {
String str = "country";
if(countCon > 1) {
str = "countries";
}
System.out.println("Thankyou for your input. We found " + countCon + " " +
str + " in the list.");
System.out.println("Listed " + str + ":\n");
for(String n : listCon) {
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
for(String b : listCol) {
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
i = i + 1;
}
break;
}
break;
}
} else {
System.out.println("Incorrect input detected. please try again. \n");
}
} while (true);
}
}
You need to remove extra break from the first for loop to iterate. Otherwise, you break after first iteration.
for(String n : listCon) {
....
for(String b : listCol) {
...
}
break; //remove this!
}
break;
EDIT
The result im after is Country 1 : France - Blue Country 2 : UK -
White Country 3 : Ireland - Green
You need to iterate like this:
for (int i = 0; i < listCon.size() && i < listCol.size(); i++) {
String n = listCon.get(i);
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
String b = listCol.get(i);
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
}

NoSuchElementException reading/ scanning input

Here is the main problem:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at ExamAnalysis.main(ExamAnalysis.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
The program compiles and runs. It's just that I am either getting the java.util.NoSuchElementException along with my five jother errors with (answer.charAt(i) == char) near the bottom. Here is my program:
import java.io.*;
import java.util.Scanner;
class ExamAnalysis
{
public static void main(String [] args) throws FileNotFoundException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type the correct answers to the exam questions, one right after the other: ");
String answers = keyboard.nextLine();
System.out.println("Where is the file with all the student responses? ");
String responses = keyboard.nextLine();
Scanner read = new Scanner(new File(responses));
while (read.hasNextLine())
{
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
int p = 1;
p += i;
System.out.println("Student " + p + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on 9 students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
}
}
public static void resultsByStudents(String responses, String answers)
{
System.out.println ("Student # Correct Incorrect Blank");
System.out.println ("~~~~~~~~~ ~~~~~~~ ~~~~~~~~~ ~~~~~");
int student = 0;
int correct = 0;
int incorrect = 0;
int blank = 0;
for (int i = 0; i <= 9; i++)
{
for (int j = 0; j <= responses.length(); j++)
{
if ((responses.charAt(j)) == answers.charAt(j))
correct++;
else if ((responses.charAt(j)) != answers.charAt(j))
incorrect++;
else
blank++;
}
System.out.println(student + " " + correct + " " + incorrect + " " + blank);
student++;
}
}
public static void analysis(String responses)
{
System.out.println("QUESTION ANALYSIS (* marks the correct response)");
System.out.println("~~~~~~~~~~~~~~~~~");
//stores the percentage of each choice chosen
double A = 0;
double B = 0;
double C = 0;
double D = 0;
double E = 0;
double X = 0;
// tallys every variable chosen per question
for (int i = 0; i <= 10; i++) // go through all the questions
{
for (int j = 0; j <= responses.charAt(i); j++) //go through all the student responses
{
// variable that are being tallied
int chooseA = 0;
int chooseB = 0;
int chooseC = 0;
int chooseD = 0;
int chooseE = 0;
int chooseBlank = 0;
//variables take percentage of choices that have been chosen from each student
A = chooseA/9;
B = chooseB/9;
C = chooseC/9;
D = chooseD/9;
E = chooseE/9;
X = chooseBlank/9;
// variables that will print the asterisk with certain character of correct answer
String a = "A";
String b = "B";
String c = "C";
String d = "D";
String e = "E";
String blank = "blank";
if (responses.charAt(j) == A)
chooseA++;
else if (responses.charAt(j) == B)
chooseB++;
else if (responses.charAt(j) == C)
chooseC++;
else if (responses.charAt(j) == D)
chooseD++;
else if (responses.charAt(j) == E)
chooseE++;
else
chooseBlank++;
System.out.println("Question #" + i);
if (answers.charAt(i) == 'A') a = "A*"; // answers cannot be resolved(I already made it a global variable in my main method.)
else if (answers.charAt(i) == 'B') b = "B*";// answers cannot be resolved
else if (answers.charAt(i) == 'C') c = "C*";// answers cannot be resolved
else if (answers.charAt(i) == 'D') d = "D*";// answers cannot be resolved
else if (answers.charAt(i) == 'E') e = "E*";// answers cannot be resolved
System.out.println(a + " " + b + " " + c + " " + d + " " + e + " " + blank);
System.out.println (chooseA + " " + chooseB + " " + chooseC + " " + chooseD + " " + chooseE + " " + chooseBlank );
System.out.println (A + " " + B + " " + C + " " + D + " " + E + " " + X);
}
}
}
}
while (read.hasNextLine())
{
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
int p = 1;
p += i;
System.out.println("Student " + p + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on 9 students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
}
}
Your logic here is confusing you. read.nextLine(); "Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line."
So you are saying, does it have a line? If so, read the next 10...well...11 lines, which isn't what you want. You don't know if there are 11 lines past this point. Don't know what that text file looks like, but you will want to restructure this part to either say, "While it has a next line", or "Read 11 lines"
Remove the for loop may resolve the issue. You are checking only once by using while(hasNextLine() ) but calling read.nextLine() 10 times in for loop.
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
.......
}
int i = 0;
int numberOfStudents = 9;
while (i < numberOfStudents && read.hasNextLine()){
responses = read.nextLine();
i++;
System.out.println("Student " + i + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on "+ numberOfStudents +" students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
i < numberOfStudents : makes the required number of inserts
read.hasNextLine() : checks if there is input from console. If not the program waits for input.
for (int i = 0; i <= 10; i++)
count from 0 -> 10 = 11 students

Categories