How to pass information with a get properly in java - java

I new to java, still trying to get down arguments and passing info. I am writing a blood pressure program for school and have some issue passing info from one class to another.
I have a fully functioning system to take in the user info in one class and have to set up another to check if the average is above or below range. Now, the range is easy, but the passing of info is another thing.
So, here's the code i wrote. the ONLY thing I'm worried about is the very last part, the 'getSystolic' and its return. I need to send the info to another part of the program not in main or in this PressueInput (its BPChecker btw) and just banging my head against the problem.
Thank you for the input:
` import java.util.Scanner;
public class PressureInput
{
private int sysInput;
private int diaInput;
private int sysAvrg;
private int diaAvrg;
public PressureInput()
{
sysInput = 0;
diaInput = 0;
sysAvrg = 0;
diaAvrg = 0;
}
public void setSysPressure()
{
sysInput = 0;
while(sysInput <= 0 || sysInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
sysInput= cin.nextInt();
System.out.println("You have entered " + sysInput + "\n");
if(sysInput <=0 || sysInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
sysAvrg += sysInput;
}
public int getSysPressure()
{
return sysInput;
}
public void setDiaPressure()
{
diaInput = 0;
while(diaInput <= 0 || diaInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
diaInput= cin.nextInt();
System.out.println("You have entered " + diaInput + "\n");
if(diaInput <=0 || diaInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
diaAvrg += diaAvrg;
}
public int getDiaPressure()
{
return diaInput;
}
public void sysAvrgRead()
{
sysAvrg = sysAvrg / 3;
System.out.println("\n" + "The systolic averge is " + sysAvrg);
}
public void diaAvrgRead()
{
diaAvrg = diaAvrg / 3;
System.out.println("The diastolic averge is " + diaAvrg + "\n");
}
public void setSystolic(int sys)
{
sysAvrg = sys;
}
public int getSystolic()
{
return sys;
}
} `

If you have a funftion in the class, that exhibits the var, then it should be fine. You need to make PressureInput a object, with PressureInput varnamePI = new PressureInput();
Then, access the var through varnamePI.sysAvrg=0; or so...

Related

How do I exit a for or a while loop with user input in java

import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("-------Welcome to the Radius calculator-------");
String input = new String (" ");
while(input.equals("END")==false) {
for (int i = 1; i < 5; i++)
for (int e = 5; e > 0; e--)
{
{
System.out.println("-----------------------------");
System.out.println("Hey you can use this calcultor " + e + " more time(s) till yoh have to purchase our full version only 3.99");
}
System.out.println("Please enter your Radius if not just type in END at any stage during the program");
Double num =sc.nextDouble();
System.out.println("Enter 1 if you would like to get the area");
System.out.println("Enter 2 if you would like to get the circumfrence");
int num1 = sc.nextInt();
if (num1 == 1) {
System.out.println("The area of the circle with the radius " + num + " is :" + (Math.PI) * (num * num));
} else if (num1 == 2) {
System.out.println("The circumfrence of the circle with the radius " + num + " is :" + (2) * (Math.PI) * (num));
} else {
System.out.println("No answer for you boss");
System.out.println("Try again!");
}
System.out.println("You have used this calculator effiently " + i + " time(s)");
System.out.println("-----------------------------");
}
}
}
}
Heres my code it works but when i type in END an ERROR comes up.(https://i.stack.imgur.com/ZZxEW.png)](https://i.stack.imgur.com/ZZxEW.png)
If theres any othere tips to make my code for effecient would be much appriciated too.
You forgot to ask for the end input during the loops.
The best way to ask for an input of different types is to use BufferedReader Class
BufferedReader reader =new BufferedReader(newInputStreamReader(System.in));
String input = null;
try {
input = reader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
if (input.equals("END")) {
break;
}
After that you can use :
Integer.parseInt(input);
to cast from String to Integer
And don't forget to clean and simplify your code.

Store array at runtime

I am an absolute beginner in programming and am facing my first big tasks.
The task is a warehouse management. All newly entered boxes should be stored in an array at runtime.
The problem is that I can create a new chest, but it will be overwritten or not saved.
My idea is that I call the run function every time an entry was successful.
import java.util.Arrays;
public class lager {
static int parser (String value) {
if (value == null) {
return -1;
} else {
return Integer.parseInt(value);
}
}
static void run (int[][]chests, int chestAmount, int maxStorage) {
//Fallunterscheidung
String option = JOptionPane.showInputDialog("What do you want to do (Type: 1-5)? \n" +
"\n" +
" 1 - Create chest \n" +
" 2 - Delete chest \n" +
" 3 - Change chest \n" +
" 4 - Show chest \n" +
" 5 - Show all");
System.out.println(chestAmount);
int optionParsed = parser(option);
if (optionParsed > 5){
System.out.println("Input incorrect or process aborted!");
run(chests, chestAmount, maxStorage);
} else if (optionParsed < 1){
System.out.println("Input incorrect or process aborted!");
return;
} else {
if (optionParsed == 1){
boolean response = create(chests, chestAmount, maxStorage);
if (!response){
System.out.println("Input incorrect or process aborted!");
} else {
System.out.println("Process successfully completed!");
}
} else if (optionParsed == 2){
boolean response = delete(chests, chestAmount, maxStorage);
if (response){
System.out.println("Input incorrect or process aborted!");
} else {
System.out.println("Process successfully completed!");
}
}
}
run(chests, chestAmount, maxStorage);
}
static boolean create (int[][]chests, int chestAmount, int maxStorage){
if (chestAmount > maxStorage - 1) {
System.out.println("The storage is already full!");
return false;
} else {
int length = Integer.parseInt(JOptionPane.showInputDialog("How long is the chest in centimeters? (e.g. 115)"));
int width = Integer.parseInt(JOptionPane.showInputDialog("How wide is the chest in centimeters? (e.g. 115)"));
int height = Integer.parseInt(JOptionPane.showInputDialog("How high is the chest in centimeters? (e.g. 115)"));
//THIS IS PROBABLY WHERE THE ERROR OCCURS
chests[chestAmount] = new int[]{length, width, height};
chestAmount++; //Count up help variable
System.out.println(chestAmount);
System.out.println("Stock " + chestAmount + " / " + maxStorage);
System.out.println(Arrays.toString(chests[chestAmount - 1]));
return true;
}
}
static boolean delete (int[][]chests, int chestAmount, int maxStorage){
String removeChest = JOptionPane.showInputDialog("Which chest do you want to delete? 1 - " + chestAmount);
int removeChestParsed = parser(removeChest);
if (removeChestParsed > chestAmount || removeChestParsed < 1){
System.out.println("Chest not available.");
return false;
} else {
chestAmount--;
chests[removeChestParsed - 1] = chests[chestAmount];
chests[chestAmount] = null;
return true;
}
}
public static void main(String[] args) {
int maxStorage = 75;
int[][] chests = new int[maxStorage][3]; //TODO: Wert 75 dynamisch anpassbar -- Fertig
//Hilfsvariable
int chestAmount = 0;
run(chests, chestAmount, maxStorage);
}
}
The problem was fixed. After I defined the variable chestAmount in the class Lager and not in the main method, everything went as desired.

Java multiplication using Recursion

I am writing a simple code in Java that is using recursion. I want to show the product of two numbers that a user will enter. I managed to do that using recursion, but stuck at the point where I want to show that the product could be written as (example) 10*5 = 5+5+5+5+5+5+5+5+5+5 (10 times), or 12*3 = 3+3+3+3+3+3+3+3+3+3+3+3 (12 times). Here is my code so far. In the code i put a comment where it should be written (example). Thanks.
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a, b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.println("The product of " + a + " and "
+ b + " is: " + multiRec(a, b));
System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
return x + (multiRec(x, y - 1));
}
}
}
}
A StringBuilder should be defiend as
StringBuilder buf = new StringBuilder (a);
Pass this StringBuilder paramater into multiRec
and then change multiRec to be
public static int multiRec(int x, int y, StringBuilder buf) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
buf.append (" + ").append (x);
return x + (multiRec(x, y - 1, buf));
}
}
}
}
Then when completed simply printout its value
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a , b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.printf("%d %s %d %s",a , "*" , b ,"= ");
System.out.println("\nThe product of " + a + " and "
+ b + " is: " + multiRec(b, a));
// System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
System.out.print(x+" ");
if (y == 1) {
return x;
} else {
System.out.print(" + ");
return x + (multiRec(x, y - 1));
}
}
}
}

Java Unexpected Programming Result

I would like to write a game about who would take the last marble and I've successfully run it. But when I attempted to add some error messages to it, such as showing "Incorrect range" when the inputs are out of range, it doesn't work properly. I know the problem is due to the incorrect recognition of variable "totalNum", but how to solve it? Thanks in advance :)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int pn = 1;
System.out.print("Intial no. of marbles [10 ~ 100]: ");
int totalNum = in.nextInt();
int input = 0;
int from = 1;
int to = totalNum/2;
if (totalNum < 10||totalNum > 100) {
System.out.println("Incorrect range. Try again!");
System.out.print("Intial no. of marbles [10 ~ 100]: ");
totalNum = in.nextInt();
}
else {
while (totalNum > 1) {
totalNum = in.nextInt();
System.out.print("Player" + pn + " [" + from + " ~ " + to + "]: ");
input = in.nextInt();
if (input < from||input > to) {
System.out.println("Incorrect range. Try again!");
continue;
}
totalNum = totalNum - input;
System.out.println("Remaining no. of marbles: " + totalNum);
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
}
}
System.out.println("Player" + pn + " takes the last marble.");
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
System.out.println("Player" + pn + " wins!");
}
I imagine this line in the while loop is the problem:
totalNum = in.nextInt();
It keeps trying to take the next input from the user but there isn't a second integer. Not sure what happens after that.
Also, your entire program seems to be roughly equivalent to doing
totalNum%2+1
and printing the answer.

Storing user input to an array java

I know this question have been asked a lot of times, but I still could not solve the problem. The problem is that I have to store an user input and print out a value.
For example, there are 4 people, person1, person2, person3 and person4. If I vote for person1, the vote number of person1 becomes 1 and the others remain 0. Then if I vote for person2, the vote number of person2 becomes 1 and person1 is also 1.
I can compile the code. But then if I vote for person1, the output becomes 4. and if I then vote for person2, the output of person2 becomes 4 and vote for person1 went back to 0. I am a complete beginner in programming and got stuck at this program for 4 whole days so any help is greatly appreciated. Thank you very much in advance.
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
public static void main (String[] args)
{
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Initialize String Arrays
String[] person = new String[4];
person[0] = "person1";
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
int[] votescount = new int[4];
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
int i;
for (i=0; i<votescount.length; i++)
{
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
} // end for loop
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
When you do this:
for (i=0; i<votescount.length; i++){...
} // end for loop
The loop happens 4 times. This means that this bit is happening 4 times:
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
which means the vote count goes up by 4!
get rid of your for loop:
for (i=0; i<votescount.length; i++)
and make persons and votescount global and static.
This is the updated code:
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
static String[] person = new String[4];//these have been made global and static
static int[] votescount = new int[4];
public static void main (String[] args)
{
// Initialize String Arrays
person[0] = "person1";//these have been moved so that it is only called once
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
System.out.println(answer);
int i;
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
First you do,
int[] votescount = new int[4];
then, you do
for (i=0; i<votescount.length; i++)
{
}
So, that loop iterates 4 times.
and inside the loop, you do,
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
and that's why, your count is up by 4!

Categories