Options method showing up twice after initial use when the loop repeats - java

import java.util.Scanner;
public class Calculator {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
String userInput1 = "";
//the do loop so i can go through all the options
do {
options();
userInput1 = userInput.nextLine();
if(userInput1.equals("add")){
System.out.println(calcAdd());
}
else if (userInput1.equals("subtract")) {
System.out.println(calcSub());
}
else if(userInput1.equals("multiply")){
System.out.println(calcMult());
}
else if(userInput1.equals("divide")){
System.out.println(calcDiv());
}
} while(!userInput1.equals("q"));
}
//options for the program
public static void options(){
System.out.println("add");
System.out.println("subtract");
System.out.println("multiply");
System.out.println("divide");
System.out.println("\"q\" to quit");
System.out.print("What do you want to do: ");
}
//addition method
public static int calcAdd(){
System.out.print("First number: ");
int x = userInput.nextInt();
System.out.print("Second number: ");
int y = userInput.nextInt();
int z;
z = x + y;
return z;
}
//subtraction method
public static int calcSub(){
System.out.print("First number: ");
int x = userInput.nextInt();
System.out.print("Second number: ");
int y = userInput.nextInt();
int z;
z = x - y;
return z;
}
//multiplication method
public static int calcMult(){
System.out.print("First number: ");
int x = userInput.nextInt();
System.out.print("Second number: ");
int y = userInput.nextInt();
int z;
z = x * y;
return z;
}
//division method
public static double calcDiv(){
System.out.print("First number: ");
double x = userInput.nextDouble();
System.out.print("Second number: ");
double y = userInput.nextDouble();
double z;
if (y == 0){
System.out.println("Sorry you can't do this");
} else {
z = x / y;
return z;
}
return 0;
}
}

Related

How to pass the validated user inputs to the method parameter?

I have two classes: MyNumbers and MyScanner. I am trying to pass the validated inputs to the calculateSum (int x, int y) method in order to print the final result in the MyScanner class, but I don't know how I can take the user inputs from the MyScanner class to pass them to the validate() method in the MyNumbers class so that it allows the calculateSum() method to perform its task.
P.S. validate() method should be void and parameterless, but calculateSum() method should be string to return the result as a string and take two parameters. I also want the validate() method to prompt for user input and validate the values to make sure that they are in the certain range. This method needs to keep prompting until user inserts a valid number.
How can I achieve this without introducing another variable/implementing setters/ passing variables as a parameter to the validate() method?
public class MyNumbers {
int number1;
int number2;
public void validate() {
if (number1 >= 10 && number1 <= 50) {
if(number2 >= 5 && number2 <= 20){
System.out.println(calculateSum(number1, number2));
}
}
else {
System.out.println("Number should be between 10 and 50");
}
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
validate();
return "Sum: " + number1 + number2;
}
}
public class MyScanner {
public static void main(String[] args) {
MyNumbers myNumbers = new myNumbers();
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
do{
switch(option){
case 1:
System.out.println("Enter number 1");
int x = scanner.nextInt();
System.out.println("Enter number 2");
int y = scanner.nextInt();
myNumbers.calculateSum(x, y);
break;
}
}
while(option!=0);
}
}
EDIT :
import java.util.*;
class MyNumbers {
int number1;
int number2;
public void validate() {
int valid=0;
int x;
int y;
Scanner s = new Scanner(System.in);
System.out.println("Welcome!");
do{
System.out.println("Enter Number 1: ");
x = s.nextInt();
if (x >= 10 && x <= 50) {
valid=2;
}
else {
System.out.println("Number 1 should be between 10 and 50");
}
}while(valid!=2);
do {
System.out.println("Enter Number 2: ");
y = s.nextInt();
if(y >= 5 && y <= 20){
System.out.println(calculateSum(x, y));
valid=3;
}
else {
System.out.println("Number 2 should be between 5 and 20");
}
}while(valid!=3);
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
return "Sum: " + (number1 + number2);
}
}
public class Main {
public static void main(String[] args) {
MyNumbers myNumbers = new MyNumbers();
myNumbers.validate();
}
}
Try
import java.util.*;
class MyNumbers {
int number1;
int number2;
public void validate(int number1 , int number2) {
if (number1 >= 10 && number1 <= 50) {
if(number2 >= 5 && number2 <= 20){
System.out.println(calculateSum(number1, number2));
}
}
else {
System.out.println("Number should be between 10 and 50");
}
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
return "Sum: " + number1 + number2;
}
}
public class Main {
public static void main(String[] args) {
MyNumbers myNumbers = new MyNumbers();
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
switch(option){
case 1:
System.out.println("Enter number 1");
int x = scanner.nextInt();
System.out.println("Enter number 2");
int y = scanner.nextInt();
myNumbers.validate(x, y);
myNumbers.calculateSum(x, y);
break;
}
}
}

How do I pass the user inputs to a constructor in a different class?

My professor told me that I have to Design a class "SharePattern" that has the following two fields: "numberOfDaysInPeriod" and
"SharePointsOnFirstDay".
The class should have a constructor to set the values of these two fields.
In a separate class he said to get user input in the main of my other class. So what goes into the constructor?
First class:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner more = new Scanner(System.in);
System.out.print("Number of days in the period: ");
int input1 = more.nextInt();
while(input1 < 10 || input1 > 20)
{
System.out.println("The number of days that is entered must not be less than 10 and more than 20. The number of days doesn't meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
input1 = more.nextInt();
}
System.out.print("Share points on the first day: ");
int input2 = more.nextInt();
int half = input1 / 2;
more.close();
SharePattern sp = new SharePattern(input1, input2, half);
sp.findFinalDaySharePoints(input1, input2, half);
}
}
2nd class:
package hw4Question2;
public class SharePattern {
public SharePattern(int input1, int input2, int half)//constructor
{
}
public void findFinalDaySharePoints(int input1, int input2, int half)
{
System.out.println(input2);
if(input1%2 == 0) {
for(int i = 1; i <= input1 ; ++i)
{
if(i<half)
{
input2 = input2 + 50;
System.out.println(input2);
}
else if(i>half)
{
input2 = input2 - 25;
System.out.println(input2);
}
}
}
else
{
for(int i = 1; i <= input1 ; ++i)
{
if(i<=half)
{
input2 = input2 + 50;
System.out.println(input2);
}
else if(i>half)
{
input2 = input2 - 25;
System.out.println(input2);
}
}
System.out.println("The final share value is "+input2);
}
}
}
First class
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner more = new Scanner(System.in);
System.out.print("Number of days in the period: ");
int input1 = more.nextInt();
while(input1 < 10 || input1 > 20)
{
System.out.println("The number of days that is entered must not be less than 10 and more than 20. The number of days doesn't meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
input1 = more.nextInt();
}
System.out.print("Share points on the first day: ");
int input2 = more.nextInt();
int half = input1 / 2;
more.close();
SharePattern sp = new SharePattern(input1, input2);
sp.findFinalDaySharePoints(half);
}
SharePattern.class
int numberOfDaysInPeriod;
int sharePointsOnFirstDay;
public SharePattern(int input1, int input2) {
this.numberOfDaysInPeriod = input1;
this.sharePointsOnFirstDay = input2;
}
public void findFinalDaySharePoints(int half)
{
System.out.println(sharePointsOnFirstDay);
if(numberOfDaysInPeriod %2 == 0) {
for(int i = 1; i <= numberOfDaysInPeriod; ++i)
{
if(i<half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay + 50;
System.out.println(sharePointsOnFirstDay);
}
else if(i>half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay - 25;
System.out.println(sharePointsOnFirstDay);
}
}
}
else
{
for(int i = 1; i <= numberOfDaysInPeriod; ++i)
{
if(i<=half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay + 50;
System.out.println(sharePointsOnFirstDay);
}
else if(i>half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay - 25;
System.out.println(sharePointsOnFirstDay);
}
}
System.out.println("The final share value is "+ sharePointsOnFirstDay);
}
}

Play again feature issue

The program works the way it should but gets user's input on whether they want to play again or not and then does nothing after that. I am setting all of the original input values to 0 which is probably why. How can I get a new input from the user when they want to play again. If someone knows a better way make this program without arrays I would greatly appreciate it if you could post the code below.
import java.util.Scanner;
import java.util.*;
public class Shapes {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("You can view any of the following shapes: ");
System.out.print("\n1 Square");
System.out.print("\n2 Right-angle Triangle");
System.out.print("\n3 Pyramid");
System.out.print("\n4 Hourglass");
System.out.print("\n5 Diamond");
System.out.print("\nEnter a integer to choose a shape: ");
String shape = userInput.nextLine();
System.out.print("\nEnter the height of the shape: ");
int inputOne = userInput.nextInt();
System.out.print("Enter a character: ");
char ch = userInput.next().charAt(0);
System.out.println("\n");
do {
if (shape.equalsIgnoreCase("1")) {
square(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("2")) {
triangle(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("3")) {
pyramid(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("4")) {
diamond(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("5")) {
hourglass(ch, inputOne);
System.out.println();
}
shape = "0";
inputOne = 0;
ch = 0;
} while (playAgain());
}
private static boolean playAgain() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Play again? (Y/N): ");
String replay = keyboard.nextLine();
return replay.equalsIgnoreCase("Y");
}
public static void square(char c, int n) {
char[] a = new char[n];
Arrays.fill(a, c);
for (; n-- > 0;)
System.out.println(a);
}
public static void triangle(char c, int n) {
for (int i = 1; i <= n; i++) {
char[] a = new char[i];
Arrays.fill(a, c);
System.out.println(a);
}
}
public static void pyramid(char c, int n) {
for (int i = 0; i < n; i++) {
while (true) {
char[] s = new char[n - i - 1];
Arrays.fill(s, ' ');
System.out.print(s);
char[] a = new char[i * 2 + 1];
Arrays.fill(a, c);
System.out.println(a);
}
}
}
public static void diamond(char c, int n) {
boolean odd = n % 2 == 1;
n++;
int mid = n / 2;
int mi = mid;
if (odd)
mi--;
for (int y = 1; y < n; y++) {
for (int x = 1; x < n; x++) {
System.out.print((Math.abs(x + y - n) > mi || Math.abs(x - y) > mi) ? ' ' : c);
}
System.out.println();
}
}
public static void hourglass(char c, int n) {
boolean odd = n % 2 == 1;
if (odd)
n++;
int mid = n / 2;
for (int y = 0; y < n; y++) {
if (odd && y == mid)
continue;
for (int x = 1; x < n; x++) {
int a = 0;
if (Math.abs(x + y - mid) >= mid)
a++;
if (Math.abs(x - y - mid) >= mid)
a++;
System.out.print((a % 2 == 0) ? c : ' ');
}
System.out.println();
}
}
}
You only prompt the user for input once and you set them to 0. On the next iteration of the loop, shape is 0 so none of the if statements evaluate to true and thus your program does nothing.
Retrieve the user's input inside the loop and remove zeroing-out the variables:
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
do {
System.out.print("You can view any of the following shapes: ");
System.out.print("\n1 Square");
System.out.print("\n2 Right-angle Triangle");
System.out.print("\n3 Pyramid");
System.out.print("\n4 Hourglass");
System.out.print("\n5 Diamond");
System.out.print("\nEnter a integer to choose a shape: ");
String shape = userInput.nextLine();
System.out.print("\nEnter the height of the shape: ");
int inputOne = userInput.nextInt();
System.out.print("Enter a character: ");
char ch = userInput.next().charAt(0);
System.out.println("\n");
if (shape.equalsIgnoreCase("1")) {
square(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("2")) {
triangle(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("3")) {
pyramid(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("4")) {
diamond(ch, inputOne);
System.out.println();
}
if (shape.equalsIgnoreCase("5")) {
hourglass(ch, inputOne);
System.out.println();
}
} while (playAgain());
}
You need to prompt for the user input inside of the do/while loop. Right now you are prompting the user right above the loop - so it only happens once in your code.
//move this stuff into the do/while
Scanner userInput = new Scanner(System.in);
System.out.print("You can view any of the following shapes: ");
System.out.print("\n1 Square");
System.out.print("\n2 Right-angle Triangle");
System.out.print("\n3 Pyramid");
System.out.print("\n4 Hourglass");
System.out.print("\n5 Diamond");
System.out.print("\nEnter a integer to choose a shape: ");
String shape = userInput.nextLine();
System.out.print("\nEnter the height of the shape: ");
int inputOne = userInput.nextInt();
System.out.print("Enter a character: ");
char ch = userInput.next().charAt(0);
System.out.println("\n");
do {
^^^^ move that stuff in here
}while(playAgain())
It's also worth noting that this would be easy to discover if you simply step through your code in a debugger.

I don't know how to fix this

I have this assignment I have to do.. and I don't know how to fix the problem so that my program will work.
import java.util.Scanner;
public class Work6{
public static void main (String[] args){
String x;
String y;
Scanner in = new Scanner(System.in);
System.out.println("Number 1: ");
x = in.nextLine();
System.out.println("Number 2: ");
y = in.nextLine();
if (x > y){
System.out.println("Bigger number: " + x);
}
else if (y > x){
System.out.println("Bigger number: " + y);
}
}
}
Basically I have to write a program that asks for two numbers and then tells me which one is bigger. Can you just please tell me what am I doing wrong?
Thanks, Eva
change x and y to int:
import java.util.Scanner;
public class Work6{
public static void main (String[] args){
int x;
int y;
Scanner in = new Scanner(System.in);
System.out.println("Number 1: ");
x = in.nextInt();
in.nextLine();
System.out.println("Number 2: ");
y = in.nextInt();
in.nextLine();
if (x > y){
System.out.println("Bigger number: " + x);`
}
else if (y > x){
System.out.println("Bigger number: " + y);
}
}
}
Just use in.nextInt() instead of in.nextLine(). It will return an int instead of a string!
You are scanning strings and then you compare its memory locations, to see which one is larger...
What you need to do is, to scan numbers not strings, and it will work:
import java.util.Scanner;
public class Work6{
public static void main (String[] args){
int x;
int y;
Scanner in = new Scanner(System.in);
System.out.println("Number 1: ");
x = in.nextInt();
System.out.println("Number 2: ");
y = in.nextInt();
if (x > y){
System.out.println("Bigger number: " + x);`
}
else if (y > x){
System.out.println("Bigger number: " + y);
}
}
}
You should read more about primitives and objects and how to compare them.
EDIT
It can also be shorter:
public static void main (String[] args){
int x;
Integer y;
Scanner in = new Scanner(System.in);
System.out.println("Number 1: ");
x = in.nextInt();
System.out.println("Number 2: ");
y = in.nextInt();
System.out.println(x > y ? "Bigger number: " + x :
x == y ? "They are equal" : "Bigger number: " + y);
}
EDIT 2:
You can still use strings if you want, but you need to create Integer out of it:
String x;
String y;
Scanner in = new Scanner(System.in);
System.out.println("Number 1: ");
x = in.nextLine();
System.out.println("Number 2: ");
y = in.nextLine();
int xInt = new Integer(x);
int yInt = new Integer(y);
System.out.println(xInt > yInt ? "Bigger number: " + x : x == y ? "They are equal" : "Bigger number: " + y);
What this code does, it reads lines and then you try to create Integer from it. If its not a valid Integer, Exception will be thrown here, so be careful with this. Also, its unboxed to int, I would recommend you to read more about it.

How to print the array index of an object class?

I have a somewhat big code and I'm triying to print the slot number of an array from an object class that resulted to be the one with the highest weight.
On my main I have declared my array like this:
Car x[] = new car[2];
Now when triying to get which car has the highest weight I've made this validation inside a for loop
//.getweight obtains the weight of each car
if(x[i].getWeight() > max){
max = x[i].getWeight();
}
That code gives me the actual weight number of the heaviest car, but what I want to print is the actual car number. The comparing works but I can't find a way to just print the slot that corresponds to the heaviest car.
UPDATE with full code:
My object car:
public class Car
{
private String color;
private int weight;
private int state;
private int fuel;
private int Maxspeed ;
private int engine;
public Car(){
this.color = "White";
this.weight = 1000;
this.state = 0;
this.fuel =0;
this.Maxspeed = 0;
this.engine = 0;
}
public Car( String color, int weight,
int state, int fuel, int Maxspeed
){
this.color = color;
this.weight = weight;
this.state = state;
this.fuel = fuel;
this.Maxspeed = Maxspeed;
}
public String getColor(){
return this.color;
}
public int getweight(){
return this.weight;
}
public int getstate(){
return this.state;
}
public int getfuel(){
return this.fuel;
}
public int getMaxspeed(){
return this.Maxspeed;
}
public int getengine(){
return this.engine;
}
public void setColor( String color ){
this.color = color;
}
public void setweight( int weight ){
this.weight = weight;
}
public void setstate( int state ){
this.state = state;
}
public void setfuel( int fuel ){
this.fuel = fuel;
}
public void setMaxspeed( int Maxspeed ){
this.Maxspeed = Maxspeed;
}
public void setengine(int engine){
this.engine = engine;
}
public void showdata(){
System.out.println( "\nCar's color is: " + this.getColor() );
System.out.println( "Car's weight is: " + this.getweight() );
System.out.println( "State: " + this.getstate() );
System.out.println( "Fuel: " + this.getfuel());
System.out.println( "Max speed: " + this.getMaxspeed());
}
public void accelerate( int speed ){
if( this.getstate() == 0 ||
this.getstate() == 3 ||
this.getstate() == 4 ||
this.getMaxspeed() < speed )
{
System.out.println("\nCar cannot accelerate...");
}
else{
System.out.println("\nCar is accelerating...");
this.setfuel(this.getfuel()-2);
this.setstate(2);
if( this.getfuel() <= 0 ){
this.setstate(4);
}
}
}
public void crash(){
this.setstate(3);
System.out.println("\nCrash!!!");
}
public void stop(){
this.setstate(1);
System.out.println("\nCar has stopped.");
}
public void addfuel(int fuel){
if(this.getstate() == 0 || this.getstate() == 4){
this.setfuel(this.getfuel()+ fuel);
}
else{
System.out.println("You can't add fuel.");
}
}
public void repair(){
if(this.getstate() == 3){
this.setstate(1);
System.out.println("The car has been repaired");
}
else{
System.out.println("The car is not broken");
}
}
}
My Main:
import java.util.Scanner;
public class aaa{
public static void main (String args []){
Car x[] = new Car[2];
int keep=1;
int counter = 0;
int counter_stopped = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int maxIndex = 0;
int maxweight = 0;
int index_engine = 0;
int min_engine = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i < x.length; i++){
String color;
int weight;
int fuel;
int Maxspeed;
int engine;
x[i] = new Car();
System.out.print("\nEnter car color " + (i + 1) + ": ");
color = input.next();
System.out.print("Enter car weight " + (i + 1) + ": ");
weight = input.nextInt();
System.out.print("Enter car fuel " + (i + 1) + ": ");
fuel = input.nextInt();
System.out.print("Enter car max speed " + (i + 1) + ": ");
Maxspeed = input.nextInt();
System.out.print("Enter car engine weight " + (i + 1) + ": ");
engine = input.nextInt();
x[i].setColor(color);
x[i].setweight(weight);
x[i].getstate();
x[i].setfuel(fuel);
x[i].setMaxspeed(Maxspeed);
x[i].setengine(engine);
}
for(int i = 0; i < x.length; i++){
int state;
System.out.print("\nEnter car state " + (i + 1) + ": ");
state = input.nextInt();
x[i].setstate(state);
while(state > 4 || state < 0){
System.out.print("state not valid.\nTry again: ");
state = input.nextInt();
x[i].setstate(state);
}
do {
keep = menu();
switch( keep ){
case 1:
accelerate(x[i]);
break;
case 2:
stop(x[i]);
break;
case 3:
crash(x[i]);
break;
case 4:
addfuel(x[i]);
break;
case 5:
repair(x[i]);
break;
case 6:
x[i].showdata();
}
} while(keep != 7);
if(x[i].getstate() == 4 || x[i].getfuel() <= 0){
counter += 1;
}
if(x[i].getstate() == 1){
counter_stopped += 1;
}
int weight = x[i].getweight();
if(weight > max){
maxweight = weight;
maxIndex = i;
}
int weightengine = x[i].getengine();
if(weightengine < min){
min_engine = weightengine;
index_engine = i;
}
}
System.out.println("\nSUMMARY");
System.out.println("Amount of cars with no fuel: " + counter);
System.out.println("Amount of stopped cars: " + counter_stopped);
System.out.println("Heaviest car: " + maxIndex);
System.out.println("Car with the smallest engine: " + index_engine);
System.out.println("=============================================");
}
public static int menu(){
int option = 0;
Scanner s = new Scanner(System.in);
System.out.println("\n1. Accelerate Car ");
System.out.println("2. Stop Car ");
System.out.println("3. Crash Car ");
System.out.println("4. Add fuel ");
System.out.println("5. Repair ");
System.out.println("6. Show data ");
System.out.println("7. Exit ");
System.out.println("=============================================");
System.out.print("Choose an option : ");
option = s.nextInt();
System.out.println("=============================================");
return option;
}
public static void accelerate(Car myCar){
Scanner input = new Scanner(System.in);
int s;
System.out.print("Enter speed: ");
s = input.nextInt();
myCar.accelerate(s);
//myCar.showdata();
}
public static void stop(Car myCar){
myCar.stop();
}
public static void crash(Car myCar){
myCar.crash();
}
public static void addfuel(Car myCar){
int fuel;
Scanner input = new Scanner(System.in);
System.out.print("Amount to add: ");
fuel = input.nextInt();
myCar.addfuel(fuel);
}
public static void repair(Car myCar){
myCar.repair();
}
}
Now, when I compile and test which engine or car is smaller or heaviest I get the number 1 as result.
The array index would be i
The actual car would be x[i]
You need to hold on to a reference to the index to the heaviest car. In this example I am using maxIndex.
float maxWeight = 0;
int maxIndex = 0;
for (int i = 0; i < x.length; i++) {
float weight = x[i].getWeight();
if (weight > max) {
maxWeight = weight;
maxIndex = i;
}
}
System.out.println("Slot of heaviest car: " + maxIndex);

Categories

Resources