Output multiple strings from scanner input - java

The purpose of my program is to accept ints, doubles, and strings from the user and when the program is terminated by inputing the word "quit", the program averages the ints and doubles, and outputs the submitted strings. Here is what i have so far:
import java.util.*;
public class Lab09 {
public static void main(String [] args) {
Scanner console = new Scanner(System.in);
double sumI = 0;
double sumD = 0;
String words = "";
int numInputInt = 0;
int numInputDoub = 0;
do {
System.out.print("Enter something: ");
if (console.hasNextInt()) {
int numI = console.nextInt();
if (numI >= -100 && numI <= 100) {
sumI += numI;
numInputInt++;
}
else {
System.out.println("Integer out of range!(-100 .. 100)");
}
}
else if (console.hasNextDouble()) {
double numD = console.nextDouble();
if (numD >= -10.0 && numD <= 10.0) {
sumD += numD;
numInputDoub++;
}
else {
System.out.println("Double out of range!(-10.0 .. 10.0)");
}
}
else {
words = console.next();
}
} while (!words.equalsIgnoreCase("quit"));
System.out.println("Program terminated...");
double avgInt = sumI / numInputInt;
double avgDoub = sumD / numInputDoub;
if (numInputInt > 0) {
System.out.println("\tAveragae of Integers: " + avgInt);
}
else {
System.out.println("\tNo intergers submitted");
}
if (numInputDoub > 0) {
System.out.println("\tAverage of Doubles: " + avgDoub);
}
else {
System.out.println("\tNo doubles submitted");
}
System.out.println(words);
}
}
The ints and doubles get processed well, but im stuck in the strings. Any ideas on how to go about doing so?
Thanks in advance!

While you could build a List<String> of words it looks like you just want to concatenate each new word to your String words like,
if (words.length() > 0) words += " "; // <-- add a space.
words += console.next(); // <-- += not =
Then change your loop test to something like,
while (!words.trim().toLowerCase().endsWith("quit"));
And it should work something like you would expect.

You could use
String input = "";
do {
//...
}
else {
input = console.next();
words += input + " ";
}
console.nextLine(); // Read the carriage return
} while (!input.equalsIgnoreCase("quit"));
//...
System.out.println(words.trim());
to concatenate the text, but this is rather inefficient when done within a loop.
A better solution would be to use a StringBuilder...
StringBuilder work = new StringBuilder(128);
String input = "";
do {
//...
}
else {
input = console.next();
words.append(" ").append(input);
}
console.nextLine(); // Read the carriage return
} while (!input.equalsIgnoreCase("quit"));
//...
System.out.println(words);

I just read your comment that you can't use any other class, try this:
import java.util.*;
public class Lab09 {
public static void main(String [] args) {
Scanner console = new Scanner(System.in);
double sumI = 0;
double sumD = 0;
String words = "";
int numInputInt = 0;
int numInputDoub = 0;
do {
System.out.print("Enter something: ");
if (console.hasNextInt()) {
int numI = console.nextInt();
if (numI >= -100 && numI <= 100) {
sumI += numI;
numInputInt++;
}
else {
System.out.println("Integer out of range!(-100 .. 100)");
}
}
else if (console.hasNextDouble()) {
double numD = console.nextDouble();
if (numD >= -10.0 && numD <= 10.0) {
sumD += numD;
numInputDoub++;
}
else {
System.out.println("Double out of range!(-10.0 .. 10.0)");
}
}
else {
words = words.concat(" ").concat(console.next());
}
} while (!words.contains("quit"));
System.out.println("Program terminated...");
double avgInt = sumI / numInputInt;
double avgDoub = sumD / numInputDoub;
if (numInputInt > 0) {
System.out.println("\tAveragae of Integers: " + avgInt);
}
else {
System.out.println("\tNo intergers submitted");
}
if (numInputDoub > 0) {
System.out.println("\tAverage of Doubles: " + avgDoub);
}
else {
System.out.println("\tNo doubles submitted");
}
System.out.println(words);
}
}

Related

Int array pushed through while loop until it reaches -1

I have to take a single line of user input, and calculate the average of all the numbers until it reaches -1 using a while loop. An example of user input could be something like 2 -1 6 which is why I've done it this way. I've figured out how to split this into an int array, but I can't figure out how to do the while loop portion.
System.out.println("user input")
String user = scan.nextLine();
String[] string = user.split(" ");
int[] numbers = new int[string.length];
for(int i = 0;i < string.length;i++) {
numbers[i] = Integer.parseInt(string[i]);
}
while ( > -1){
}
Class java.util.Scanner has methods hasNextInt and nextInt.
import java.util.Scanner;
public class Averages {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter series of integers on single line separated by spaces.");
System.out.println("For example: 2 -1 6");
int sum = 0;
int count = 0;
while (scan.hasNextInt()) {
int num = scan.nextInt();
if (num == -1) {
break;
}
sum += num;
count++;
}
if (count > 0) {
double average = sum / (double) count;
System.out.println("Average: " + average);
}
else {
System.out.println("Invalid input.");
}
}
}
Note that you need to cast count to a double when calculating the average otherwise integer division will be performed and that will not give the correct average.
I am assuming you mean, when user input number is -1. we should take average of all number before -1. that is was I am doing here.
System.out.println("user input")
String user = scan.nextLine();
int totalSum = 0;
double avg = 0;
String[] string = user.split(" ");
int[] numbers = new int[string.length];
for(int i = 0;i < string.length;i++) {
numbers[i] = Integer.parseInt(string[i]);
if(numbers[i]==-1){
avg = (double)totalSum / i;
break;
}
totalSum += numbers[i];
}
With only while loop
System.out.println("user input");
String user = scan.nextLine();
int totalSum = 0;
double avg = 0;
String[] string = user.split(" ");
int[] numbers = new int[string.length];
int i = 0;
numbers[i] = Integer.parseInt(string[i]);
while(numbers[i]!=-1) {
totalSum += numbers[i];
i++;
numbers[i] = Integer.parseInt(string[i]);
}
avg = (double)totalSum / i;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("user input");
String user = scan.nextLine();
boolean found = false;
Double average = 0.0;
String[] string = user.split(" ");
int[] numbers = new int[string.length];
for(int i = 0;i < string.length && found == false ;i++) {
numbers[i] = Integer.parseInt(string[i]);
}
int t = 0;
while (found == false && t < string.length){
if(numbers[t] == - 1){
average = average/t;
found = true;
}
else{
average = (Double) average + numbers[t];
t++;
}
}
System.out.println("Average = " + average);
}
}

Decimal to Binary conversion using java Errors

I am kind of confused is my program correct or I am missing something!
I could get an output out of it.
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter you String: ");
String bin = sc.nextLine();
int length = bin.length();
int j = 0;
int sum = 0;
if (length != 0) {
for (int i = length - 1; i >= 0; i--) {
if (bin.charAt(i) == "0" || bin.charAt(i) == "1") {
String s = bin.charAt(j) + "";
sum = (int) (sum + (Integer.valueOf(s)) * (Math.pow(2, i)));
j++;
} else {
System.out.println("illegal input.");
}
}
System.out.println(sum);
} else {
System.out.println("illegal input.");
}
}
Remove the quotation marks on this line:
if (bin.charAt(i) == "0" || bin.charAt(i) == "1") {
should become
if (bin.charAt(i) == 0 || bin.charAt(i) == 1) {
Below code works fine:
import java.util.Scanner;
public class test {
public static void main (String args []) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter you String: ");
String bin = sc.nextLine();
int length = bin.length();
int j = 0;
int sum = 0;
if (length != 0) {
for (int i = length - 1; i >= 0; i--) {
if (bin.charAt(i) == '0' || bin.charAt(i) == '1') {
String s = bin.charAt(j) + "";
sum = (int) (sum + (Integer.valueOf(s)) * (Math.pow(2, i)));
j++;
} else {
System.out.println("illegal input.");
}
}
System.out.println(sum);
} else {
System.out.println("illegal input.");
}
}
}

String Cannont Be Converted to Char

I do not understand why my program will not allow me to convert my variable into char. Any help would be greatly appreciated!!! I am getting a total of 7 errors all either based around my test score grades or around the test score keyboard entry.
public class lab13
{
public static void main(String[] args)
{
// declare variables
int average;
int sum;
int i;
char grade;
int testScore;
//Create a Scanner Object
Scanner keyboard= new Scanner(System.in);
sum = 0;
i = 1;
while (i <= 4)
{
System.out.print("Enter a test score:");
testScore=keyboard.nextLine();
if (testScore < 60)
{
grade =(F);
}
else
{
if (testScore < 70)
{
grade =("D");
}
else
{
if (testScore < 80)
{
grade =("C");
}
else
{
if (testScore < 90)
{
grade =("B");
}
else
{
grade =("A");
}
}
}
}
System.out.print("Test score:"+testScore);
System.out.print("Letter grade:"+grade);
sum = sum + testScore;
i = i + 1;
}
average = sum / 4;
System.out.print("Test score average = " + average);
} // close main
} // close lab13
A char constant can be expressed with '' like
grade = 'F';
and
grade = 'D';
and
grade = 'C';
and
grade = 'B';
and
grade = 'A';
char can only hold a single character, which is defined using single quotes, as in 'C'
Insted of keyboard.nextLine() use keyboard.nextInt() and for character value assignment directly use character with single quota like 'A' instead of ("A")
import java.util.Scanner;
public class lab13
{
public static void main(String[] args)
{
// declare variables
int average;
int sum;
int i;
char grade;
int testScore;
//Create a Scanner Object
Scanner keyboard= new Scanner(System.in);
sum = 0;
i = 1;
while (i <= 4)
{
System.out.print("Enter a test score:");
testScore=keyboard.nextInt();
if (testScore < 60)
{
grade ='F';
}
else
{
if (testScore < 70)
{
grade ='D';
}
else
{
if (testScore < 80)
{
grade ='C';
}
else
{
if (testScore < 90)
{
grade ='B';
}
else
{
grade ='A';
}
}
}
}
System.out.println("Test score:"+testScore);
System.out.println("Letter grade:"+grade);
sum = sum + testScore;
i = i + 1;
}
average = sum / 4;
System.out.print("Test score average = " + average);
} // close main
} // close lab13

NumberFormatException: For input string: "[memorylocation" java

I'm doing an assignment where the goal is to, among other things, to add two large integers. Here is my code, spread out into four files.
Main that we cannot change:
import java.util.*;
import MyUtils.MyUtil;
public class CSCD210HW7
{
public static void main(String [] args)throws Exception
{
int choice;
String num;
LargeInt one, two, three = null;
Scanner kb = new Scanner(System.in);
num = HW7Methods.readNum(kb);
one = new LargeInt(num);
num = HW7Methods.readNum(kb);
two = new LargeInt(num);
do
{
choice = MyUtil.menu(kb);
switch(choice)
{
case 1: System.out.println(one + "\n");
break;
case 2: System.out.println("The value of the LargeInt is: " + two.getValue() + "\n");
break;
case 3: num = HW7Methods.readNum(kb);
one.setValue(num);
break;
case 4: if(one.equals(two))
System.out.println("The LargeInts are equal");
else
System.out.println("The LargeInts are NOT equal");
break;
case 5: three = two.add(one);
System.out.printf("The results of %s added to %s is %s\n", one.getValue(), two.getValue(), three.getValue());
break;
case 6: HW7Methods.displayAscendingOrder(one, two, three);
break;
default: if(two.compareTo(one) < 0)
System.out.printf("LargeInt %s is less than LargeInt %s\n", two.getValue(), one.getValue());
else if(two.compareTo(one) > 0)
System.out.printf("LargeInt %s is greater than LargeInt %s\n", two.getValue(), one.getValue());
else
System.out.printf("LargeInt %s is equal to LargeInt %s\n", two.getValue(), one.getValue());
break;
}// end switch
}while(choice != 8);
}// end main
}// end class
LargeInt Class(Custom Class We Created)
public class LargeInt implements Comparable<LargeInt>
{
private int[]myArray;
private LargeInt()
{
this("0");
}
public LargeInt(final String str)
{
this.myArray = new int[str.length()];
for(int x = 0; x < this.myArray.length; x++)
{
this.myArray[x] = Integer.parseInt(str.charAt(x)+ "");
}
}
public LargeInt add(final LargeInt passedIn)
{
String stringOne = myArray.toString();
String stringTwo = passedIn.myArray.toString();
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
return new LargeInt(""+s);
}
public void setValue(final String arrayString)
{
this.myArray = new int[arrayString.length()];
for(int x = 0; x < myArray.length; x++)
{
this.myArray[x]=arrayString.charAt(x);
}
}
#Override
public int compareTo(LargeInt passedIn)
{
if(passedIn == null)
{
throw new RuntimeException("NullExceptionError");
}
int ewu = 0;
int avs = 0;
if(this.myArray.length != passedIn.myArray.length)
{
return this.myArray.length - passedIn.myArray.length;
}
for(int i = 0; i < this.myArray.length -1; i++)
{
if(this.myArray[i] != passedIn.myArray[i])
{
return this.myArray[i]-passedIn.myArray[i];
}
}
return ewu-avs;
}
public int hashCode()
{
String p = "";
for(int f = 0; f < this.myArray.length; f++)
{
p += myArray[f];
}
return p.hashCode();
}
public String getValue()
{
String h = "";
for(int t = 0; t < this.myArray.length; t++)
{
h += myArray[t];
}
return h;
}
#Override
public boolean equals(Object jbo)
{
if(jbo == null)
{
return false;
}
if(!(jbo instanceof LargeInt))
{
return false;
}
LargeInt k =(LargeInt)jbo;
if(k.myArray.length != this.myArray.length)
{
return false;
}
for(int d = 0; d < this.myArray.length; d++)
{
if(k.myArray[d] != myArray[d])
{
return false;
}
}
return true;
}
#Override
public String toString()
{
String c = "";
for(int q = 0; q < this.myArray.length; q++)
{
c += myArray[q];
}
return "The LargeInt is: " + c;
}
}
HW7Methods File
import java.util.*;
import java.io.*;
public class HW7Methods
{
public static String readNum(Scanner kb)
{
String num = "";
System.out.print("Enter Your Large Int: ");
num = kb.nextLine();
return num;
}
public static void displayAscendingOrder(final LargeInt first, final LargeInt second, final LargeInt third)
{
String highestInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) >= 0)
{
highestInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) >= 0)
{
highestInt = second.getValue();
}
else
{
highestInt = third.getValue();
}
String middleInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) <= 0)
{
middleInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) <= 0)
{
middleInt = second.getValue();
}
else
{
middleInt = third.getValue();
}
String lowestInt;
if(first.compareTo(second) <= 0 && first.compareTo(third) <= 0)
{
lowestInt = first.getValue();
}
else if(second.compareTo(first) <= 0 && second.compareTo(third) <= 0)
{
lowestInt = second.getValue();
}
else
{
lowestInt = third.getValue();
}
System.out.println("The LargeInts in order are: " + lowestInt + ", " + middleInt + ", " + highestInt);
}
}
MyUtil file
package MyUtils;
import java.io.*;
import java.util.Scanner;
public class MyUtil
{
public static int menu(Scanner kb)
{
int userChoice;
System.out.println("1) Print First Int");
System.out.println("2) Print Second Int");
System.out.println("3) Add Different Int");
System.out.println("4) Check If Equal");
System.out.println("5) Add Large Ints");
System.out.println("6) Display In Ascending Order");
System.out.println("7) Compare Ints");
System.out.println("8) Quit");
kb = new Scanner(System.in);
System.out.print("Please Select Your Choice: ");
userChoice = kb.nextInt();
while(userChoice < 1 || userChoice > 8)
{
System.out.print("Invalid Menu Choice. Please Re-Enter: ");
userChoice = kb.nextInt();
}
return userChoice;
}
}
When I go to run this code, it prompts me for two Large Integers like it's supposed to. However, when I choose option 5 to add them, this is what I get:
Exception in thread "main" java.lang.NumberFormatException: For input string: "[I#55f96302"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at LargeInt.add(LargeInt.java:24)
at CSCD210HW7.main(CSCD210HW7.java:41)
I've never seen that type of error before. Can someone tell me what is going on?
For input string: "[I#55f96302
That is not a "proper" String you are trying to parse here.
This is what an int[] looks like when you call toString() on it.
String stringOne = myArray.toString();
Why do you do that? What is that supposed to do?
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
From the looks of it, you try to handle "large" ints with your LargeInt class by somehow storing them in an array of ints. That's okay, BigInteger also works like that (more or less), but you cannot just do calculations by trying to convert back to int (after all those numbers are too big for int arithmetic to handle, even if you do the string parsing properly).

How to read lines from a file and assign the lines to an array?

Currently, I'm trying to read in a .dat file and assign various lines into an array. The file will provide items like "a100" and "q80" which I will have to separate into categories by letter and then have different grades as an array for each category. Right now, this is what I have, but I'm getting a lot of run-time errors when I try various things. Is there something I'm missing here?
Some of the errors I'm having:
When I execute case 'P', it prints this out: WeightedGrades#13105f32
When I try to execute cases C, A or D, this happens: Exception in thread "main" java.lang.NoSuchMethodError: WeightedGrades.deleteGrade(Ljava/lang/String;)Z
WeightedGrades class:
public class WeightedGrades {
private String name;
private int numGrades;
private String[] grades;
public static final double ACTV_WT = 0.05, QUIZ_WT = 0.10, PROJ_WT = 0.25, EXAM_WT = 0.30, FINAL_EXAM_WT = 0.30;
public WeightedGrades(String nameIn, int numGradesIn, String[] gradesIn) {
name = nameIn;
numGrades = numGradesIn;
grades = gradesIn;
}
public String getName() {
return name;
}
public int getNumGrades() {
return numGrades;
}
public String[] getGrades() {
return grades;
}
public double[] gradesByCategory(char categoryChar) {
int count = 0;
for (int i = 0; i < grades.length; i++) {
if (categoryChar == grades[i].charAt(0)) {
count++;
}
}
double[] gradesNew = new double[count];
count = 0;
for( int i = 0; i < numGrades; i++) {
if (categoryChar == grades[i].charAt(0)) {
gradesNew[count] = Double.parseDouble(grades[i].substring(1));
count++;
}
}
return gradesNew;
}
public String toString() {
String result = "\tStudent Name: " + getName()
+ "\n\tActivities: " + gradesByCategory('A')
+ "\n\tQuizzes: " + gradesByCategory('Q')
+ "\n\tProjects: " + gradesByCategory('P')
+ "\n\tExams: " + gradesByCategory('E')
+ "\n\tFinal Exam: " + gradesByCategory('F')
+ "\n\tCourse Average: " + courseAvg();
return result;
}
public void addGrade(String newGrade) {
if (numGrades >= grades.length) {
increaseGradesCapacity();
}
grades[numGrades] = newGrade;
numGrades++;
}
public boolean deleteGrade(String gradeDelete) {
boolean delete = false;
int deleteIndex = -1;
for (int i = 0; i < numGrades; i++) {
if (gradeDelete.charAt(0) == grades[i].charAt(0) &&
Double.parseDouble(gradeDelete.substring(1))
== Double.parseDouble(grades[i].substring(1))) {
deleteIndex = i;
}
}
if (deleteIndex > -1) {
for (int i = deleteIndex; i < numGrades - 1; i++) {
grades[i] = grades[i + 1];
}
grades[numGrades - 1] = "";
numGrades--;
return true;
}
else {
return false;
}
}
public void increaseGradesCapacity() {
String[] temporary = new String[grades.length + 1];
for (int i = 0; i < grades.length; i++) {
temporary[i] = grades[i];
}
grades = temporary;
}
public double average(double[] newArray) {
if (newArray.length == 0) {
return 0.0;
}
double sum = 0;
double average = 0;
for ( int i = 0; i < newArray.length; i++) {
sum += newArray[i];
average = sum / newArray.length;
}
return average;
}
public double courseAvg() {
double actvAvg = 0.0;
double quizAvg = 0.0;
double projAvg = 0.0;
double examAvg = 0.0;
double finalAvg = 0.0;
double avg = 0.0;
if (!numGrades.length == 0) {
avg = actvAvg * ACTV_WT + quizAvg * QUIZ_WT + projAvg * PROJ_WT + examAvg * EXAM_WT + finalAvg * FINAL_EXAM_WT;
}
return avg;
}
}
Second class
import java.util.Scanner;
import java.io.IOException;
public class WeightedGradesApp {
public static void main(String[] args) throws IOException {
String name = "";
int numGrades = 0;
String[] grades = new String[13];
String code = "";
String gradeAdd = "";
String gradeDelete = "";
String categoryIn = "";
WeightedGrades student = new WeightedGrades(name, numGrades, grades);
Scanner userInput = new Scanner(System.in);
if (args == null) {
System.out.println("File name was expected as a run argument.");
System.out.println("Program ending.");
return;
}
else {
System.out.println("File read in and WeightedGrades object created.");
System.out.println("");
System.out.println("Player App Menu");
System.out.println("P - Print Report");
System.out.println("C - Print Category");
System.out.println("A - Add Grade");
System.out.println("D - Delete Grade");
System.out.println("Q - Quit ");
do {
System.out.print("Enter Code [P, C, A, D, or Q]: ");
code = userInput.nextLine();
if (code.length() == 0) {
continue;
}
code = code.toUpperCase();
char codeChar = code.charAt(0);
switch (codeChar) {
case 'P':
System.out.println(student.toString());
break;
case 'C':
System.out.print(" Category: ");
categoryIn = userInput.nextLine();
char categoryChar = categoryIn.charAt(0);
System.out.println(student.gradesByCategory(categoryChar));
break;
case 'A':
System.out.print(" Grade to add: ");
gradeAdd = userInput.nextLine();
student.addGrade(gradeAdd);
break;
case 'D':
System.out.print(" Grade to delete: ");
gradeDelete = userInput.nextLine();
boolean isDeleted = student.deleteGrade(gradeDelete);
if (isDeleted) {
System.out.println(" Grade deleted");
}
else {
System.out.println(" Grade not found");
}
break;
case 'Q':
break;
default:
}
} while (!code.equalsIgnoreCase("Q"));
}
}
}
For starters your code as is doesn't compile due to the line
if (!numGrades.length == 0) {
This is because numGrades is an int it is a primative type and therefore does not have any property length. I'm assuming what you want here is
if (numGrades != 0) {
Also as I mentioned you are not dealing with reading in the file, you supply the file name but never actually read it, I suggest you look at the Java tutorial on File IO
On this note you do the check args == null this will not check that no args are supplied, try it. what you want is args.length == 0
On your other error I have no idea how you even produced that... I'm assuming it is using an older compiled version of the class where the methods have not being written.

Categories