Hi I am just learning java with a book; in this, there is an excersise called loan; I am following the sample, but when I want to test the program after I type the loan amount named by me as montoPrestamo (in Spanish) but when I type any value, netBeans does not nothing, no error, no exception, no next prompt, nothing.
I dont know what is going on or where is the mistake.
thanks
here is my code:
public static void main(String[] args) {
double montoPrestamo, interesAnual,pagoMensual,pagoTotal;
int tiempoPrestamo;
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(System.getProperty("line.separator"));
System.out.print("Monto del prestamo (Pesos y Centavos): ");
montoPrestamo = scanner.nextDouble();
System.out.print("el valor ingresado es " + montoPrestamo);
System.out.print("Tasa de Interes anual (ejemplo, 9,5): ");
interesAnual=scanner.nextDouble();
System.out.print("Tiempo de periodo del prestamo en años : ");
tiempoPrestamo=scanner.nextInt();
System.out.println("");
System.out.println("Cantidad solicitada $"+montoPrestamo);
System.out.println("la tasa de interes de su prestamo:"+interesAnual+"%");
System.out.println("Tiempo del prestamo en años"+tiempoPrestamo);
System.out.println("\n");
System.out.println("Pago mensual"+pagoMensual);
System.out.println("Pago total"+pagoTotal);
}
It works after removing this line:
scanner.useDelimiter(System.getProperty("line.separator"));
Probably this does not work from within an IDE because it uses an own terminal which might use another linefeed separator than your operating system.
Related
I'm doing internships with a small project that asks the user to select a category of expenses, to later request quantities that are stored in a ArrayList and finally the amount of the total expenses of that category is printed on the screen. The problem comes at the moment in which I associate the variable 'quantity' with a Scanner entry, at that moment the execution thread remains in Execution and it does not return any type of error.
package gestioneconomica;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
/**
*
* #author Robin
*/
class Gastos {
//Declaración de los tipos de gastos organizados en ArrayList()
ArrayList<Double> taberna=new ArrayList<>();
ArrayList<Double> tPublico=new ArrayList<>();
ArrayList<Double> alimentacion=new ArrayList<>();
ArrayList<Double> formacion=new ArrayList<>();
//Declaración e inicialización de la suma de los valores de cada ArrayList()
double sumTaberna=0.0;
double sumTPublico=0.0;
double sumAlimentacion=0.0;
double sumFormacion=0.0;
//Instanciación del objeto 'sc' de la clase Scanner
Scanner sd=new Scanner(System.in);
//*************THE NEXT LINE CAUSES THE ERROR****************
double quantity=sd.nextDouble();
//Declaración e inicialización de métodos
public void addTaberna(){
System.out.print("Ingrese importe: ");
while(quantity!=0){
taberna.add(quantity);
}
System.out.print("El total consumido en esta categoría es de: ");
Iterator <Double> itTaberna=taberna.iterator();
while(itTaberna.hasNext()){
System.out.println(itTaberna.next());
}
}
public void addtPublico(){
System.out.print("Ingrese importe: ");
while(quantity!=0){
tPublico.add(quantity);
}
Iterator <Double> itTPublico=tPublico.iterator();
while(itTPublico.hasNext()){
sumTPublico+=itTPublico.next();
}
System.out.println("Gastos totales en Transporte Público: " + sumTPublico);
}
public void addAlimentacion(){
System.out.print("Ingrese importe: ");
alimentacion.add(sd.nextDouble());
}
public void addFormacion(){
System.out.print("Ingrese importe: ");
formacion.add(sd.nextDouble());
}
}
//THIS IS THE DRIVER CLASS
package gestioneconomica;
import java.util.Scanner;
class GastosExe{
public static void main(String[]args){
System.out.println("###################################################");
System.out.println("BIENVENIDO/A AL PROGRAMA DE GASTOS DE ROBIN");
System.out.println("###################################################");
System.out.println("(1)TABERNA\t(2)TRANSPORTE PÚBLICO\t(3)ALIMENTACIÓN\t (4)INVERSIÓN FORMATIVA");
System.out.println("Seleccione el tipo de Gasto: ");
Gastos gastos=new Gastos();
Scanner sc=new Scanner(System.in);
int tipo=sc.nextInt();
switch(tipo){
case 1:
System.out.println("Ha seleccionado Taberna");
gastos.addTaberna();
break;
case 2:
System.out.println("Ha seleccionado Transporte Público");
break;
case 3:
System.out.println("Ha seleccionado Alimentación");
gastos.addAlimentacion();
break;
case 4:
System.out.println("Ha seleccionado Inversión Formativa");
gastos.addFormacion();
break;
}
}
}
Welcome to SO. This is a very nicely phrased first question.
at that moment the execution thread remains in Execution and it does
not return any type of error
That's because there is no error here. And the correct term is "at the moment the execution thread (main thread) remains blocked" Your program is behaving exactly the way you coded it to behave
Let's break it down from the main method.
Gastos gastos=new Gastos();
When you call the Gastos constructor here on the main method, the Gastos class initializes, which has the quantity field of type double, initialized directly with the input from the Scanner.
When execution reaches this line double quantity = sd.nextDouble(); it blocks the main thread, waiting for keyboard input from the user..
So you should enter a selection here 1
when you press enter, sd.nextDouble(); method returns, and main thread resumes.
Then, when the Gastos() constructor call returns and the main thread reaches this line int tipo = sc.nextInt();
Which blocks the main thread again, waiting for another keyboard input from the user.
So you should enter a selection here again 2
When you press enter, sc.nextInt(); method returns and the main thread resumes execution
Sample run
###################################################
BIENVENIDO/A AL PROGRAMA DE GASTOS DE ROBIN
###################################################
(1)TABERNA (2)TRANSPORTE PÚBLICO (3)ALIMENTACIÓN (4)INVERSIÓN FORMATIVA
Seleccione el tipo de Gasto:
1
2
Ha seleccionado Transporte Público
try:
double quantity = Double.parseDouble(sd.nextLine());
I have a little question. I need to read two words in a line for put name and lastname.
public void Promedios5(){
Scanner Marbis=new Scanner(System.in);
String[] x=new String[5];
double[][] a=new double[5][4];
double[] b=new double [5],c=new double[5];
System.out.println("Este programa genera los promedios de las notas de cuatro unidades\n"
+ "se le solicitarán a usted, el nombre y las cuatro notas");
System.out.println("Podría ingresarlas ahora por favor:");
for(int y=0;y<=4;y++){
System.out.println("Ingrese el nombre:");
x[y]=Marbis.nextLine();
for(int z=0;z<=3;z++){
a[y][z]=Marbis.nextDouble();
}
b[y]=a[y][0]+a[y][1]+a[y][2]+a[y][3];
c[y]=b[y]/4;
}
System.out.println("Ahora usted verá los promedios de las personas:");
System.out.println("Nombre:\t\t\tPromedio");
for(int m=0;m<=4;m++)
System.out.printf("%s:\t\t%.2f\n",x[m],c[m]);
}
Here I have the error: x[y]=Marbis.nextLine();
I know that I use it for two or more words in a Line, but in the second chances it marks me error, like this (This is the result, I think that I can use arrays in nextLine):
MArio Albert
100
100.00
78.00
100.00
Ingrese el nombre:
John Antoinie
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at vectormarbis1.MarbisVectors2.Promedios5(MarbisVectors2.java:125)
at vectormarbis1.VectorMarbis1.main(VectorMarbis1.java:28)
C:\Users\ManoloAurelio\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 39 seconds)
You only flush the output in Java.
When to discard the rest of the line? To solve your problem you can call
input.nextLine();
You need to do this after nextDouble() as you expect to be reading from the next line.
I hope the below given code helps you solve your problem.
public void Promedios5(){
Scanner Marbis=new Scanner(System.in);
String[] x=new String[5];
double[][] a=new double[5][4];
double[] b=new double [5],c=new double[5];
System.out.println("Este programa genera los promedios de las notas de cuatro unidades\n"
+ "se le solicitarán a usted, el nombre y las cuatro notas");
System.out.println("Podría ingresarlas ahora por favor:");
for(int y=0;y<=4;y++){
System.out.println("Ingrese el nombre:");
x[y]=Marbis.nextLine();
for(int z=0;z<=3;z++){
a[y][z]=Marbis.nextDouble();
}
Marbis.nextLine(); //Just add this line here
b[y]=a[y][0]+a[y][1]+a[y][2]+a[y][3];
c[y]=b[y]/4;
}
System.out.println("Ahora usted verá los promedios de las personas:");
System.out.println("Nombre:\t\t\tPromedio");
for(int m=0;m<=4;m++)
System.out.printf("%s:\t\t%.2f\n",x[m],c[m]);
}
So yesterday I asked a question about some GUI-ing. I completly threw that over, since I found it a little to complicated for me to actually deal with it.
Now I am reworking the thing in the console.
And I got myself stuck again. My problem this time: How can I jump back to a point before a if-command was executed?
Direct example:
import java.util.Scanner;
import java.io.*;
public class HBA {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Herzlichen Glückwunsch Anna! Und viel Spaß mit deinem Geschenk!") ;
System.out.println("Neben diesem Programm befindet sich eine Passwort gesicherte Datei, die einen weiteren Teil deines Geschenks enthällt."
+ "Um an das Passwort zu gelangen wirst du jedoch ein paar ganz besonders schwierige Fragen beantworten müssen!"
+ "Wenn du bereit für das Quiz bist, gib in die Eingabe: 'ok' ein.");
String OK, Q1, Q2, Q3, Q4, Q5, Q6, Q7;
BufferedReader repo = null;
OK = scan.next();
if (OK == "ok") {
System.out.println("Alles gut, fangen wir mit etwas leichtem an!");
}
else {
System.out.println("Wie... bei so einer einfachen Sache versagst du schon? Versuchs nochmal!");
}
System.out.println("Frage 1: Wer ist Supergeil? \n A: Erik \n B: Anna \n C: The J \n D: Friedrich Liechtenstein");
mark(0);
Q1 = scan.next();
if (Q1 == "D") {
System.out.println("Richtig! Der erste Buchstabe lautet: S");
}
else {
System.out.println("Leider falsch. Versuch es nochmal.");
reset();
}
}
}
The scripted works as expected, besides: If you type something wrong in the last part:
System.out.println("Frage 1: Wer ist Supergeil? \n A: Erik \n B: Anna \n C: The J \n D: Friedrich Liechtenstein");
mark(0);
Q1 = scan.next();
if (Q1 == "D") {
System.out.println("Richtig! Der erste Buchstabe lautet: S");
}
else {
System.out.println("Leider falsch. Versuch es nochmal.");
reset();
}
}
}
It just ends the script. Instead it should jump back to the beginning of the if-command.
Means: The answer to the question in the System.out.printLn (it is a question) is D and you typ A instead, it should reset the whole thing that you can try it again and answer something different. How can I achieve that? I read that BufferedReader have a mark() and reset() function, but I don't know if they work the way I expect them to or how I would have to integrate them.
I also thought about using a while or a do command. But I haven't found a way for that yet.
Can someone pls enlighten me?
Thanks!
/**
* #(#)b.java
*
*
* #author
* #version 1.00 2012/5/4
*/
import java.util.*;
import java.io.*;
import java.*;
public class b {
static void lireBddParcs(String nomFichier) throws IOException
{
LinkedHashMap parcMap = new LinkedHashMap<Parc,Collection<Manege>> ();
boolean existeFichier = true;
FileReader fr = null;
try
{
fr = new FileReader (nomFichier);
}
catch(java.io.FileNotFoundException erreur)
{
System.out.println("Probleme rencontree a l'ouverture du fichier" + nomFichier);
existeFichier = false;
}
if (existeFichier)
{
Scanner scan = new Scanner(new File(nomFichier));
while (scan.hasNextLine())
{
String[] line = scan.nextLine().split("\t");
Parc p = new Parc(line[0], line[1], line[2]);
parcMap.put(p, null);
}
}
scan.close();
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
lireBddParcs("parcs.txt");
}
}
parc.txt contains:
Great America Chicago Illinois
Magic mountain Los Ageles Californie
Six Flags over Georgia Atlanta Georgie
Darien Lake Buffalo New York
La Ronde Montreal Quebec
The Great Escape Lake Georges New York
Six Flags New Orleans New Orleans Louisiane
Elitch Gardens Denver Colorado
Six Flags over Texas Arlington Texas
Six Flags New England Springfield Massachusetts
Six Flags America Washington D.C.
Great Adventure Jackson New Jersey
error: class, interface, or enum expected line 94
error: class, interface, or enum expected line 99
I decided to change my code, because something didn't work out as expected, but now I am getting this. Can't get through the compilation. Any idea why it doesn't work? I am a complete noob about to abandon my java course.
Although indentation is confusing, the main method is outside of the class while it should be inside of it.
It also make the line scan.close(); invalid, as scan is not defined there. remove the } before scan.close();.
It's just because there's an extraneous closing brace in your first method here:
}
scan.close();
If you use an IDE such as eclipse or netbeans to edit your source files, it will help a lot with automatic brace matching and highlighting these kinds of errors.
I have a particular file that Java says is empty...
Source Code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MinimumWorkingExample
{
public static void main(String[] args) throws FileNotFoundException
{
String filename = "/home/tyson/Data/English-French_test/test/test.f";
Scanner fileIn = new Scanner(new File(filename));
System.out.println("***START***");
while(fileIn.hasNextLine())
{
System.out.println(fileIn.nextLine());
}
System.out.println("***FINISH***");
}
}
Output
***START***
***FINISH***
...but the file is not empty:
Console
tyson#tyson-desktop:~$ head /home/tyson/Data/English-French_test/test/test.f
<s snum=0001> 2 . </s>
<s snum=0002> 2 . </s>
<s snum=0003> oh , oh ! </s>
<s snum=0004> oh , oh ! </s>
<s snum=0005> oh , oh ! </s>
<s snum=0006> souvenons - nous , monsieur le Orateur , que ce sont ces secteurs de notre soci�t� qui servent de �pine dorsale � notre �conomie . </s>
<s snum=0007> bravo ! </s>
<s snum=0008> bravo ! </s>
<s snum=0009> monsieur le Orateur , ma question se adresse � le ministre charg� de les transports . </s>
<s snum=0010> tous deux poss�dent de nombreuses ann�es de exp�rience dans la fabrication et la distribution de les produits forestiers . </s>
tyson#tyson-desktop:~$
Question
Why is this happening???
Also do Scanner fileIn = new Scanner(new File(filename), "Cp1252"); as this is the encoding for French, and your system seems to be UTF-8.
The Scanner might have encoding problems if it thinks to read UTF-8 multibytes.
You may be missing the Scanner's default delimiter so it sees your whole file as one line without end, thus hasNextLine() is false. Make sure that the character you get from
Scanner.delimiter()
Is present in your file. If they don't match, you can use
Scanner.useDelimiter("\\s or your regex/string here")
to set it to the correct one.
According to Java Docs, the Line Separators are any of the ones below. Does your file contain any?
private static final String LINE_SEPARATOR_PATTERN = "\r\n|[\n\r\u2028\u2029\u0085]"