how to store strings in a while loop in java - 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);
...
}

Related

How do i store the chosen values after user input? The goal is to print out array2 as a receipt with all the chosen treatments when the user is done

String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
String[] array2 = new String [10]; // New array that saves up to 10 elements(treatments)
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
System.out.println("Control" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
int n = array.length;
for (int i=0; i<n; i++) {
for (int j=0; i<n ; j++) {
System.out.println();
treatment = input.nextInt();
if (treatment==1) {
cost += Integer.parseInt(array[i][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==2) {
cost += Integer.parseInt(array[i+1][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==3) {
cost += Integer.parseInt(array[i+2][1]);
System.out.print("Total cost so far: " + cost);
}
}
}
How do I move on from here? I figured that I have to store the input in the new array and exit the loop after 10 treatments or add an option to the user to print out the receipt when they're done.
The receipt needs to print all the chosen treatments along with the cost for each individual treatment. I will also need to add a variable to add a total amount for all the chosen treatments.
Here it is what you are trying to do, As the treatments are fixed so you can just index them as 0, 1, 2. One thing you can do is to make a hashmap in which you can store the treatment name and its cost (String,int) every time the user wants to enter.
Look at the code below
import java.util.*;
import java.util.HashMap;
public class treatment {
public static void main(String []args) {
String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
// New array that saves up to 10 elements(treatments)
HashMap<String, Integer> treat = new HashMap<String, Integer>();
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
int n = array.length;
int i =0;
char c = '\0';
do {
System.out.println("\n\nControl" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
System.out.println("Exit: " + "-1");
System.out.println();
System.out.print("Enter treatment value (1, 2, 3): ");
treatment = input.nextInt();
if (treatment==1){
i = 0;
cost += Integer.parseInt(array[0][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==2) {
i = 1;
cost += Integer.parseInt(array[1][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==3) {
i = 2;
cost += Integer.parseInt(array[2][1]);
System.out.println("\nTotal cost so far: " + cost);
}
treat.put(array[i][0], cost);
} while (treatment != -1);
System.out.println("Total COst is : " + cost);
System.out.println("The treatements you opt for are:\n");
System.out.println(treat);
System.out.println("\n");
}
}

how do I pass a user inputted integer through methods?

Essentially i've isolated the issue, the int numpersons begins as 0. I take a user input to make it a particular number which is the array size, when the second method begins it takes the 0 again and then the array has an out of bounds exception. I want to pass it from one method to the next, or make them more successive, idk how to do this
thanks in advance
import java.util.Scanner;
public class BankApp {
Scanner input = new Scanner(System.in);
int numpersons = 0;
private SavingsAccount[] clients = new SavingsAccount[numpersons];
public BankApp() {
while (numpersons < 1) {
System.out.println("How many people are there?");
numpersons = input.nextInt();
if (numpersons < 1 || 2147483647 < numpersons) {
System.out.println("invalid number, please enter again");
}
}
input.nextLine();
}
public void addClients() {
int i = 0;
while (i < numpersons) {
System.out.println("enter account id " + (i + 1));
String AccountID = input.nextLine();
System.out.println("enter account name " + (i + 1));
String AccountName = input.nextLine();
System.out.println("enter account balance " + (i + 1));
Double AccountBalance = input.nextDouble();
clients[i] = new SavingsAccount(AccountID, AccountName, AccountBalance);
input.nextLine();
i++;
}
}
public void displayClients() {
int i = 0;
while (i < numpersons) {
System.out.println("======================================");
System.out.println("Account ID " + (i + 1) + ": " + clients[i].getID());
System.out.println("Account Name " + (i + 1) + ": " + clients[i].getName());
System.out.println("Account Balance " + (i + 1) + ": " + clients[i].getBalance());
System.out.println("======================================");
i++;
}
}
public static void main(String args[]) {
BankApp ba = new BankApp();
ba.addClients();
ba.displayClients();
}
}

simple java multiplication game

I'm making a simple multiplication game, but when the user enters a correct answer, it still runs the else statement. I know it's a simple solution but I just can't figure it out. Can someone give me a hand?
public static void partB() {
System.out.println("Exercise 1B");
int count = 0;
String active = "true";
int correct = 0;
while (active == "true") {
Random r = new Random();
int Low = 10; //inclusive
int High = 21; //not inclusive
int Result = r.nextInt(High - Low) + Low;
Random r2 = new Random();
int Result2 = r2.nextInt(High - Low) + Low;
int Total = Result * Result2;
Scanner input = new Scanner(System.in);
System.out.println(Result + "*" + Result2 + "=?");
String guess = new String(input.nextLine());
String tostrng = String.valueOf(Total);
if (guess.equals (tostrng)) {
correct += 1;
count+=1;
System.out.println("Correct answer. Score: " + correct + "(" + count + ")");
}
if (guess.equals("q")) {
System.out.println("Good Bye!");
active = "false";
//return;
}
else {
count +=1;
System.out.println("Incorrect answer. Score:" + correct + "(" + count + ")");
}
}
}
Your else with wrong if
public static void partB() {
System.out.println("Exercise 1B");
int count = 0;
String active = "true";
int correct = 0;
while (active == "true") {
Random r = new Random();
int Low = 10; //inclusive
int High = 21; //not inclusive
int Result = r.nextInt(High - Low) + Low;
Random r2 = new Random();
int Result2 = r2.nextInt(High - Low) + Low;
int Total = Result * Result2;
Scanner input = new Scanner(System.in);
System.out.println(Result + "*" + Result2 + "=?");
String guess = new String(input.nextLine());
String tostrng = String.valueOf(Total);
if (guess.equals (tostrng)) {
correct += 1;
count+=1;
System.out.println("Correct answer. Score: " + correct + "(" + count + ")");
}
else {
count +=1;
System.out.println("Incorrect answer. Score:" + correct + "(" + count + ")");
}
if (guess.equals("q")) {
System.out.println("Good Bye!");
active = "false";
//return;
}
}
}
Make type of active variable as boolean i.e. boolean active=true;
and for comparing string values always use .equals() method.
Fixed it like this!
thanks for the help though guys.
if (guess.equals("q")) {
System.out.println("Good Bye!");
return;
}
if (guess.equals(tostrng)) {
correct += 1;
count += 1;
System.out.println("Correct answer. Score: " + correct + "(" + count + ")");
} else {
count += 1;
System.out.println("Incorrect answer. Score:" + correct + "(" + count + ")");
}

Extra + signs on my program

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;
}

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);
}

Categories