Java Code Examples for java.util.Scanner

The following are top voted examples for showing how to use java.util.Scanner. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: android-dev-challenge   File: NetworkUtils.java   Source Code and License 8 votes vote down vote up
/**
 * This method returns the entire result from the HTTP response.
 *
 * @param url The URL to fetch the HTTP response from.
 * @return The contents of the HTTP response.
 * @throws IOException Related to network and stream reading
 */
public static String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();

        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");

        boolean hasInput = scanner.hasNext();
        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        urlConnection.disconnect();
    }
}
 
Example 2
Project: Hacktoberfest-Data-Structure-and-Algorithms   File: Closest.java   Source Code and License 8 votes vote down vote up
public static void main(String[] args) {
    //get input
    Scanner sc = new Scanner(System.in).useDelimiter(" ");
    ArrayList<Integer> input = new ArrayList<>();
    //add input to ArrayList
    while (sc.hasNextInt()) {
        input.add(sc.nextInt());
    }
    //sort the list
    Collections.sort(input);
    //initialize closest values, with the first two elements in the list
    int closest = input.get(1)-input.get(0);
    //check all elements in the list
    for(int i = 2; i < input.size(); i++) {
        //change closest if we find two elements with a shorter distance.
        closest = Math.min(closest, input.get(i)-input.get(i-1));
    }
    //print the shortest distance
    System.out.println(closest);
}
 
Example 3
Project: Shield   File: Functions.java   Source Code and License 7 votes vote down vote up
public static ArrayList<String[]> secondList(){

        try{
            Scanner scannerSongs = new Scanner(new File("Recommended_db.csv"));
            ArrayList<String[]> allSongs = new ArrayList<>();
            scannerSongs.nextLine();
            while (scannerSongs.hasNextLine()) {
                String line = scannerSongs.nextLine();
                String[] columns = line.split(",");
                String[] songInfo = {columns[3],columns[4],null};
                allSongs.add(songInfo);
            }
            return allSongs;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
 
Example 4
Project: 3way_laboratorios   File: Ex4.java   Source Code and License 7 votes vote down vote up
public static void main(String[] args) {
	// entrada = 3 notas
	// Seria o prompt do java script
	Scanner sc = new Scanner(System.in);
	System.out.println("Digite o valor da nota 1:");
	double nota1 = sc.nextDouble();
	System.out.println("Digite o valor da nota 2:");
	double nota2 = sc.nextDouble();
	System.out.println("Digite o valor da nota 3:");
	double nota3 = sc.nextDouble();

	// processamento = calcular media
	double media = (nota1 + nota2 + nota3)/3;

	// saida = condicao do aluno (Reprovado, aprovado, recuperacao)
	if (media <= 5) {
		System.out.println("Reprovado");
	} else if (media > 5 && media < 7) {
		System.out.println("Recuperacao");
	} else {
		System.out.println("Aprovado");
	}
}
 
Example 5
Project: ecam-app-android   File: NetworkUtils.java   Source Code and License 7 votes vote down vote up
public static String getResponseFromHttpUrl(String url) throws IOException {

        URL urlObject = new URL(url);

        HttpURLConnection urlConnection =
                (HttpURLConnection) urlObject.openConnection();

        try {
            InputStream in = urlConnection.getInputStream();

            Scanner scanner = new Scanner(in);
            scanner.useDelimiter("\\A");

            boolean hasInput = scanner.hasNext();
            if (hasInput) {
                return scanner.next();
            } else {
                return null;
            }
        } finally {
            urlConnection.disconnect();
        }
    }
 
Example 6
Project: AlgoCS   File: FlatSpots_1617.java   Source Code and License 7 votes vote down vote up
public static void main(String[] args) {
    Scanner x = new Scanner(System.in);
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));
    int n = x.nextInt(), c;
    int a[] = new int[701];
    for (int i = 0; i < n; i++) {
        c = x.nextInt();
        a[c]++;
    }
    int s = 0;
    for (int i = 600; i < a.length; i++) {
        s += a[i] / 4;
    }
    writer.print(s);
    writer.close();
}
 
Example 7
Project: AlgoCS   File: Stripies_1161.java   Source Code and License 7 votes vote down vote up
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    PrintWriter out = new PrintWriter(System.out);
    Byte n = in.nextByte();
    double ans = 0;
    double a[] = new double[n];
    for (int i = 0; i < a.length; i++) {
        a[i] = in.nextInt();
    }
    Arrays.sort(a);
    ans = a[a.length - 1];
    for (int i = a.length - 1; i > 0; i--) {
        ans = Max(ans, a[i - 1]);
    }
    System.out.printf("%.2f", ans);
}
 
Example 8
Project: time4sys   File: NfpFactoryImpl.java   Source Code and License 7 votes vote down vote up
/**
 * @generated NOT
 */
@Override
public TimeInterval createTimeIntervalFromString(final String value) {
	final TimeIntervalImpl anInterval = new TimeIntervalImpl();
	final Scanner scan = new Scanner(value);
	final String leftPar = scan.findInLine("\\]|\\[");
	anInterval.setMinOpen("]".equals(leftPar));
	final String leftStr = scan.findInLine("[^,]*");
	anInterval.setMin(createDurationFromString(leftStr));
	scan.findInLine(",");
	String rightStr = scan.findInLine("[^\\]\\[]*");
	if (rightStr == null) {
		rightStr = leftStr;
	}
	anInterval.setMax(createDurationFromString(rightStr));
	final String rightPar = scan.findInLine("\\]|\\[");
	anInterval.setMaxOpen("[".equals(rightPar));
	scan.close();
	return anInterval;
}
 
Example 9
Project: android-dev-challenge   File: NetworkUtils.java   Source Code and License 6 votes vote down vote up
/**
 * This method returns the entire result from the HTTP response.
 *
 * @param url The URL to fetch the HTTP response from.
 * @return The contents of the HTTP response, null if no response
 * @throws IOException Related to network and stream reading
 */
public static String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();

        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");

        boolean hasInput = scanner.hasNext();
        String response = null;
        if (hasInput) {
            response = scanner.next();
        }
        scanner.close();
        return response;
    } finally {
        urlConnection.disconnect();
    }
}
 
Example 10
Project: codeforces   File: Problem_427A.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int number = in.nextInt();

    int reserve = 0;
    int result = 0;
    int temp;
    for (int i = 0; i < number; i++) {
        temp = in.nextInt();
        if (temp == -1 && reserve > 0)
            reserve--;
        else if (temp == -1 && reserve == 0)
            result++;
        else if (temp > 0)
            reserve += temp;
    }

    System.out.print(result);
}
 
Example 11
Project: MMORPG_Prototype   File: GameServer.java   Source Code and License 6 votes vote down vote up
private void startCommandHandlerOnNewThread()
{
    Log.info("NOTE: you can now type commands here.");
    CommandHandler commandHandler = new CommandHandler();
    Runnable commandHandlingTask = () ->
    {
        try (Scanner scanner = new Scanner(System.in))
        {
            while (true)
            {
                String command = scanner.nextLine();
                commandHandler.handle(command);
            }
        }
    };
    new Thread(commandHandlingTask).start();
}
 
Example 12
Project: openjdk-jdk10   File: FcFontConfiguration.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the OS version string from a Linux release-specific file.
 */
private String getVersionString(File f){
    try {
        Scanner sc  = new Scanner(f);
        return sc.findInLine("(\\d)+((\\.)(\\d)+)*");
    }
    catch (Exception e){
    }
    return null;
}
 
Example 13
Project: codeforces   File: Problem_591A.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int length = in.nextInt();
    int speed1 = in.nextInt();
    int speed2 = in.nextInt();

    double time = (double) length / (speed1 + speed2);
    System.out.print(time * speed1);
}
 
Example 14
Project: Progetto-A   File: PartitaOfflineConsoleView.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @param model modello partita offline
 */
public PartitaOfflineConsoleView(PartitaOfflineModel model) {
    this.listeners = new CopyOnWriteArrayList<>();
    this.model = model;
    this.model.addObserver(this);
    scanner = new Scanner(System.in);
}
 
Example 15
Project: teamcity-autotools-plugin   File: DejagnuTestsXMLParser.java   Source Code and License 6 votes vote down vote up
/**
 * Handles Xml file and public dejagnu test results from this.
 *
 * @param xmlFile file with test results
 * @return count of public xmlFile has been handled
 */
int handleXmlResults(@NotNull final File xmlFile){
  myTestsCount = 0;
  try {
    String xmlEntry = new Scanner(xmlFile, "UTF-8").useDelimiter("\\A").next();
    if (myNeedReplaceApm){
      xmlEntry = replaceAmp(replaceXmlHeaderVersion(xmlEntry));
    }
    if (myNeedToReplaceControls){
      xmlEntry = replaceControlChars(xmlEntry);
    }
    parseXmlTestResults(xmlEntry, xmlFile.getAbsolutePath());
    return myTestsCount;
  }
  catch (final FileNotFoundException ignored){
    //e.getMessage();
    return 0;
  }
}
 
Example 16
Project: MyCourses   File: stringVeriAlma.java   Source Code and License 6 votes vote down vote up
public static void main(String [] args)
{
	Scanner input = new Scanner(System.in);
	int sayi;
	String metin;

/*
	system.out.println("Randevu adi giriniz : ");
	metin = input.next();
	system.out.println("Randevu yeri giriniz : ");
	metin = input.nextLine();
	system.out.print("Randevu tarih-saati giriniz : " + metin);
	sayi = input.nextLine();
	
	System.out.println("Randevunuz = " + randevu);
	System.out.println("Yeriniz = " + yer);
	System.out.println("Tarihiniz = " + tarih);
	
	
	getchar();
	return 0;
*/
	
	

}
 
Example 17
Project: java_mooc_fi   File: GreaterNumber.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    
    System.out.print("Type the first number: ");
    int firstNumber = Integer.parseInt(reader.nextLine());
    System.out.print("Type the second number: ");
    int secondNumber = Integer.parseInt(reader.nextLine());
    
    System.out.println("");
    if ( firstNumber > secondNumber ) {
        System.out.println("Greater number: " + firstNumber);
    } else if (firstNumber < secondNumber) {
        System.out.println("Greater number: " + secondNumber);
    } else {
        System.out.println("The numbers are equal!");            
    }

}
 
Example 18
Project: i_stolbov   File: OracleClient.java   Source Code and License 6 votes vote down vote up
/**
 * init.
 * @param socket - ip
 * @throws IOException - IOException
 */
public void init(Socket socket) throws IOException {
    String message;
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    Scanner console = new Scanner(System.in);
    do {
        message = console.nextLine();
        out.println(message);
        String str;
        if (!EXIT.equals(message)) {
            while (!(str = in.readLine()).isEmpty()) {
                System.out.println(str);
            }
        }
    } while (!EXIT.equals(message));
}
 
Example 19
Project: LivroJavaComoProgramar10Edicao   File: AccountTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args)
{ 
   // create a Scanner object to obtain input from the command window
   Scanner input = new Scanner(System.in);

   // create an Account object and assign it to myAccount
   Account myAccount = new Account(); 

   // display initial value of name (null)
   System.out.printf("Initial name is: %s%n%n", myAccount.getName());

   // prompt for and read name
   System.out.println("Please enter the name:");
   String theName = input.nextLine(); // read a line of text
   myAccount.setName(theName); // put theName in myAccount
   System.out.println(); // outputs a blank line

   // display the name stored in object myAccount
   System.out.printf("Name in object myAccount is:%n%s%n",
      myAccount.getName());
}
 
Example 20
Project: Metro-Etiquette-System   File: Contact.java   Source Code and License 6 votes vote down vote up
public static void address(){

	System.out.println("Address:\nRoorkee Metro Rail Corporation,\nFire bridge lane,");
	System.out.println("Civillines Road,\nUttarakhand-247667,");
	System.out.println("Telephone no.04023283550,");
	System.out.println("email id:[email protected],");
	System.out.println("Fax no.:53795748");
	
	Scanner in = new Scanner(System.in);
	int a=0;
	System.out.println("\nPress any non zero integer to Return to main menu.");
	a = in.nextInt();
	if(a !=0)
		Metro_Etiquettes.mainMenu();
	else{
		System.out.print("Wrong choice!\nSystem is terminating.....\n..\nTerminated.");
	}	
}
 
Example 21
Project: Homework   File: Menu.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args)
{
	Scanner sc =new Scanner(System.in);
	System.out.println("************登录菜单************\n1、登录系统\n2、退出");
	int a1 = sc.nextInt();
	if(a1 == 1)
	{
		System.out.println("************主菜单************\n"
				+ "1、客户管理系统\n2、购物结算\n3、真情回馈\n4、注销");
		int a2 = sc.nextInt();
		switch(a2)
		{
			case 1: 
				System.out.println("购物管理系统>客户信息管理\n"
						+ "1、显示所有客户信息\n2、添加客户信息\n3、修改客户信息\n4、查询客户信息");
				break;
			case 2: break;
			case 3:
				System.out.println("购物管理系统>真情回馈\n"
						+ "1、幸运大放送\n2、幸运抽奖\n3、生日问候");
				break;
			case 4: break;
		}
	}
	sc.close();
}
 
Example 22
Project: codeforces   File: Problem_379A.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int newCandle = in.nextInt();
    int oldCandle = in.nextInt();

    int hours = newCandle;
    int temp, remainder;

    temp = newCandle / oldCandle;
    remainder = newCandle % oldCandle;
    while (temp > 0) {
        hours += temp;
        newCandle = temp + remainder;
        temp = newCandle / oldCandle;
        remainder = newCandle % oldCandle;
    }
    System.out.print(hours);
}
 
Example 23
Project: Stork   File: InvQuadRegression.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  int num = 500000;

  // Test values
  double[] test_a = { 30, -40, 36 };

  //InvQuadRegression qr = new InvQuadRegression(list.size());
  InvQuadRegression qr = new InvQuadRegression(num);

  // Seed qr with random stuff.
  for (int i = 0; i < num; i++) {
    int n = (int) (15*Math.random())+1;
    double th = cal_thr(test_a, n);// + .1*Math.random();
    qr.add(n, 1/(th*th));
  }

  double[] a = qr.calculate();
}
 
Example 24
Project: PatProject   File: Prob1023.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n = 10;
    int[] box = new int[n];
    box[0] = scanner.nextInt();
    boolean flag = false;
    for (int i = 1; i < n; i++) {
        box[i] = scanner.nextInt();
        if (!flag) {
            if (box[i] != 0) {
                System.out.print(i);
                box[i]--;
                flag = true;
            }
        }

    }
    for (int i = 0; i < n; i++) {
        if (box[i] != 0) {
            for (int j = 0; j < box[i]; j++) {
                System.out.print(i);
            }
        }
    }

}
 
Example 25
Project: Homework   File: OOex02.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) 
{
	Scanner sc = new Scanner(System.in);
	Vistor vister = new Vistor();
	for (int i = 0; i < 10; i++) 
	{
		System.out.println("请输入姓名");
		vister.name = sc.next();
		if ("n".equals(vister.name)) 
		{
			System.out.println("退出程序");
			break;
		}
		System.out.println("请输入年龄");
		vister.age = sc.nextInt();
		vister.show();
	}
	
	sc.close();

	
	
}
 
Example 26
Project: GitHub   File: ComputerIdentifierGenerator.java   Source Code and License 6 votes vote down vote up
private static String getWindowsIdentifier() throws IOException, NoSuchAlgorithmException {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(new String[] { "wmic", "csproduct", "get", "UUID" });

    String result = null;
    InputStream is = process.getInputStream();
    Scanner sc = new Scanner(process.getInputStream());
    try {
        while (sc.hasNext()) {
            String next = sc.next();
            if (next.contains("UUID")) {
                result = sc.next().trim();
                break;
            }
        }
    } finally {
        is.close();
    }

    return result==null?UNKNOWN:Utils.hexStringify(Utils.sha256Hash(result.getBytes()));
}
 
Example 27
Project: robird-reborn   File: TweetLongerUtils.java   Source Code and License 6 votes vote down vote up
private static String readTweetLongedText(String id) {
    StringBuilder sb = new StringBuilder();
    try {
        Scanner scanner = new Scanner(new BufferedInputStream(
                new URL("http://www.twitlonger.com/api_read/" + id).openStream()));
        while (scanner.hasNext())
            sb.append(scanner.nextLine());
        scanner.close();
        return new TwitLongerResponse(sb.toString()).content;
    } catch (IOException e) {
        Timber.i("", e);
    }

    return sb.toString();
}
 
Example 28
Project: Homework   File: Discount.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) 
{
	//从控制台输入会员积分
	Scanner sc = new Scanner(System.in);
	System.out.print("请输入会员积分:");
	int point = sc.nextInt();
	sc.close();
	//判断会员积分所属区间,输出相应折扣
	if (point < 2000)
	{
		System.out.println("该会员享受的的折扣是:9折");
	}
	else if (point < 4000)
	{
		System.out.println("该会员享受的的折扣是:8折");
	}
	else if (point < 8000)
	{
		System.out.println("该会员享受的的折扣是:7折");
	}
	else
	{
		System.out.println("该会员享受的的折扣是:6折");
	}	
}
 
Example 29
Project: HackerRank_solutions   File: Solution.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int t = scan.nextInt();
    for (int i = 0; i < t; i++) {
        try {
            long x = scan.nextLong();
            System.out.println(x + " can be fitted in:");
            if (x >= Byte.MIN_VALUE && x <= Byte.MAX_VALUE) {
                System.out.println("* byte");
            }
            if (x >= Short.MIN_VALUE && x <= Short.MAX_VALUE) {
                System.out.println("* short");
            }
            if (x >= Integer.MIN_VALUE && x <= Integer.MAX_VALUE) {
                System.out.println("* int");
            }
            if (x >= Long.MIN_VALUE && x <= Long.MAX_VALUE) {
                System.out.println("* long");
            }
        } catch (Exception e) {
            System.out.println(scan.next() + " can't be fitted anywhere.");
        }
    }
    scan.close();
}
 
Example 30
Project: codeforces   File: Problem_454A.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int size = in.nextInt();

    int middle = size / 2;
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            if (i <= middle) {
                if (j <= middle + i && j >= middle - i)
                    System.out.print("D");
                else
                    System.out.print("*");
            } else {
                if (j <= size - (i - middle) - 1 && j >= i - middle)
                    System.out.print("D");
                else
                    System.out.print("*");
            }
        }
        System.out.println();
    }
}
 
Example 31
Project: estrutura-de-dados   File: Principal.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner leitor = new Scanner(System.in);
	Pilha pilha = new Pilha();
	String msg = "1 - Adiciona\n2 - Remove\n3 - Exibe\n9 - Sair";
	int opc, e;

	do {
		System.out.println(msg);
		opc = leitor.nextInt();

		switch (opc) {
			case 1:
				System.out.print("Elemento: ");
				e = leitor.nextInt();
				pilha.adiciona(e);
				break;
			case 2:
				System.out.println("Removido: " + pilha.remove());
				break;
			case 3:
				pilha.exibe();
				break;
		}
	} while(opc != 9);
}
 
Example 32
Project: Java   File: DriverFactorial.java   Source Code and License 6 votes vote down vote up
public static void main(String []args)throws IllegalArgumentException
{
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter a number whose fctorial need to be found");
    int x=sc.nextInt();
    long fac=0;
    try{
        if(x>20)
        throw new IllegalArgumentException(x);
        if(x<0)
        throw new IllegalArgumentException();
        fac=fact(x);
        System.out.println("Factorial of "+x+" is : "+fac);
    }
    catch(Exception e)                 /*For exceptions other than range specification*/
    {
        System.out.println(e);
        System.out.println("Factorial can't be calculated because of some exception.");
    }
}
 
Example 33
Project: GitHub   File: RealmTests.java   Source Code and License 6 votes vote down vote up
private List<String> getCharacterArray() {
    List<String> chars_array = new ArrayList<String>();
    String file = "assets/unicode_codepoints.csv";
    Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(file), "UTF-8");
    int i = 0;
    String currentUnicode = null;
    try {
        while (scanner.hasNextLine()) {
            currentUnicode = scanner.nextLine();
            char[] chars = Character.toChars(Integer.parseInt(currentUnicode, 16));
            String codePoint = new String(chars);
            chars_array.add(codePoint);
            i++;
        }
    } catch (Exception e) {
        fail("Failure, Codepoint: " + i + " / " + currentUnicode + " " + e.getMessage());
    }
    return chars_array;
}
 
Example 34
Project: estrutura-de-dados   File: Ex7.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    double radius, height, vol;
    
    System.out.print("Raio do Cilindro: ");
    radius = input.nextDouble();
    System.out.print("Altura do Cilindro: ");
    height = input.nextDouble();
    input.close();
    
    vol = (Math.PI * Math.pow(radius, 2)) * height;
    System.out.printf("Volume do Cilindro: %.2f\n", vol);
}
 
Example 35
Project: java_mooc_fi   File: PositiveValue.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    // Type your program here:
    System.out.print("Type a number: ");
    int number = Integer.parseInt(reader.nextLine());
    
    System.out.println("");
    if (number > 0) {
        System.out.println("The number is positive.");
    } else {
        System.out.println("The number is not positive.");
    }
 
}
 
Example 36
Project: azure-maven-plugins   File: AddMojoTest.java   Source Code and License 5 votes vote down vote up
@Test
public void assureInputFromUser() throws Exception {
    final AddMojo mojo = getMojoFromPom();
    final AddMojo mojoSpy = spy(mojo);
    final Scanner scanner = mock(Scanner.class);
    doReturn("2").when(scanner).nextLine();
    doReturn(scanner).when(mojoSpy).getScanner();

    final Set<String> set = new HashSet<>();
    mojoSpy.assureInputFromUser("property", "", Arrays.asList("a0", "a1", "a2"), set::add);

    assertTrue(set.contains("a2"));
}
 
Example 37
Project: PatProject   File: Prob1026.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong();
        long b = scanner.nextLong();
        long timeResult = Math.round((b - a) / 100.0);
        System.out.printf("%02d:%02d:%02d", timeResult / 3600, (timeResult / 60) % 60, timeResult % 60);
//        System.out.print(+":"++":"+);
    }
 
Example 38
Project: HackerRank-in-Java   File: Solution.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int m = scan.nextInt();
        int n = scan.nextInt();

        double [][] X = new double[n][m + 1];
        double [][] Y   = new double[n][1];

        for (int row = 0; row < n; row++) {
            X[row][0] = 1;
            for (int col = 1; col <= m; col++) {
                X[row][col] = scan.nextDouble();
            }
            Y[row][0] = scan.nextDouble();
        }

        /* Calculating B */
        double [][] xtx    = multiply(transpose(X),X);
        double [][] xtxInv = invert(xtx);
        double [][] xty    = multiply(transpose(X), Y);
        double [][] B      = multiply(xtxInv, xty);

        int sizeB = B.length;

        /* Calculating values for "q" feature sets */
        int q = scan.nextInt();
        for (int i = 0; i < q; i++) {
            double result = B[0][0];
            for (int row = 1; row < sizeB; row++) {
                result += scan.nextDouble() * B[row][0];
            }
            System.out.println(result);
        }

        scan.close();
    }
 
Example 39
Project: hack   File: TwoStrings.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    int t = scanner.nextInt();

    for (int i = 0; i < t; i++) {
        int[] chars = new int[26];

        String a = scanner.next();

        String b = scanner.next();

        int n = a.length();
        if (n != b.length()) {
            System.out.println("NO");
        } else {
            for (int j = 0; j < n; j++) {
                chars[a.charAt(j) - 'a']++;
                chars[b.charAt(j) - 'a']--;
            }

            boolean found = true;

            for (int j = 0; j < 26; j++) {
                if (chars[j] != 0) {
                    System.out.println("NO");

                    found = false;

                    break;
                }
            }

            if (found) {
                System.out.println("YES");
            }
        }
    }
}
 
Example 40
Project: Homework   File: HibernateTest.java   Source Code and License 5 votes vote down vote up
@Test
public void adoptPet()
{
	Scanner input = new Scanner(System.in);
	LOGGER.info("欢迎光临宠物乐园");
	LOGGER.info("请输入登录名:");
	String username = input.next();
	LOGGER.info("请输入密码:");
	String password = input.next();
	
	Master master = new Master(username, password);

	MasterDao mas = new MasterDaoImpl(session, tx);
	MasterServiceImpl masterService = new MasterServiceImpl(mas);
	if(masterService.login(master))
	{
		LOGGER.info("登录成功!");
		Pet pet = new Pet();
		pet.setName("旺财");
		pet.setMaster(master);
		PetType pt = new PetType();
		pt.setName("狗狗");
		session.persist(pt);
		pet.setPetType(pt);
		masterService.adoptPet(pet);
	}
	else 
	{
		LOGGER.info("登录失败!");
	}
}
 
Example 41
Project: 3way_laboratorios   File: Ex4.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	// entrada = valor da compra
	// Seria o prompt do java script
	Scanner sc = new Scanner(System.in);
	System.out.println("Digite o valor da compra:");
	double valorCompra = sc.nextDouble();
	
	// processamento = saber qual é o valor da parcela
	double valorParcela = valorCompra / 5;
	
	// saida = valor da parcela
	System.out.println("Valor da parcela = "+ valorParcela);
}
 
Example 42
Project: ibm-cos-sdk-java   File: BasicProfileConfigLoader.java   Source Code and License 5 votes vote down vote up
/**
 * Loads the credential profiles from the given input stream.
 *
 * @param is input stream from where the profile details are read.
 */
private AllProfiles loadProfiles(InputStream is) throws IOException {
    ProfilesConfigFileLoaderHelper helper = new ProfilesConfigFileLoaderHelper();
    Map<String, Map<String, String>> allProfileProperties = helper
            .parseProfileProperties(new Scanner(is, StringUtils.UTF8.name()));

    // Convert the loaded property map to credential objects
    Map<String, BasicProfile> profilesByName = new LinkedHashMap<String, BasicProfile>();

    for (Entry<String, Map<String, String>> entry : allProfileProperties.entrySet()) {
        String profileName = entry.getKey();
        Map<String, String> properties = entry.getValue();

        if (profileName.startsWith("profile ")) {
            LOG.warn(
                    "The legacy profile format requires the 'profile ' prefix before the profile name. " +
                    "The latest code does not require such prefix, and will consider it as part of the profile name. " +
                    "Please remove the prefix if you are seeing this warning.");
        }

        assertParameterNotEmpty(profileName,
                                "Unable to load properties from profile: Profile name is empty.");
        profilesByName.put(profileName, new BasicProfile(profileName, properties));
    }

    return new AllProfiles(profilesByName);
}
 
Example 43
Project: jarn   File: YarnTreeParser.java   Source Code and License 5 votes vote down vote up
private YarnNode readNodeHeader(Scanner scanner) {
	String title = scanner.nextLine().replace("title:", "").trim();
	String[] tags = scanner.nextLine().replace("tags:", "").split(" ");
	// Skip color
	scanner.nextLine();
	// Skip position
	scanner.nextLine();
	// Skip header end
	scanner.nextLine();
	return new YarnNode(title, tags);
}
 
Example 44
Project: Homework   File: Regesit.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) 
{
	Scanner sc = new Scanner(System.in);
	Regesit regesit1 = new Regesit();

	do
	{
		System.out.print("请输入用户名:");
		regesit1.userName = sc.next();
		System.out.print("请输入密码:");
		regesit1.password = sc.next();
		if (!regesit1.regesit(regesit1.userName, regesit1.password))
		{
			System.out.println("用户名长度不能小于3,密码长度不能小于6!");
		}
		else 
		{
			System.out.print("请再输入密码:");
			if (regesit1.regesit(sc.next()))
			{
				System.out.print("注册成功,请记住用户名和密码");
				break;
			}
		}
	}
	while(true);

}
 
Example 45
Project: Hacktoberfest-Mathematics   File: standard_deviation.java   Source Code and License 5 votes vote down vote up
public static void main(String [] args){

        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());
        int [] population = new int[n];
        for(int i = 0;i<n;i++){
            population[i] = scanner.nextInt();
        }

        double deviation = calculateDeviation(population,n);
        System.out.println(deviation);
    }
 
Example 46
Project: Alfred   File: Alfred.java   Source Code and License 5 votes vote down vote up
static void printData(File file) throws FileNotFoundException {
	out = new Scanner(file);
	while (out.hasNext())
		System.out.println(out.nextLine());
}
 
Example 47
Project: Homework   File: Pet.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args)
{
	Scanner sc = new Scanner(System.in);	

	Penguin p = new Penguin();
	Dog d = new Dog();

	System.out.println("欢迎来到宠物店");
	System.out.print("请输入要领养宠物的名字:");
	String name = sc.next();
	
	System.out.print("请输入要领养宠物的类型(1、狗狗 2、企鹅):");
	switch(sc.nextInt())
	{
		case 1:
			d.setName(name);
			System.out.print("请狗狗的品种:(1、聪明的拉布拉多 2、酷酷的雪瑞娜)");
			switch(sc.nextInt())
			{
				case 1:
					d.setStrain("聪明的拉布拉多");
					break;
				case 2:
					d.setStrain("酷酷的雪瑞娜");
					break;
			}
			
			System.out.print("请输入狗狗的健康值:");
			int health = sc.nextInt();
			if (health < 1 || health > 100)
			{
				System.out.println("健康值应该在1至100之间,默认值为60.");
			}else
			{
				d.setHealth(health);
			}
			d.show();
			break;
		case 2:
			p.setName(name);
			System.out.print("请企鹅的性别:(1、Q仔 2、Q妹)");
			switch(sc.nextInt())
			{
				case 1:
					p.setSex(Penguin.SEX_FEMALE);
					break;
				case 2:
					p.setSex(Penguin.SEX_MALE);
					break;
			}
			
			System.out.print("请输入企鹅的健康值:");
			health = sc.nextInt();
			if (health < 1 || health > 100)
			{
				System.out.println("健康值应该在1至100之间,默认值为60."); 
			}else
			{
				p.setHealth(health);
			}
			p.show();
			break;

	}
	

}
 
Example 48
Project: Homework   File: Series.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args)
{  
   int[] list = new int[]{8, 4, 2, 1, 23, 344, 12};  
  	for (int i = 0; i < list.length; i++) 
   {  
       System.out.println(list[i]);  
   }  
   int sum = 0;  
  	for (int i = 0; i < list.length; i++) 
   {  
       sum = sum + list[i];  
   }
   	System.out.println("和是:" + sum);


	Scanner input = new Scanner(System.in);  
 	 	System.out.print("请输入一个整数: ");  
   	int guess = input.nextInt();  
 		boolean isCorrect = false;  
   for (int i = 0; i < list.length; i++)
    {  
      if (guess == list[i])
       {  
           isCorrect = true;  
           break;  
       }  

  		}  
  	 	if (isCorrect)
  		{  
  	     System.out.println("猜对了!");  
  		} 
  	 	else 
   	{  
       System.out.println("Sorry!");  
   	}  
    }
 
Example 49
Project: codeforces   File: Problem_839A.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int days = in.nextInt();
    int total_candies = in.nextInt();

    int result = -1;

    if (days * 8 >= total_candies) {
        int sum = 0, remaining = 0;
        for (int i = 0; i < days; i++) {
            int tmp = in.nextInt();
            if (tmp > 8) {
                sum += 8;
                remaining += tmp - 8;
            } else {
                int additional;
                if (remaining > 8 - tmp) {
                    additional = 8 - tmp;
                    remaining -= 8 - tmp;
                } else {
                    additional = remaining;
                    remaining = 0;
                }
                sum += tmp + additional;
            }

            if (sum >= total_candies) {
                result = i + 1;
                break;
            }
        }
    }

    System.out.print(result);
}
 
Example 50
Project: HackerRank-Studies   File: Solution.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	try (
			Scanner in = new Scanner(System.in);
			PrintWriter out = new PrintWriter(System.out);
	) {
		int n = in.nextInt();
		ArrayList<Integer> aList = new ArrayList<>();
		int result = 0;
		assert (n >= 1 && n <= 100);

		// set elements in aList
		for (int i = 0; i < n; i++) {
			int a = in.nextInt();

			// validation and set an element in aList
			if (a >= -1000 && a <= 1000) {
				aList.add(a);
			} else {
				assert (false);
			}
		}

		// solution
		for (int i = 0; i < n; i++) {
			int sum = 0;
			for (int j = i; j < n; j++) {
				sum += aList.get(j);

				// if sum is a negative value, plus one to result value
				if (sum < 0) {
					result++;
				}
			}
		}

		out.println(result);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 51
Project: Homework   File: OOEX01.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args)
{
	Scanner sc = new Scanner(System.in);	
	Pet dog = new Dog();
	dog.show();
	
}
 
Example 52
Project: i_stolbov   File: FileManagerClient.java   Source Code and License 5 votes vote down vote up
/**
 * start.
 * @param socket - socket
 * @throws IOException - IOException
 */
public void start(Socket socket) throws IOException {
    String message;
    Command cmd;

    InputStream inputStream = socket.getInputStream();
    OutputStream outputStream = socket.getOutputStream();

    DataInputStream dis = new DataInputStream(inputStream);
    DataOutputStream dos = new DataOutputStream(outputStream);

    CommandFactoryClient factory = new CommandFactoryClient(inputStream, outputStream);

    Scanner console = new Scanner(System.in);

    if (SUCCESS.equals(dis.readUTF())) {
        System.out.println("FileManager is ready to work.");
        factory.show();
        do {
            System.out.print("Command: ");
            message = console.nextLine();
            if (!EXIT.equals(message)) {
                cmd = new Command(message);
                factory.run(cmd);
            } else {
                dos.writeUTF(EXIT);
                dos.flush();
            }
        } while (!EXIT.equals(message));
    }
}
 
Example 53
Project: Password-Connector   File: PasswordConnector.java   Source Code and License 5 votes vote down vote up
/**
 * Initializing and starting
 * program.
 */
public PasswordConnector(){
	
	// initialize
	scan = new Scanner(System.in);
	manager = Manager.getInstance(scan);
	
	System.out.print("\n$$Welcome at Password Connector$$\n\n"
			+ "**Please provide password to login into the system..\[email protected]> ");
	
	// Making user to login.
	manager.login();
	start();
	
}
 
Example 54
Project: Homework   File: TestScore.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args)
{
	ScoreCalc scoreCalc = new ScoreCalc();
	Scanner sc = new Scanner(System.in);
	System.out.print("请输入Java成绩:");
	scoreCalc.javaScore = sc.nextInt();
	System.out.print("请输入C#成绩:");
	scoreCalc.cSharpScore = sc.nextInt();
	System.out.print("请输入DB成绩:");
	scoreCalc.dbScore = sc.nextInt();
	System.out.println("总成绩是:"+ scoreCalc.calcSum());
	System.out.println("平均分是:"+ scoreCalc.calcAvg());
	sc.close();
}
 
Example 55
Project: HackerRank_solutions   File: Solution.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    while (n-- > 0) {
        int grade = scan.nextInt();
        System.out.println(roundGrade(grade));
    }
    scan.close();
}
 
Example 56
Project: HackerRank_solutions   File: Solution.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int s = scan.nextInt();
    int[] array = new int[s];
    for (int i = 0; i < s; i++) {
        array[i] = scan.nextInt(); 
    }
    scan.close();
    insertionSort(array);
}
 
Example 57
Project: codeforces   File: Problem_122A.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int input = in.nextInt();
    String result = "NO";
    int[] array = {4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777};

    for (int anArray : array) {
        if (input % anArray == 0) {
            result = "YES";
            break;
        }
    }

    System.out.print(result);
}
 
Example 58
Project: HackerRank_solutions   File: Solution.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    int j = scan.nextInt();
    int k = scan.nextInt();
    scan.close();

    int count = 0;
    for (int num = i; num <= j; num++) {
        if (Math.abs(num - reverse(num)) % k == 0) {
            count++;
        }
    }
    System.out.println(count);
}
 
Example 59
Project: java_mooc_fi   File: FirstPart.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    
    System.out.print("Type a word: ");
    String word = reader.nextLine();
    System.out.println("");
    
    System.out.print("Length of the first part: ");
    int index = Integer.parseInt(reader.nextLine());
    System.out.println("");
    
    System.out.println("Result: " + word.substring(0, index));
}
 
Example 60
Project: estrutura-de-dados   File: Ex2.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n1, n2, sum;
    
    System.out.print("Informe o 1º valor: ");
    n1 = input.nextInt();
    System.out.print("Informe o 2º valor: ");
    n2 = input.nextInt();
    input.close();
    sum = n1 + n2;
    System.out.printf("\n%d + %d = %d\n", n1, n2, sum);
}