I am having trouble with the logic I think. My results are not adding up correctly. Can someone please help? The problem is in the arrayList.size, nums.length or something. I entered 50 40 60 as my integers.
public class Application {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (input.hasNextInt()) {
list.add(input.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
System.out.printf("%s", "You entered: ");
for (int i = 0; i < nums.length; i++) {
System.out.printf("%d%s", nums[i], ", ");
}
Collections.sort(list);
int b = Collections.max(list);
int c = Collections.min(list);
int arraySize = nums.length-1;
double sum = 0;
for(int i = 0; i < list.size(); i++)
{
sum += list.get(i);
}
System.out.println(" \nLast Number is : " + list.get(arraySize)
+ "\nLargest Number is: " + b
+ "\nSmallest number is :" + c
+ "\n" + "You entered " + (arraySize+1) + " numbers"
+ "\nTotal numbers added up is: " + sum
+ "\nAverage number is: " + (sum / (nums.length)));
input.close();
}
}
You are sorting list so it will return last value from sorted list. Collections.sort(list) is sorting asc so you get max number from the list. First approach,
1) Either you have to manage origanal list before sorting like
ArrayList<Integer> ori = new ArrayList<Integer>(list);
Collections.sort(list);
And get the value from ori.
System.out.println(" \nLast Number is : " + ori.get(list.size()-1)
2) Second approach, Create variable which will store temp last entered value. you can use it.
Might it helps!!
So your example like:
public static void main(final String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (input.hasNextInt()) {
list.add(input.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
System.out.printf("%s", "You entered: ");
for (int i = 0; i < nums.length; i++) {
System.out.printf("%d%s", nums[i], ", ");
}
ArrayList<Integer> ori = new ArrayList<Integer>(list);
Collections.sort(list);
int b = Collections.max(list);
int c = Collections.min(list);
int arraySize = nums.length-1;
double sum = 0;
for(int i = 0; i < list.size(); i++)
{
sum += list.get(i);
}
System.out.println(" \nLast Number is : " + ori.get(list.size()-1)
+ "\nLargest Number is: " + b
+ "\nSmallest number is :" + c
+ "\n" + "You entered " + (arraySize+1) + " numbers"
+ "\nTotal numbers added up is: " + sum
+ "\nAverage number is: " + (sum / (nums.length)));
input.close();
}
Related
Hi I want to put my prints in a for-loop. how to do it? So something like
if index = 0,1,2 print.
if index = 2,3,4 print.
if index = 4,5,6 print.
Code:
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.println("\n\nThis starts to look like calculations:");
System.out.print("\n" + objectList.get(0));
System.out.print(" "+ objectList.get(1));
System.out.print(" " + objectList.get(2) + " =");
System.out.print("\n\n" + objectList.get(2));
System.out.print(" " + objectList.get(3));
System.out.print(" " + objectList.get(4)+ " =");
System.out.print("\n\n" + objectList.get(4));
System.out.print(" " + objectList.get(5));
System.out.print(" " + objectList.get(6) + " =");
output:
This starts to look like calculations:
1 + 3432.123 =
3432.123 * 4535 =
4535 - 24.4 =
private String buildOperation(int pos){
String output;
if(pos == 0) {
output = "+";
}else if(pos == 1){
output = "*";
}else {
output = "-";
}
return output;
}
List<Object> objectList = new ArrayList(res);
for(int i = 0; i < objectList.size()-1; i++){
System.out.println(objectList.get(i) + buildOperation(i) + objectList.get(i+1) + "=");
}
Additionaly I'll use a HashMap with the operations to avoid all if/else conditions
Map<Integer,String> operations = new HashMap{}
operations.put(0,"+");
operations.put(1,"*");
operations.put(2,"-");
System.out.println(objectList.get(i) + operations.get(i) + objectList.get(i+1) + "=");
}
Final solution now the String size does not matter anymore.
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.print("\n\nThis starts to look like calculations:");
int maxi= objectList.size();
maxi = maxi -2;
System.out.println("\n\nmaxi = " + maxi);
for (int i = 0; i < maxi; i+=2) {
System.out.println("");
System.out.println(i);
System.out.print("\n\n" + objectList.get(i));
System.out.print(" " + objectList.get(i + 1));
System.out.print(" " + objectList.get(i + 2)+ " =");
My problem is probably ridiculously easy and I'm just missing something. My program crashes due to a null value of cell 1 during its first iteration. i troubleshot a bit myself and realized on iteration 1 the array length is 1 then after all other iterations the length is 2. this initial improper length causes a complete crash. Any ideas?
`import java.util.Scanner;
import java.io.*;
/* Takes in all of users personal information, and weather data. Then proceeds to determine status of day + averages of the data values provided, then reports to user*/
public class ClimateSummary
{
public static void main (String [] args) throws FileNotFoundException
{
Scanner sc = new Scanner (new File(args[0]));
String name = sc.nextLine();
String birthCity = sc.next();
String birthState = sc.next();
String loc = sc.next();
int birthDay = sc.nextInt();
String birthMonth = sc.next();
int birthYear = sc.nextInt();
int highTemp = 0;
double avgTemp;
double avgPrecip;
int coldDays = 0;
int hotDays = 0;
int rainyDays = 0;
int niceDays = 0;
int miserableDays = 0;
double totalTemp = 0;
double totalPrecip = 0;
int i = 0;
while(i <= 5)
{
String storage = sc.nextLine();
String[] inputStorage = storage.split(" "); //couldnt find scanf equiv in c for java so using array to store multiple values.
System.out.println(inputStorage[0]);
int tempTemp = Integer.parseInt(inputStorage[0]);
double tempPrecip = Double.parseDouble(inputStorage[1]);
totalTemp = totalTemp + tempTemp;
totalPrecip = totalPrecip + tempPrecip;
if(highTemp < tempTemp)
{
highTemp = tempTemp;
}
if(tempTemp >= 60.0)
{
hotDays++;
}else{
coldDays++;
}
if(tempPrecip > 0.1)
{
rainyDays++;
}
if(tempTemp >= 60.0 || tempTemp <= 80.0 || tempPrecip == 0.0)
{
niceDays++;
}else if(tempTemp < 32.0 || tempTemp > 90.0 || tempPrecip > 2.0)
{
miserableDays++;
}else{
}
i++;
}
avgTemp = totalTemp/5;
avgPrecip = totalPrecip/5;
System.out.println("Name: " + name);
System.out.println("Place of birth: " + birthCity + "," + birthState);
System.out.println("Data collected at: " + loc);
System.out.println("Date of birth: " + birthMonth + " " + birthDay +", " + birthYear);
System.out.println("");
System.out.println("The highest temperature during this tine was " + highTemp + " degrees Farenheit");
System.out.println("The average temperature was " + avgTemp + " degrees Farenheit");
System.out.println("The average amount of precipitation was " + avgPrecip + " inches");
System.out.println("Number of hots days = " + hotDays);
System.out.println("Number of cold days = " + coldDays);
System.out.println("Number of rainy days = " + rainyDays);
System.out.println("Number of nice days = " + niceDays);
System.out.println("Number of miserable days = " + miserableDays);
System.out.println("Goodbye and have a nice day!");
}
Eric Thomas
Columbus
Nebraska
Columbus
18
February
1990
54 0
44 2.2
64 0.06
26 0.5
34 0.02
If your file contains null values then you should handle it separately.... using something like this:
if (name == null) {
//do something
}
else {
// do something else;
}
A good discussion on nulls can be seen here...How to check for null value in java
Also, after splitting a string, you need to check if the array (which is the output) has values at the indices that you are using.
For example:
String name = "A/B/C";
String[] nameArray = name.split("/");
In the above case, nameArray[3] will throw an error.
for(int counter = 0; counter < args.length; counter++){
System.out.println("Displaying per words: " + args[counter]);
splitWords = args[counter].toCharArray();
for(int counter2 = 0; counter2 < splitWords.length; counter2++){
System.out.println("Word spliced: " + splitWords[counter2]);
System.out.println("The number equivalent of " + splitWords[counter2] + " is "
+ (int) splitWords[counter2]);
occurenceCount[(int)splitWords[counter2]]++;
System.out.println("The letter " + splitWords[counter2] +
" was shown " + occurenceCount[(int)splitWords[counter2]] + " times.");
}
}
My function doesn't detect counter2 as a variable since it was inside the nested for loop. So how do I get out of this dilemma?
I'm trying to use the argument inputs (string respectively) and post the number of occurrences using an ascii table as reference and, as you see, there's just one obstacle from stopping me from accomplishing that.
Any ideas?
Your primary problem is that you have missed one important fact - your counts are not complete until after your loop has completed.
You therefore need to print out your counts in a separate loop after your first loop is complete.
public void test() {
String[] args = {"Hello"};
int[] occurenceCount = new int[256];
for (int word = 0; word < args.length; word++) {
System.out.println("Displaying per words: " + args[word]);
char[] splitWords = args[word].toCharArray();
for (int character = 0; character < splitWords.length; character++) {
System.out.println("Word spliced: " + splitWords[character]);
System.out.println("The number equivalent of " + splitWords[character] + " is "
+ (int) splitWords[character]);
occurenceCount[(int) splitWords[character]]++;
System.out.println("Word spliced: " + splitWords[character]);
}
}
// Scond loop to print the results.
for (int character = 0; character < occurenceCount.length; character++) {
int count = occurenceCount[character];
if (count > 0) {
System.out.println("The letter " + ((char) character)
+ " was shown " + count + " times.");
}
}
}
import java.util.Random;
import java.util.Scanner;
public class LotteryGame{
public static void main(String[] args) {
int NUM_DIGITS = 6;
int[] userDigits = new int[NUM_DIGITS];
int[] lotteryNumbers = new int[NUM_DIGITS];
int sameNum;
generateNumbers(lotteryNumbers);
getUserData(userDigits);
sameNum = compareArrays(lotteryNumbers, userDigits);
System.out.println("Winning numbers: " + lotteryNumbers[0] + " "
+ lotteryNumbers[1] + " " + lotteryNumbers[2] + " "
+ lotteryNumbers[3] + " " + lotteryNumbers[4] + " " + lotteryNumbers[5] + " ");
System.out.println("Your numbers: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " " + userDigits[5] +" ");
System.out.println("Number of matching digits: " + sameNum);
if (sameNum == 6) {
System.out.println("First prize!!!");
}
if (sameNum == 5) {
System.out.println("Second prize!!!");
}
if (sameNum == 0) {
System.out.println("No matching numbers, you lost.");
}
}
public static void generateNumbers(int[] lotteryNumbers) {
Random randNum = new Random();
lotteryNumbers[0] = randNum.nextInt(59);
lotteryNumbers[1] = randNum.nextInt(59);
lotteryNumbers[2] = randNum.nextInt(59);
lotteryNumbers[3] = randNum.nextInt(59);
lotteryNumbers[4] = randNum.nextInt(59);
lotteryNumbers[5] = randNum.nextInt(59);
return lotteryNumbers[5];
}
public static void getUserData(int[] userDigits) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter first digit: ");
userDigits[0] = keyboard.nextInt();
System.out.print("Enter second digit: ");
userDigits[1] = keyboard.nextInt();
System.out.print("Enter third digit: ");
userDigits[2] = keyboard.nextInt();
System.out.print("Enter fourth digit: ");
userDigits[3] = keyboard.nextInt();
System.out.print("Enter fifth digit: ");
userDigits[4] = keyboard.nextInt();
System.out.print("Enter sixth digit: ");
userDigits[5] = keyboard.nextInt();
return userDigits[5];
}
public static int compareArrays(int[] userDigits, int[] lotteryNumbers) {
int sameNum = 0;
for (int i = 0; i < 6; i++) {
for (int x = 0; x < 5; x++) {
if (lotteryNumbers[i] == userDigits[x]) {
sameNum++;
}
}
}
return sameNum;
}
}
When I compile I get the following errors-
LotteryGame.java:51: error: incompatible types: unexpected return value
return lotteryNumbers[5];
^
LotteryGame.java:72: error: incompatible types: unexpected return value
return userDigits[5];
^
2 errors
Can any of you help me with these compilation errors? I'm trying to get this to work. The user is supposed to input 6 numbers, and the program is supposed to pick randomly 6 numbers. Using these numbers, the program will compare the numbers with echoed input.
generateNumbers and getUserData are void functions, meaning they don't return anything, so you can't return anything from them.
You probably want to declare them as functions returning int instead:
public static int generateNumbers(int[] lotteryNumbers)
Univerio is correct in answering your original question.
Looking at your test code you might consider removing the return statement on those two functions since you are just populating both arrays.
I was hoping someone could help me out with a small problem I am having in java. I have a List and an ArrayList that I would like to output to a file with the first element of each, printed next to one another. Here is what I have so far:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
for(String unique:uniqueList){
out.write(unique + "\r");
}
ArrayList<Integer>subtr=new ArrayList<Integer>();
out.write("The number: " + subtr + "\r");
This results in this output:
A
B
C
D
E
F
The number: [1, 2, 3, 4, 5, 6]
But I would rather it be like this:
A The number: 1
B The number: 2
...etc.
I am not really sure where to start on how to get the output format like that. I tried putting both sets of values into arrays but I just ended up confusing myself... Which is how I ended up here. Any help would be super appreciated.
Simply do this:
String br = System.getProperty("line.separator");
for (int i = 0, n = Math.min(uniqueList.size(), subtr.size()); i < n; i++)
out.write(uniqueList.get(i) + " The number: " + subtr.get(i) + br);
Something like this:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
ArrayList<Integer> subtr = new ArrayList<Integer>();
int length = Math.min(uniqueList.size(), substr.size());
for (int i = 0; i < length; i++) {
out.write(uniqueList.get(i) + " The number: " + substr.get(i) + "\r");
}
List<String> uniqueList = new ArrayList<String>(dupMap.values());
ArrayList<Integer>subtr=new ArrayList<Integer>();
for (int i = 0; i < uniqueList.size(); i++){
out.write(uniqueList.get(i) + "\r");
out.write("The number: " + subtr.get(i) + "\n");
}
NOTE: This assumes that both lists have the same number of elements. If they are not, you would iterate to Math.min(uniqueList.size(), subtr.size()).
This should do it:
int maxLength = Math.min(uniqueList.size(), subtr.size());
for(int i = 0; i < maxLength; i++)
{
out.print(uniqueList.get(i) + " The number: " + subtr.get(i) + "\r");
}
The efficient way is to maintain a HashMap with uniqueList as keys and subtr as values. Then iterate over a map.
Map<String,Integer> map = new HashMap<String,Integer>();
for (int i = 0; i < uniqueList.size(); i++){
map.put(key, subtr.get(i));
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
out.println(entry.getKey() + " The Number : " + entry.getValue());
}