Program not running as intended [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to make a java program that will add inputs until the total equals 100+ OR the user inputs 5 numbers. I'm also attempting to add a highest run to it that keeps track of the highest input. Currently it continues to run after 5 inputs when it's less than 100 total and my highest run doesn't work. How would I fix this?(I'm new to Java if you can tell)
import java.io.*;
public class HighScoreTest {
public static void main(String[] args) {
// input streams.
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
// constant declarations
final Integer MAX = 100;
final Integer MAX_NUMBER = 4;
// variable declarations
String sName;
Integer currentTotal;
Integer currentNumber;
Integer numbersInputed = 0;
Integer count;
Integer maxRunToDate = 0;
// we catch exceptions if some are thrown.
// an exception would be entering a string when a number is expected
try {
System.out.println("What is your name?");
// reading string from the stream
sName = reader.readLine();
currentTotal = 0;
for(count = 0; count < MAX_NUMBER; count++) {
numbersInputed += count;
}
do {
System.out.println("Please enter a number");
currentNumber = Integer.parseInt(reader.readLine());
currentTotal = currentTotal + currentNumber;
}while(currentTotal < MAX || numbersInputed == MAX_NUMBER);
if (maxRunToDate < currentTotal) {
maxRunToDate = currentTotal;
}
System.out.println(sName +", the total for this run is "+ currentTotal);
System.out.println("The highest run is "+ maxRunToDate);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}

Some help to get you going:
currentRun = currentRun + currentNumber;
Simply doesn't make sense!
I assume that currentRun should count the number of runs so far. So that you can stop after the 5th round.
Thus: you should just increment that counter by for each round.
In other words: try to separate things. Step back and consider what kind of information you want to "track" and how many variables you really need to do that.
And please understand: we will not solve your assignment for you. If at all, there will be some guidance on how to make progress. But don't expect us to figure all the bugs in your code and resolve them for you.

There is several things that you need to know:
First, avoid wrap classes like Integer unless you intend to use it together with the Colection FrameWork or even Streams. If your problem is the fact that the output of the parsing is the Integer class, don't worry, for it will auto unbox. Something like this:
int currentNumber = Integer.parseInt(reader.readLine()); //Auto Unboxing
Second, why do you even have the for loop in the beginning? Remove it. If you want to initialize the numbersInputed variable just do it.
And third, if you whant to increment or decrement, you can just use ++ or `--
And check the Oracle Tutorials: https://docs.oracle.com/javase/tutorial/
I hope I have helped.
Have a nice day. :)

Related

Print the integers from 1 to a number given by user [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm doing the Java MOOC by Helsinki University. Stuck on the following problem:
Write a program which prints the integers from 1 to a number given by the user.
Sample output
Where to? 3
1
2
3
The code below outputs the expected results but is not accepted as valid. Any suggestions or pointers are welcome, thank you!
import java.util.Scanner;
public class FromWhereToWhere {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = Integer.valueOf(scanner.nextLine());
int start = 1;
while (start <= userInput) {
System.out.println(start);
start++;
}
}
}
Most likely the system that tests your program is stuffing values into standard input (System.in) with spaces, and assumes that you will read with .nextInt().
If that's not it, double check the program description; what is supposed to happen if I enter -1? 0? 1985985410395831490583440958230598? FOOBAR?
If it doesn't say, then presumably the verifier won't throw those inputs at you (if it does, file a bug with the MOOC provider, the course itself needs fixing if that is the case), but if it does, you're going to have to code those rules in, probably.
This shouldn't be it, but to exactly mirror the desired result, it's System.out.print("Where to? "); - note, no ln, and a trailing space.
You did not check if the user input is valid, I would suggest starting off with the following:
check if userInput is a valid number (includes numeric characters).
check if userInput is larger or equal to 1.
your answer is ok but can be optimized to the beginners levels if that is what your teacher is expecting because:
you can get an int directly from scanner, no need to use the wrapper class Integer.
you can use another loop ... a for loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = scanner.nextInt();
System.out.println("ok!");
for (int i = 1; i <= userInput; i++)
{
System.out.println(i);
}
}
Just try by Removing
System.out.println("Where to?");
with
System.out.print("Where to?");

Character.isDigit parameters and line unavailable errors within the isDigit method (clarification)

I'm currently working on a small project for an introductory java class. We're supposed to make a program which can take in an integer from the user and output the number of odds, evens, and zeroes present within the code. This seemed pretty easy to me, and I managed to implement the code, but a class mate, after I criticized his code for incorrectly following the prompt, noted that my code would crash if anything but digits was input.
Out of spite I've tried to go beyond the prompt and have the program output an error message if it encounters characters aside from digits (instead of having my compiler return an error). However I'm returning multiple errors within the Eclipse compiler when using the isDigit method in the Character class.
I don't know exactly what's causing this, and I feel I must be missing something crucial, but my teacher quite frankly isn't qualified enough to understand what's causing the error, and none of my classmates can seem to figure it out either.
package ppCH5;
import java.util.Scanner;
public class PP5_3
{
public static void main(String[]args)
{
int even = 0;
int odd = 0;
int zero = 0;
int num = 0;
int count = 0;
boolean inputError = false;
System.out.println("please provide some integer");
Scanner scan = new Scanner(System.in);
String numbers = scan.next();
scan.close();
Scanner intSeperate = new Scanner(numbers);
intSeperate.useDelimiter("");
while(intSeperate.hasNext())
{
if(Character.isDigit(numbers.charAt(count)))
{
count++;
num = intSeperate.nextInt();
if((num % 2)==1)
odd++;
if((num % 2)==0)
if(num==0)
zero++;
else
even++;
}
else
{
count++;
inputError = true;
}
}
intSeperate.close();
if(!inputError)
{
System.out.println("There are " + even + " even digits.\n" + odd + " odd digits.\nAnd there are " + zero + " zeros in that integer.");
}
else
{
System.out.println("You have provided a disallowed input");
}
}
}
Any help would be appreciated, I'm currently at a loss.
When you enter a single non-digit character, say a, the else branch inside the while loop will get executed, incrementing count, right? And then the loop will start a new iteration, right?
In this new iteration, intSeparator.hasNext() still returns true. Why? Because the input a is never read by the scanner (unlike if you have entered a digit, intSeparator.nextInt would be called and would have consumed the input).
Now count is 1 and is an invalid index for the 1-character string. Therefore, numbers.charAt(count) throws an exception.
This can be avoided if you break; out of the loop immediately in the else block:
else
{
inputError = true;
break;
}
Also, don't close the scan scanner. scan is connected to the System.in stream. You didn't open that stream, so don't close it yourself.

How to store a value for later use? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am a new user and I have a "noob" question. We are being taught Java in school and I have a question about one of our activities. One requirement is to take in student info (such as course) and convert them to a single letter (I assume use .charAt??) and then later on count how many students are enrolled into that course. I have the student info down here:
import java.util.*;
import java.lang.*;
public class CourseTallier
{
public static void main (String[] args)
{
String student = inputStudInfo();
}
public static String inputStudInfo ()
{
Scanner kbd = new Scanner(System.in);
int limit = 0, idnum = 0;
String college = "";
System.out.println("Please input a valid ID number:");
idnum = Integer.parseInt(kbd.nextLine());
if (idnum == 0)
{
System.out.println("Thank you for using this program.");
System.exit(0);
}
while (idnum < limit) {
System.out.println("Invalid ID number. Please enter a positive integer:");
idnum = Integer.parseInt(kbd.nextLine());
}
System.out.println("Please enter a valid course (BLIS, BSCS, BSIS, or BSIT");
college = kbd.nextLine();
while(!college.equalsIgnoreCase("BLIS") && !college.equalsIgnoreCase("BSCS") && !college.equalsIgnoreCase("BSIS") && !college.equalsIgnoreCase("BSIT"))
{
System.out.println("Invalid course. Please enter either BLIS, BSCS, BSIS, or BSIT");
college = kbd.nextLine();
}
return college;
}
public static Character convertCourse (String college)
{
}
and as you can see I am stuck at the "Convert Course" method (modular is required). I was wondering how would I convert something like "BLIS" to a single character "L" and then create another method that counts the number of how many students are enrolled in that course.
I am not asking for someone to complete this program for me cause that would be cheating. I am simply asking someone for a shove in the right direction. Your help is very much appreciated.
Edit: As asked here are the exact requirements:
Program
To the storing for future values, do you know what instance variables are? Unless I misunderstood the question, it seems like it would make sense to make four (static) instance variables that hold the count of users enrolled in each course.
You could either use the .charAt method or use the "switch" statement.
the problem with the charAt method is that you probably can't find different letters for each course using the same indexed letter.(which will bring you to the switch statement again)
To count the number of student enrolled in that course you should have a count variable and increase it every time you convert a course into a single char.
One way would be to use a switch statement
switch(college)
{
case "BLIS":
return("a");
}
Not sure if thats really what your meant to be doing, if your meant to store student data then a Map implementing datastructure would be the go
Well, first of all you need to make your code more modular. How about dividing it into sections,like, getting user input, validating user input, storing user input.
Well to store the user data, you can use something like a HashMap. Keep course as key (eg BLIS) and no of students as value. In start intialize it with 0.
Map<String, Integer> studentCourseHashMap = new HashMap<String, Integer>();
studentCourseHashMap.put("BLIS", 0);
So, every time a user enrolls for the particular course all you need to do is to find the course and increment it by 1. So, for example if a student enrolled for BLIS course. then,
if(studentCourseHashMap.containsKey("BLIS")){
//Checking if BLIS course is available
Integer noOfStudents = studentCourseHashMap.get("BLIS");
//Increment no of students for each enrollment
noOfStudents++;
//Saving the updated value in hashmap
studentCourseHashMap.put("BLIS", noOfStudents);
}
Hope this will help, mention your doubts in comments. :)
why not use a counter for each course and increment it whenever the user enters it.
switch(college)
case BLIS:
blisCounter+=1;
break;
case BSCS:
bscsCounter+=1;
break;
case BSIS:
bsisCounter+=1;
break;
case BSIT:
bsitCounter+=1;
break;
If you want to take each letter from the string, here's the way:
String str = "BLIS";
String strArray[] = str.split("");
for (int i = 0; i < strArray.length; i++) {
System.out.println(strArray[i]);
}
If you want to map the Course String to individual Characters, below is the way:
Map<String, Character> courseMap = new HashMap<String, Character>();
courseMap.put("BLIS", 'L');
courseMap.put("BSCS", 'C');
courseMap.put("BSIS", 'S');
courseMap.put("BSIT", 'T');
for(String courseStr: courseMap.keySet()) {
System.out.println(courseStr + " > " + courseMap.get(courseStr));
}

Java -- How to make a continous counter (1 + 2 = 3; + 3 = 6) etc

I'm not sure if this is possible in Java. I just finished Python and I've taken a webdesign course, so my brain isn't synced with Java yet.
I want it to be something like this
double yourInput = input.nextDouble();
double numCount = (numCount + yourInput);
For example, if I entered 2, 7, and 9 (it would loop) I would want it to do something like this: numCount = 0; then numCount = 0 + 2; then numCount = 2 + 7; then numCount = 9 + 9.
Is this possible in Java? If so, how?
Just loop using input.hasNextDouble():
//give default value
double numCount = 0;
//while user is still giving input
while(input.hasNextDouble()) {
//get input
double yourInput = input.nextDouble();
//add input
numCount += yourInput;
}
//output
System.out.println("total = " + numCount);
Algorithm CONTINOUS_COUNTER()
BEGIN
DECLARE inputReader : java.util.Scanner(System.in);
DECLARE numCount : Double;
SET numCount := 0.0; //Setting the default value to the counter;
LOOP until inputReader.hasNextDouble() returns TRUE
numCount := numCount + inputReader.nextDouble();
END LOOP;
print "Num count = " + numCount;
END;
Dear Katy, this is the logic you should use to develop this program. This is just an algorithm. I don't think it's good to post the real program here, since you are learning Java. Try to convert this algorithm to the Java code. Learn it. :)
Here a working example:
import javax.swing.JOptionPane;
public class DoubleCounter {
private static double total = 0.0;
public static void run(){
while(true){
String input = JOptionPane.showInputDialog("Total Count: "+ total+" add next double: ");
try{
double next = Double.parseDouble(input);
total+=next;
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null, "Wrong input! You must get a valid number!");
continue;
}
}
}
public static void main(String[] args) {
DoubleCounter.run();
}
}
You define a class DoubleCounter with a static member total count.
This class has a run() method that infinitly loop and show ad InputDialog.
The input dialog alway return a string that we 'try' to parsed in a double.
If parsed without problem, we add the result to the total count.
The class has a main method that is the application entry point that 'statically' call run() method of DoubleCounter.
I suggest you to see how 'static' modifier work on class member (total) and on methods (run()).
Hope helped you!
Katy, this is the real program.
import java.util.Scanner;
public class ContinousCounter{
public static void main(final String [] args){
double numCount = 0.0;
Scanner inputReader = new Scanner(System.in);
System.out.println("Enter the values : ");
while(inputReader.hasNextDouble()){ numCount += inputReader.nextDouble();}
System.out.printf("The value for numCount = %f",numCount);
}
}
In order to do what I think you're saying here, you should be using a while loop. It is fairly simple, just think about how you want it to work. It will loop a block of code that adds the scanner's next line to a sum
double mySum = 0;
while(input.nextDouble() != 0){
double myInput = input.nextDouble();
mySum += myInput;
}
In the above loop, we are assuming that when the scanner's next line is 0 there are no more numbers to add, but that can be adjusted so that it stops at other times.
I can see that since you have completed a course in Python programming that you are able to come up with the logic for this and are only looking for convention or proper syntax, so let's explain how the above works:
A while loop will run as long as the statement you let it handle evaluates to true, if you want it to do something while false you can put use an exclamation point before your statement and encase your parameters in parentheses such as the following : while (!(x<=2))
A while loop has the following syntax (in logical form):
while (boolean) {run this code}
You can use the shorthand for adding myInput to your mySum:
+= will add the righthand side to the lefthand side and save that value
If you want to run the code at least once despite the value, you can use a do while loop. The logic behind it is: do {this} while (boolean);

Reading and compiling lines from JTextArea using conditional statements [duplicate]

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 9 years ago.
Good morning everyone, I'm a beginner student in java programming. So, direct to the point, I'm creating a program that can read and compile a .txt file with a click of a button.
I'm already done with the reading of the file. My problem is that my program doesn't compile the text from the first JTextArea and show the results to the second JTextArea.
I've been having this problem for four days now, I've been trying to change the code in any possible ways I can think of. Can someone enlighten me and tell me what's wrong with my code? It will surely help me a lot.
Many thanks to all.
#SuppressWarnings("IncompatibleEquals")
private void executeCodeActionPerformed(java.awt.event.ActionEvent evt) {
String loadi = "Load";
String add = "Add";
String subt = "Subt";
String mult = "Mult";
String div = "Div";
String input = "Input";
String print = "Print";
int number = 0;
String txt = textAreaCode.getText();
String split = " ";
String [] text = txt.split(split);
String word = text[0];
int num = Integer.getInteger(text[1]);
int result = num;
int result1 = 0;
Scanner scan = new Scanner(txt);
scan.nextLine();
for (int count=0;count<txt.length();count++ ) {
if (loadi.equalsIgnoreCase(word)){
result1 = num + number;
}
else if (add.equalsIgnoreCase(word)){
result1 = num + result;
}
else if (subt.equalsIgnoreCase(word)){
result1 = num - result;
}
else if (mult.equalsIgnoreCase(word)){
result1 = num * result;
}
else if (div.equalsIgnoreCase(word)){
result1 = num / result;
}
else if (print.equalsIgnoreCase(word)){
textAreaOutput.setText(String.valueOf(result1));
}
else if (input.equalsIgnoreCase(word)){
String nmbr = inputField.getText();
int nmr = Integer.parseInt(nmbr);
result1 = nmr + number;
}
}
I see a few errors in your code that might add up to not working at all. Here they are:
The variable word is never updated to the following tokens (it is set to text[0] at first then never changed). Same goes for num.
All operations act on variables num and result, then put the result into result1. So intermediate results are not carried from an operation to the next.
The "input" operation load current value from inputField, without waiting for the user to actually type something.
The main loop iterate until count reach the number of characters in the program; it should loop for the number of tokens instead.
Also, here are a few suggestions to make your code more ligible:
If you are beginning in Java, then get rid of the Scanner object, and keep only the "split on spaces" approach. I would not recommend this for real problems, but Scanner is somewhat complex to use correctly.
Wrap the splited words array into a List collection, then obtain an iterator from it. Here it is:
Iterator<String> words = Arrays.asList(txt.split("[ ]+")).iterator();
Then, write your loop as:
while (words.hasNext()) {
String command = words.next();
...
}
Move your operation mnemonics outside of the function, and mark them as final.
Read your operation arguments from inside each operation block; this is required because some operation do not receive arguments.
Well, I won't give you the code, as this is something you really have to do by yourself. Hope that helps. Good luck.

Categories