How to remove the dot? - java

I started to study JAVA, So sorry for the question.. I practice the WHILE LOOP, so I have this code:
import java.util.Scanner;
public class Class {
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
double n = 0;
while ( n < 10 )
{
System.out.println( (n+1) + "." + message );
n++;
}
}
}
so, I want to get a result somthing like that: 10. 20. 30. and etc..
but I get: 1.0. , 2.0., 3.0. and etc..
what I should do to remove this dot, between 1 and 0...? thank you very much for your help :).

Use int instead of double for n variable:
int n = 0;

Well, a quick fix to your problem would be first changing the data type to int, so int n = 0; then simply add "0." to your print statement, so it looks like:
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
int n = 0;
while ( n < 10 ) {
System.out.println( (n+1) + "0." + message );
n++;
}
}
}
Or, alternatively, you could do int n = 10 and have your while loop condition aswhile( n < 100 ) then increment n by ten (n+=10;). So now it would look like:
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
int n = 10;
while ( n < 100 ) {
System.out.println(n + "." + message);
n+=10;
}
}
}

you can increment in 10s by multiplying n by 10, Also you might want to use int type rather than double to remove the decimal point.
int n = 1;
while ( n <= 10 )
{
System.out.println( ( 10 * n) "." + message );
n++;
}

You can try something like this:
int n = 10; // start from 10 and change it from double to int to get rid of decimal point
while ( n <= 100 ){
System.out.println( n + "." + "message");
n+=10; // increment by 10 after every loop
}

Related

Printing out individual QPs

import java.util.Scanner;
public class Grades2
{
public static void main( String[] args )
{
int NUMBER_OF_COURSES = 5;
int totalQualityPoints;
double GPA; // Grade Point Average
int QP = 0; // only need to store quality points
String courseGrade;
int[] courseNumber ={5};
Scanner in = new Scanner( System.in );
for (int n = 1; n<=5; n++)
{
System.out.print( "Enter Class "+n+" grade : " );
courseGrade = in.next();
if ( courseGrade.equals( "A" ) )
{
System.out.println( "Outstanding" );
QP += 4;
}
if ( courseGrade.equals( "B" ) )
{
System.out.println( "Above average" );
QP += 3;
}
if ( courseGrade.equals( "C" ) )
{
System.out.println( "Average" );
QP += 2;
}
if ( courseGrade.equals( "D" ) )
{
System.out.println( "Below average" );
QP += 1;
}
if ( courseGrade.equals( "F" ) )
{
System.out.println( "Try again" );
QP += 0;
}
}
}
}
How would I output the individual course QPs into a form like this
Course 1 : 9 quality points(s) (QP[1])
Course 2 : 9 quality points(s) (QP[2])
Course 3 : 9 quality points(s) (QP[3])
Course 4 : 9 quality points(s) (QP[4])
Course 5 : 9 quality points(s) (QP[5])
I think adding something next to the QPs and associate them with something but I'm not sure how to do so. I tried adding something next to it and I'm not sure how so I always end up with int found array needed. Thanks in advance :)

calling a method from within a for statement in java

I'm still a pretty novice programmer so please excuse my messing code. When I try to compile the following code I get the error:
The method Customer(java.lang.String, java.lang.Double) is undefined for the type Customer
I have previously attempted to declare the object "s" within the for statement, it then creates a new error at the end of the program where I reference the object "s" again. I was wondering how I could get around this problem? Below I have included my current program, along with the desired output and Customer.class API.
API
desired output
import java.util.Scanner;
public class A4
{
public static void main( String[] args )
{
//delcaring variables
Scanner input = new Scanner( System.in );
String[] name = new String[5];
Double[] amount = new Double[5];
Customer s = new Customer( "", 0 );
//begining of program
for ( int i = 0; i <= 5; i++ )
{
System.out.println( "please enter the name of the customer" );
name[i] = input.next();
System.out.println( "please enter the amount in that account" );
amount[i] = input.nextDouble();
s.Customer( name[i], amount[i] );
//Customer s = new Customer(name [i],amount[i]);
}
System.out.println( "Search for all customers who have more than $100" );
for ( int t = 0; t <= 5; t++ )
{
if ( amount[t] >= 100 )
{
System.out.println( name[t] );
}
}
Double avgBalance = 0.0;
for ( int r = 1; r <= 5; r++ )
{
avgBalance += r;
}
avgBalance = avgBalance / 5;
System.out.println( "The average balance is: " + avgBalance );
Double max = amount[1];
for ( int j = 0; j <= 5; j++ )
{
if ( amount[j] > max )
{
max = amount[j];
}
}
System.out.println( "The customer with the highest balance is: " + max );
System.out.println( "Show all accounts after a 5% balance increase" );
//Customer c = new Customer(name [i],amount[i]);
for ( int e = 0; e <= 5; e++ )
{
//Customer c = new Customer amount[e].applyPercentageIncrease(5);
//amount [e]=
//applyPercentageIncrease q = new
s.applyPercentageIncrease( 5 );
System.out.println( s.getName() + " has " + s.getBalance() );
}
}
}
UPDATE: i have implemented what Gtomika suggested and the program now runs, however in the first for statement, the program asks the user for 6 names then sets an out of bounds error, i understand the out of bounds error, however the for statement conditions state that it should only ask for 5 names and 5 balances right? am i missing something here?
UPDATE2: I have fixed the above problem and have improved my program, now i need some help in using the method applyPercentageIncrease from the Customer.class API. I am aware the code i wrote below is not functional, but i would appreciate some help with applying a 5% increase to all account balances using the method stated above. thanks
for (int e=0;e<5;e++)
{
//Customer c = new Customer amount[e].applyPercentageIncrease(5);
//amount [e]=
//applyPercentageIncrease q = new
customers[o]=e.applyPercentageIncrease(5);
System.out.println (o.getName()+" has "+o.getBalance());
}
You should also declare and array (or perhaps an ArrayList or LinkedList) of Customer objects:
Customer[] customers = new Customer[5];
This way in the for loop you can say:
for (int i=1;i<=5;i++)
{
System.out.println("please enter the name of the customer");
name[i] = input.next();
System.out.println("please enter the amount in that account");
amount[i] = input.nextDouble();
customers[i] = new Customer(name[i],amount[i]); //set the i. element of the Customer array
}
Now you can reference the created Customer objects after this loop!

asking multiplication table using random integers

I wrote the following code that asks the question 'How much is num1 times num2?'. However when I tried to run the java file I got no response. Can you please help me to understand what I did wrong. The code is as follows:
import java.util.Scanner;
import java.util.Random;
public class MultiplyLearn{
public void Learn(){
Random multiple = new Random();
Scanner input = new Scanner( System.in );
boolean wrong = true;
int num1 = 1 + multiple.nextInt( 9 );
int num2 = 1 + multiple.nextInt( 9 );
while( wrong == true ){
askQuestion( num1, num2 );
int answer = input.nextInt();
if( answer == num1*num2 ){
System.out.println( "Very Good" );
wrong = false;
}
else{
System.out.print( "No. Please try again." );
}
}
}
public String askQuestion( int x, int y ){
return "How much is" + x + "times" + y + "?";
}
}
Add a main method to your class
import java.util.Scanner;
import java.util.Random;
public class MultiplyLearn{
//your actual code goes here
public static void main(String args[]) throws Exception{
new MultiplyLearn().Learn();
}
}
so your final class will look as
import java.util.Scanner;
import java.util.Random;
public class MultiplyLearn{
public void Learn(){
Random multiple = new Random();
Scanner input = new Scanner( System.in );
boolean wrong = true;
int num1 = 1 + multiple.nextInt( 9 );
int num2 = 1 + multiple.nextInt( 9 );
while( wrong == true ){
askQuestion( num1, num2 );
int answer = input.nextInt();
if( answer == num1*num2 ){
System.out.println( "Very Good" );
wrong = false;
}
else{
System.out.print( "No. Please try again." );
}
}
}
public String askQuestion( int x, int y ){
return "How much is" + x + "times" + y + "?";
}
public static void main(String args[]) throws Exception{
new MultiplyLearn().Learn();
}
}
import java.util.Random;
import java.util.Scanner;
public class MultiplyLearn {
public static void main(String[] args) {
// TODO Auto-generated method stub
MultiplyLearn driver = new MultiplyLearn();
//driver.askQuestion(2, 4);
driver.Learn();
}
public void Learn(){
Random multiple = new Random();
Scanner input = new Scanner( System.in );
boolean wrong = true;
int num1 = 1 + multiple.nextInt( 9 );
int num2 = 1 + multiple.nextInt( 9 );
while( wrong == true ){
// ISSUE: The returned value needs to be printed out. The program was waiting for input and hence it did not proceed from there(No O/P). I have corrected it.
System.out.println(askQuestion( num1, num2 ));
int answer = input.nextInt();
if( answer == num1*num2 ){
System.out.println( "Very Good" );
wrong = false;
}
else{
System.out.print( "No. Please try again." );
}
}
}
public String askQuestion( int x, int y ){
return "How much is" + x + "times" + y + "?";
}
}
I think this is what you need:
import java.util.Scanner;
import java.util.Random;
public class MultiplyLearn{
public void learn(){
Random multiple = new Random();
Scanner input = new Scanner( System.in );
boolean wrong = true;
int num1 = 1 + multiple.nextInt( 9 );
int num2 = 1 + multiple.nextInt( 9 );
while(wrong){
System.out.println("How much is " + num1 + " times " + num2 + "?");
int answer = input.nextInt();
if( answer == num1*num2 ){
System.out.println( "Very Good" );
wrong = false;
}
else{
System.out.print( "No. Please try again." );
}
}
}
public static void main(String[] args)
{
MultiplyLearn learner = new MultiplyLearn();
learner.Learn();
}
A few points:
Naming conventions suggest methods should start in lower case
I don't see the point in having a seperate method simply for asking the question
Use naming conventions first : http://java.about.com/od/javasyntax/a/nameconventions.htm
So name Learn() function as learn().
Then you have to start the project from a static function.
So if you want to start project from learn() function you need to make it static(but you need to make other function also static in this case), or if you just want to use that function you need to write a static main function(preffered in this case).
import java.util.Scanner;
import java.util.Random;
public class MultiplyLearn{
public static void main(String args[]){
MultiplyLearn multiplyLearn = new MultiplyLearn();
multiplyLearn.learn();
}
public void learn(){
Random multiple = new Random();
Scanner input = new Scanner( System.in );
boolean wrong = true;
int num1 = 1 + multiple.nextInt( 9 );
int num2 = 1 + multiple.nextInt( 9 );
while( wrong == true ){
askQuestion( num1, num2 );
int answer = input.nextInt();
if( answer == num1*num2 ){
System.out.println( "Very Good" );
wrong = false;
}
else{
System.out.print( "No. Please try again." );
}
}
}
public String askQuestion( int x, int y ){
return "How much is" + x + "times" + y + "?";
}
}

Arrays, Doubles, IF/Else

Im suppose to write a code using an Array of numbers and apparently not a string and they need to be double. The way I wrote the code, the only way I know how, works. Maybe im making it too complicated and an array would make it simple idk. Im new to programming, new as in a few days. please help.
What is needed is:
Write a code that will average the input of 10 numbers and show the avg along with if they pass or fail. if < 50 fail, else > 50 pass.
we have to use an array, we need to use JOptionPane.showMessageDialog., the numbers need to be double and rounded to two decimals.
I declared double but i get an error if i enter a decimal number. If i just run the code as is, it will let me enter 10 numbers, avg them and then tell me if i pass or fail. Im just lost when it comes to using the other factors. thanks
the working code follows:
package avgpassorfail;
import javax.swing.JOptionPane;
public class Avgpassorfail {
public static void main(String[] args) {
String firstNumber,
secondNumber,
thirdNumber,
fourthNumber,
fifthNumber,
sixthNumber,
seventhNumber,
eighthNumber,
ninethNumber,
tenthNumber;
double number1,
number2,
number3,
number4,
number5,
number6,
number7,
number8,
number9,
number10,
sum;
firstNumber =
JOptionPane.showInputDialog ( "Enter 1st Grade" );
secondNumber =
JOptionPane.showInputDialog ( "Enter 2nd Grade" );
thirdNumber =
JOptionPane.showInputDialog ( "Enter 3rd Grade" );
fourthNumber =
JOptionPane.showInputDialog ( "Enter 4th Grade" );
fifthNumber =
JOptionPane.showInputDialog ( "Enter 5th Grade" );
sixthNumber =
JOptionPane.showInputDialog ( "Enter 6th Grade" );
seventhNumber =
JOptionPane.showInputDialog ( "Enter 7th Grade" );
eighthNumber =
JOptionPane.showInputDialog ( "Enter 8th Grade" );
ninethNumber =
JOptionPane.showInputDialog ( "Enter 9th Grade" );
tenthNumber =
JOptionPane.showInputDialog ( "Enter 10th Grade" );
number1 = Integer.parseInt ( firstNumber);
number2 = Integer.parseInt ( secondNumber);
number3 = Integer.parseInt ( thirdNumber);
number4 = Integer.parseInt ( fourthNumber);
number5 = Integer.parseInt ( fifthNumber);
number6 = Integer.parseInt ( sixthNumber);
number7 = Integer.parseInt ( seventhNumber);
number8 = Integer.parseInt ( eighthNumber);
number9 = Integer.parseInt ( ninethNumber);
number10 = Integer.parseInt ( tenthNumber);
sum = (number1 + number2 + number3 + number4 + number5 + number6 + number7 + number8 +number9 + number10)/10;
JOptionPane.showMessageDialog (
null, "The Average is " + sum, "Results",
JOptionPane.PLAIN_MESSAGE);
if (sum < 50){
JOptionPane.showMessageDialog (
null, "Fail", "Results",
JOptionPane.PLAIN_MESSAGE);
}else{
JOptionPane.showMessageDialog (
null, "Pass", "Results",
JOptionPane.PLAIN_MESSAGE);
}
System.exit ( 0 );
}
}
Woah there, that's a lot of repetition. You should probably clean this up with loops, like:
double sum = 0; // initialize variable for sum of all the numbers
for (int i = 1; i <= 10; i ++) { // go from 1 to 10
String strNum = JOptionPane.showInputDialog("Enter grade #" + i); // prompt for input
double dNum = Double.parseDouble(strNum); // convert to double
sum += dNum; // add to sum
}
double avg = sum / 10; // now get the average
number1 = Integer.parseInt ( firstNumber); expects to recieve a string that "looks like" an integer, if you give it something that "looks like" anything else you will recieve an error. You should instead use Double.parseDouble(firstNumber);
And yes, you should absolutely use an array for this. The use of arrays allows for a far shorter program;
public class UseArrays {
public static void main(String[] args){
int numberOfEntries=10
double[] numbers =new double[numberOfEntries];
for(int i=0;i< numbers .length;i++){
String option =
JOptionPane.showInputDialog ( "Enter Grade " + i );
numbers[i]=Double.parseDouble(option);
}
double sum=0;
for(int i=0;i< numbers .length;i++){
sum+=numbers[i];
}
double average=sum/10;
System.out.println(average);
}
}
Note also that with the program created in this way it is incredibly easy to change the number of entries, in addition to being much shorter to write. You would not want to type out each entry by hand if you had hundreds, thousands or even millions of entries.
You could make this program even shorter by not storing each double then adding them later (which would also make using the array unnessissary). This program would look like;
public class DontUseArrays {
public static void main(String[] args){
int numberOfEntries=10
double sum=0;
for(int i=0;i< numberOfEntries;i++){
String option =
JOptionPane.showInputDialog ( "Enter Grade " + i );
double number=Double.parseDouble(option);
sum+=number;
}
double average=sum/10;
System.out.println(average);
}
}
Here's a fragment of code that should get you on your way:
public void test() {
double[] numbers = new double[10];
double sum = 0;
for ( int i = 0; i < numbers.length; i++ ) {
String number = JOptionPane.showInputDialog ( "Enter Grade "+(i+1) );
numbers[i] = Double.parseDouble(number);
sum += numbers[i];
}
}
What if you had to calculate 1000 grades? That's why we use arrays.
package avgpassorfail;
import javax.swing.JOptionPane;
public class Avgpassorfail
{
public static void main(String[] args)
{
String[] mumStr = new String[10];
double sum = 0;
for (int i = 0; i < numStr.length; i++) //0 to 10 (10 not included)
{
numStr[i] = JOptionPane.showInputDialog ( "Enter Grade " + (i+1)+ ": " );
sum += Double.parseDouble(numStr[i]);
}
double avg = sum / numStr.length;
JOptionPane.showMessageDialog (null, "The Average is " + avg, "Results", JOptionPane.PLAIN_MESSAGE);
if (avg < 50)
{
JOptionPane.showMessageDialog (null, "Fail", "Results", JOptionPane.PLAIN_MESSAGE);
}
else
{
JOptionPane.showMessageDialog (null, "Pass", "Results", JOptionPane.PLAIN_MESSAGE);
}
System.exit ( 0 );
}
}
To parse your Strings to the double type use Double.parseDouble(String s)
You can assign the ints returned from Integer.parseInt(String s) to your double variables, because doubles are higher precision than ints and so type conversion happens automatically without the need for an explicit cast.
However you can not parse any String with a decimal point to an int using Integer.parseInt(String s), by definition.
Additional point - There's no need to declare the String variables, or have a separate variable for each number - it'll be much cleaner to use an array and a loop to input the numbers, and possibly sum the numbers as they come in, something like:
double[] numbers = new double[10];
double sum = 0d;
for(int i = 0; i < numbers.length; i++ ) {
numbers[i] = Double.parseDouble(JOptionPane.showInputDialog ( "Enter 1st Grade" ));
sum += numbers[i];
}
double mean = sum / numbers.length;

Adding values in a for loop

I cant figure out how to add the values after it spits out the numbers.
it says:
Number: 5 // I typed 5
1 2 3 4 5
The sum is.
So i need to add those number 1 2 3 4 5 but cant figure out how.
import java.util.Scanner
public class AddingValuesWithAForLoop
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( " \n" );
System.out.println( "Number: " );
int number = keyboard.nextInt();
int sum = 0;
for (int run=1; run<=number; run=run+1)
{
System.out.print( run + " " );
sum = sum + 1 ;
}
System.out.println( "The sum is . " );
}
}
You need to add run to sum and then print it out, like this:
import java.util.Scanner
public class AddingValuesWithAForLoop
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( " \n" );
System.out.println( "Number: " );
int number = keyboard.nextInt();
int sum = 0;
for (int run=1; run<=number; run=run+1)
{
System.out.print( run + " " );
sum = sum + run;
}
System.out.println( "The sum is " + sum );
}
}
System.out.println( "The sum is: " + sum );
the + sum seems weird but you can use it the and a number value to a string
import java.util.Scanner;
public class AddLoop {
public static void main(String[] args) {
int sum = 0;
for(int i=1 ; i<=10 ; i++){
Scanner s = new Scanner( System.in);
System.out.println("Enter number" + " " + i);
int b = s.nextInt();
sum = sum + b;
}
System.out.println("The result is :" + sum );
}
}
I believe you want sum = sum + run;
if you are wanting to sum (1, 2, 3, 4, 5) = 15.
Fahd's answer is pretty much what you're looking for (he posted while I was typing mine). My answer just has a little bit different syntax to perform the loop and sum.
import java.util.Scanner
public class AddingValuesWithAForLoop { public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( " \n" );
System.out.println( "Number: " );
int number = keyboard.nextInt();
int sum = 0;
for (int run=1; run<=number; run++)
{
System.out.print( run + " " );
sum += run;
}
System.out.println( "The sum is " + sum + "." );
}
}
well the way your doing it you will need to do keyboard.nextLine(); that will set all of your numbers to a string. Once you have all of your numbers in string you can parse through the string and set that as the scanner then do nextInt()
import java.util.Scanner
public class AddingValuesWithAForLoop
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Number: ");
string numbers = keyboard.nextLine(); // 5 1 2 3 5
Scanner theNumber = new Scanner(numbers);
int sum = 0;
for (int run = theNumber.nextInt(); run > 0; run--)
{
System.out.print(run + " ");
sum += theNumber.nextInt();
}
System.out.println("The sum is: " + sum);
}
}
Here is the code that might be helpful:
import java.util.Scanner;
public class AddLoop {
public static void main(String[] args) {
int sum = 0;
for(int i=1 ; i<=10 ; i++){
Scanner s = new Scanner( System.in);
System.out.println("Enter number" + " " + i);
int b = s.nextInt();
sum = sum + b;
}
System.out.println("The result is :" + sum );
}
}
Hope this answer help you.
Assume that input value is 6, So internally add all the consecutive numbers until 6. I.e Since the input value is 6, output should be like this
0+1+2+3+4+5=15
Refer to the below snippet
public void testAdding() {
int inputVal = 6;
String input = "";
int adder = 0;
for(int i=0; i < inputVal; i++) {
input = String.valueOf(i);
if(inputVal == (i+1)) {
System.out.print(input);
} else {
System.out.print(input+"+");
}
adder =+ i + adder;
}
System.out.print("="+adder);
}

Categories

Resources