how to use value from the for-loop outside it java - java

import java.util.Scanner;
public class App {
public static void main(String[] args) {
double input;
double netto=0;
Scanner value = new Scanner(System.in);
for(int x=0;x<4;x++){
System.out.println("Please enter the number");
input = value.nextInt();
if(input>=300){
netto= input - input*0.30;
}
else {
netto =input- input*0.20;
}
}
netto=+netto;
System.out.println(netto);
}
}
i want that the code adds the results after subtracting part of them according to the entered value.
the problem is that the code saves the last result only and shows it.

Seems like you meant to accumulate the values into netto using += instead of overriding it with =:
for (int x = 0; x < 4; x++) {
System.out.println("Please enter the number");
input = value.nextInt();
if (input>=300) {
netto += input - input * 0.30; // Here
}
else {
netto += input - input * 0.20; // And here
}
}

Related

Take integer inputs till the user enters 0 and print the sum of all numbers (HINT: while loop) (coding language:- JAVA)

IN this problem we have to print the sum of all the numbers until the user enters zero.
my attempt:
import java.util.Scanner;
public class printsum_until_enter0 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
//int count = 0;
int x = in.nextInt();
while (x >0) {
if (x > 0) {
sum = sum + x;
System.out.println(sum);
x--;
} else {
System.out.println("no data was entered");
}
x--;
}
}
}
it runs infinitly before writing X--...but now it takes only one input and after that it is executed...but it supposed to execute after entering 0 and sum of all the numbers before entering 0. But it is not happeing.Any solution guys...Code in java..
Your problem is that you only ask the user for input once. What you want to do is move the scanner.nextInt part somehow into your loop. In java there is a concept called do while loop which executes the loop body first and then checks the loop condition if it should be repeated. If you do not want to use a do while loop you can use a while true loop to check if the input was 0 and exit. Notice also how x needs to be initialised before the function body to be recognized by the while statement
Unfortunately, I did not get why you decreased x in your code. Let me know if I misunderstood your question or you have any more questions
import java.util.Scanner;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int x = 0;
do {
System.out.println("Please insert a number: ");
x = in.nextInt();
// If x is 0 it wont change the sum
sum += x;
System.out.println(sum);
} while (x > 0);
System.out.println("no data was entered");
}
}
Fixed your code
package test1;
import java.util.Scanner;
public class printsum_until_enter0 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int x = in.nextInt();
while (x >0) {
if (x > 0) {
sum = sum + x;
} else {
System.out.println("no data was entered");
}
x = in.nextInt();
}
System.out.println(sum);
}
}
do {
x = in.nextInt();
if(x > 0) {
sum += x;
}
} while(x > 0)

How can I define a char variable within a method?

I'm attempting to write a loop, that when the user inputs Y, the loop continues, and when the user inputs N, the loop stops. However, when I try to assign the variable I get the error "Cannot convert from void to char" I'm obviously messing up somewhere along the line but I'm not sure where.
import java.util.Scanner;
public class SimpleList {
public static void main(String[] args) {
System.out.println("Welcome to the Simple List Class");
getData();
}
private static void getData() {
Scanner input = new Scanner(System.in);
float[] numbers = new float[10];
System.out.println("Enter a non-negative floating point value: ");
for(int i = 0; i < 10; i++) {
float x = input.nextFloat();
if (x > 0) {
numbers[i] = x;
char ans = System.out.print("Would you like to input another value? (Y or N)? ");
}
else {
System.out.println("That is not a valid. Try Again.");
}
}
System.out.println(Arrays.toString(numbers));
}
} ```
You're assigning ans to the result of System.out.print() which is a void method.
Instead, create the prompt beforehand and use the Scanner to take the input:
public class SimpleList {
public static void main(String[] args) {
System.out.println("Welcome to the Simple List Class");
getData();
}
private static void getData() {
Scanner input = new Scanner(System.in);
float[] numbers = new float[10];
System.out.println("Enter a non-negative floating point value: ");
for(int i = 0; i < 10; i++) {
float x = input.nextFloat();
if (x > 0) {
numbers[i] = x;
// New Prompt
System.out.print("Would you like to input another value? (Y or N)? ");
// Take input and set ans
char ans = input.next().charAt(0);
}
else {
System.out.println("That is not a valid. Try Again.");
}
}
System.out.println(Arrays.toString(numbers));
}
}

How to use try catch to replace invalid data of user input array instead of restarting code in Java?

Whenever invalid input is entered, such as a letter, the code starts from the beginning. How do I get it so that it keeps rebuilding the code from where invalid input was entered. I want it to kick out the invalid input, and prompt the user to re-enter a valid input, and keep building it.
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
int z = 1;
do {
try {
Scanner scanner = new Scanner(System.in);
double[] myArr1 = new double[10]; //Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x=0; x<myArr1.length; x++) {
myArr1[x] = scanner.nextDouble(); //Gets user input
} //end of for
double sum1 = 0;
for(double x=0; x<myArr1.length; x++) {
sum1 += myArr1[(int) x]; //Defines sum1
} //end of for
double[] myArr2 = new double[10]; //Creates array
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int y=0; y<myArr2.length; y++) {
myArr2[y] = scanner.nextDouble(); //Gets user input
} //end of for
double sum2 = 0;
for (double y=0; y<myArr2.length; y++) {
sum2 += myArr2[(int) y];
} //end of for
System.out.println("Sum of first 10 elements is: " + sum1); //Prints sum of first 10 elements
System.out.println("Sum of second 10 elements is: " + sum2); //Prints sum of last 10 elements
}/*end of try*/catch (Exception e) { //Catches errors in user input
System.out.println("Invalid input. Try again: ");
System.out.println("");
} //end of catch
}//end of do
while(z==1);
return;
}
}
You can craft a helper method for input. It will continually prompt with the messages provided until a correct type is entered. This tends to come in handy when inputs need to be taken from different locations within the program.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double v = nextDouble(input, "Please enter a value: ", "Improper type, try again: ");
System.out.println(v);
}
public static double nextDouble(Scanner input, String prompt, String error) {
System.out.print(prompt);
// loop forever
for(;;) {
try {
double v = input.nextDouble();
return v;
} catch (InputMismatchException ie) {
input.nextLine(); // clear input buffer
System.out.print(error);
}
}
}
Here is an example from your code.
Scanner scanner = new Scanner(System.in);
String prompt = "Please enter a number: ";
String error = "Invalid input, try again";
double[] myArr1 = new double[10]; // Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x = 0; x < myArr1.length; x++) {
myArr1[x] = nextDouble(scanner, prompt, error);
} // end of for
double sum1 = 0;
for (double x = 0; x < myArr1.length; x++) {
sum1 += myArr1[(int) x]; // Defines sum1
} // end of for
Get rid of your existing try/catch blocks. And I don't know why you have a do/while since you aren't looping more than once.
or you can using while loop and a boolean value to get a number
Scanner scanner = new Scanner(System.in);
boolean bool = true;
double d ;//= scanner.nextDouble();
while(bool){
try{
scanner = new Scanner(System.in);
d = scanner.nextDouble();
bool = false;
}catch(InputMismatchException e){
System.err.println("invalid input");
}
}
I've figured it out. I had to create a boolean, but also decrement the index of the array of where the bad input was being placed (i = i-1). I also made it just one array and set the first 10 values to x and the last 10 to y to make it a little bit simpler.
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
double[] array = new double[20]; //creates array
boolean on = true; //sets value "on"
while (on) { //starts while loop
System.out.println("Enter 20 numbers: ");
System.out.println("");
for (int i = 0; i < array.length; i++) { //creates user input prompt
Scanner input = new Scanner(System.in); //gets user input
try {
array[i] = input.nextDouble(); //assigns user input to array[i]
}/*end of try*/ catch (Exception e) { //catches invalid input
System.err.println("Invalid Input. Try again: ");
i = i - 1; //decrements index of re-entered number
} //end of catch
} //end of for
double x = 0;
for (int z = 0; z < 10; z++) {
x += array[z];
} //end of for
System.out.println("Sum of first 10 numbers = " + x); //adds first 10 numbers in array and assigns them to x
System.out.println("");
double y = 0;
for (int z = 10; z < 20; z++) {
y += array[z];
} //end of for
System.out.println("Sum of last 10 numbers = " + y); //adds last 10 numbers in array and assigns them to y
on = false; //breaks while loop
} //end of while
}
}

Using scanner input to make a for loop

I am trying to make a sort of ATM. I want the program to do the following: If a user enters a number, the number gets multiplied by 12.
I already have the following code:
import java.util.Scanner;
public class DisplayMultiples {
public static void main(String args[]) {
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
keyboardInput.nextLine();
int b = 12;
if() {
for (int i = 1; i < b; i++) {
System.out.println(i*b);
}
else {
System.out.println("Error, this value is never used");
}
}
}
Convert the input to a number.
If the input is not a number, show error message, and exit.
If the input is a number, multiply it by 12, show result, and exit.
The easiest way is to get an int from the Scanner and then check if it's between 1 and 12, and if so, multiply it by 12.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
int number = keyboardInput.nextInt();
if (number > 0 && number < 13) {
System.out.println(number * 12);
} else {
System.out.println("Error, this value is never used");
}
Note that as you are likely a beginner, entering anything but an int in the console will result in an error but I assume that's not entirely necessary for you. If it is, read up on try...catch.
This way will avoid exceptions when entering non numbers.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
String inpStr = keyboardInput.nextLine();
int b = 12;
int inpVal = -1;
try {
inpVal = Integer.parseInt(inpStr);
} catch (NumberFormatException nfe) {
}
if (inpVal >= 1 && inpVal <= 12) {
System.out.println(inpVal * b);
} else {
System.out.println("Error, this value is never used");
}

how do i repeatedly multiply a number in java by 2 until it reaches 1 million?

import java.util.Scanner;
class Main {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int testNumber = userInput.nextInt();
do{
System.out.println(newNumber * 2);
newNumber++;
}while( testNumber < 1000000);
}
}
You need to update the number after you multiply it by 2:
newNumber = newNumber * 2;
System.out.println(newNumber);
Also you are using newNumber and testNumber and newNumber doesn't appear to be defined anywhere...
}while( ***testNumber***newNumber*** < 1000000);
You need to pick one because if you are updating newNumber but comparing testNumber in your loop you will have created an infinite loop.
The code you have shown shouldn't compile unless you are leaving something out of your post.
You have the right idea with your loop, but you have multiple problems with your variables.
Your first problem is that you read in a variable from the user - testNumber, but then you are (incorrectly) manipulating a completely different variable - newNumber.
Your second problem is that you are testing the unchanged variable as your stop condition.
You probably want your loop to be something like:
do {
testNumber = testNumber * 2;
System.out.println(testNumber);
} while(testNumber < 1000000);
You can also make a recursive method for it.
public int reachMillion(int num) {
if(num<=0)
return -1; // indicating it is not possible.
if(num>=1000000) // Base Condition denoting we have reached 1 million
return num;
return reachMillion(num*2); // recursive part to multiply by 2 until we reach 1 million
}
class Main {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int newNumber = 0;
do{
System.out.println("Enter a positive number: ");
try{
newNumber = userInput.nextInt();
}catch(Exception ignored){ }
System.out.println("");
}while(newNumber <= 0);
System.out.println("----- " + newNumber + " multiply by 2 ------");
while(newNumber <= 1_000_000){
System.out.print("2 * " + newNumber +" = ");
newNumber <<= 1;//in some compilers left shift is faster than multiply
System.out.println(newNumber);
}
}
#brso05 has done well describing what went wrong here. I'd like to offer a complete example:
import java.util.Scanner;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Please input a number: ");
int userInputNumber = userInputScanner.nextInt();
System.out.println();
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
Beware! That code does not handle any bad user input. For instance, if you give it 0, it will loop forever, and if you give it foo, it will crash. In case you want to handle all the edge cases of user input, this will do that:
import java.util.*;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
int userInputNumber;
//
while(true) {
System.out.print("Please input a number: ");
if (userInputScanner.hasNext()) {
// The user gave us something, but we don't know if it's a number
String rawUserInput = userInputScanner.next();
try {
userInputNumber = Integer.parseInt(rawUserInput);
// If that previous line runs, the user has given us an integer!
System.out.println();
if (userInputNumber > 0) {
// The user has given a valid number. Break out of the loop and multiply it!
break;
}
else {
// The user has given a bad number. Tell them why and ask again.
System.out.println("The number has to be greater than 0.");
}
}
catch (NumberFormatException exception) {
// The user has given us something, but it wasn't an integer
System.out.println();
System.out.println("That is not a number: " + exception.getMessage());
}
}
else {
// There is no input, so we can't do anything.
return;
}
}
// Done looping through user input
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
There is a tricky part of do-while loops. In that type of loops, do part is executed firstly. For the example below, although the input is already bigger than 1000000, it prints 1000001.
public void doWhileLoop() {
int num = 1000001;
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}
Therefore, it will be a good idea to use some guard-clauses (aka, if-statements) before doing something in do-while loops. Like,
public void doWhileLoop() {
int num = 1000001;
if(num >= 1000000) {
return;
}
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}

Categories

Resources